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
docs(freshness): re-verify the 174 stale docs against the code they describe and correct 164
nirholasb6194ae821cb
diff --git a/README.md b/README.mdindex 6c4a15e3d..109d265f7 100644--- a/README.md+++ b/README.md@@ -9994,7 +9994,7 @@ The full OpenAPI 3.1 spec is available at `/openapi.json`. The key API surface iCron schedules are declared in `vercel.json` (still the live cron/route config the server reads) and executed in production by **Google Cloud Scheduler**, which calls each endpoint on its schedule. All cron endpoints are fail-closed — a missing auth token aborts with an error rather than silently skipping (see [Security Hardening](#security-hardening)).-The crons in `vercel.json` (110 entries on 2026-08-28) are routed through a single dynamic handler at [`api/cron/[name].js`](api/cron/[name].js); the `name` segment selects the handler function. Scheduler jobs are provisioned from the `vercel.json` cron list via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs). The table below is a selection of the notable jobs, each schedule quoted verbatim from `vercel.json`; that file is the complete list.+The crons in `vercel.json` (111 entries on 2026-09-01) are routed through a single dynamic handler at [`api/cron/[name].js`](api/cron/[name].js); the `name` segment selects the handler function. Scheduler jobs are provisioned from the `vercel.json` cron list via [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs). The table below is a selection of the notable jobs, each schedule quoted verbatim from `vercel.json`; that file is the complete list.| Schedule | Endpoint | Purpose || -------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |@@ -10261,7 +10261,7 @@ three.ws is available on major cloud marketplaces and open to infrastructure par| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- || **AWS** | **AWS Partner** (APN Software Path). AWS Marketplace SaaS listing in review: see [docs/aws-marketplace.md](docs/aws-marketplace.md) and the public partner page at [three.ws/aws](https://three.ws/aws). Part of the stack runs on AWS `us-east-1` (the Forge sculptor Lambda `three-ws-forge` and the S3 avatar bucket), registered in AWS MyApplications under account `155407237916` (the main app runs on Google Cloud Run). We publish engineering write-ups on the AWS Builder Center as [@threews](https://builder.aws.com/community/@threews); the index is [docs/aws-builder-center.md](docs/aws-builder-center.md). || **Alibaba Cloud** | Live: [product listing →](https://marketplace.alibabacloud.com/products/56724001/sgcmfw00036800.html) · [storefront →](https://marketplace.alibabacloud.com/store/3247293.html) |-| **Google Cloud** | Production runs on **Google Cloud Run** (`three-ws-api`, `us-central1`) fronted by a global HTTPS load balancer + Cloud CDN, with all 101 scheduled jobs on Cloud Scheduler and GPU inference workers on Cloud Run: a natural fit for GCP's AI infrastructure and Vertex AI. Open to co-listing, credits, and joint GTM. |+| **Google Cloud** | Production runs on **Google Cloud Run** (`three-ws-api`, `us-central1`) fronted by a global HTTPS load balancer + Cloud CDN, with all 110 scheduled jobs on Cloud Scheduler and GPU inference workers on Cloud Run: a natural fit for GCP's AI infrastructure and Vertex AI. Open to co-listing, credits, and joint GTM. |## Ecosystem Directories@@ -10660,7 +10660,7 @@ three.ws ships in five phases. Each phase closes a specific gap between the curr| **2** | Agent personalization + voice cloning | 🟡 In progress — voice clone, persona, memory seeds shipped behind `/demos`; main-flow integration next || **3** | Onchain economy (agent tokens, reputation markets, royalties) | 🟡 In progress: bonding-curve sim, EAS-reputation viewer, 0xsplits + EAS SDKs landed; per-call skill royalties accrue on paid skill calls (`royalty_ledger`); contracts + audits next || **4** | Open inference network (decentralized GPU layer) | 🟡 Live core: open node-operator client (CPU + CUDA images) + `/api/nodes` job queue with signed, server-recomputed receipts shipped; Livepeer federation behind a flag |-| **5** | Native widgets (agent on your home screen and desktop) | 🟡 In progress: Glance shipped the card endpoint, the Windows 11 widget (installs from the PWA manifest, no store) and the `<agent-glance>` element; Android app widget next, then macOS and iOS |+| **5** | Native widgets (agent on your home screen and desktop) | 🟡 In progress: Glance shipped the card endpoint (JSON, SVG, PNG, Adaptive Card), the Windows 11 widget (installs from the PWA manifest, no store), the `<agent-glance>` element, and the Android home screen widget (app 1.1.0, linked from `/glance` with its own revocable token); macOS and iOS next |---@@ -10783,21 +10783,21 @@ This is a different product from the embeddable web widgets at [three.ws/widgets| # | Surface | Shell needed | Status || - | ------- | ------------ | ------ || 1 | Windows 11 widgets board | None | **Shipped.** The installed PWA declares a `widgets` manifest member and an Adaptive Card template ([/api/glance/template](api/glance/template.js)); the service worker ([public/glance-sw.js](public/glance-sw.js)) answers `widgetinstall`, `widgetresume`, `widgetclick` and `periodicsync` |-| 2 | Any web page | None | **Shipped.** `<agent-glance>` ([public/glance/element.js](public/glance/element.js)), plus one SVG URL for a README, a Slack unfurl, or any `<img>` |-| 3 | Android home screen | Already shipped (`ws.three.app`) | Next. Native `AppWidgetProvider` overlay added to the Bubblewrap project, refreshed by `WorkManager`, tapping deep links into the TWA. The card endpoint it needs is live |+| 2 | Any web page | None | **Shipped.** `<agent-glance>` ([public/glance/element.js](public/glance/element.js)), plus one SVG or PNG URL for a README, a Slack unfurl, or any `<img>` |+| 3 | Android home screen | Already shipped (`ws.three.app`) | **Shipped** in app 1.1.0. Native `AppWidgetProvider` overlay on the Bubblewrap project ([solana-mobile/android-overlay](solana-mobile/android-overlay/README.md)) in a 2x2 and a 4x2 / 4x3 layout, refreshed by `WorkManager` from `GET /api/glance/mine?format=png` about every 30 minutes, keeping the last card when the phone is offline, tapping deep links into the TWA. It carries its own `glw_` widget token, linked from [/glance](public/glance/index.html) ("Link this phone") and revocable there at any time || 4 | macOS | Small SwiftUI host app | WidgetKit extension plus a menu bar companion; needs an Apple Developer account || 5 | iOS | App Store wrapper | Same WidgetKit extension target as macOS; gated on shipping the iOS app itself |**Deliverables**-- ✅ A cacheable card endpoint, [/api/glance/card](api/glance/card.js), serving one model as JSON, SVG and Adaptive Card, plus [/api/glance/mine](api/glance/mine.js) for the signed-in owner's own agent. Spec: [specs/GLANCE_CARD.md](specs/GLANCE_CARD.md)+- ✅ A cacheable card endpoint, [/api/glance/card](api/glance/card.js), serving one model as JSON, SVG, PNG and Adaptive Card, plus [/api/glance/mine](api/glance/mine.js) for the owner's own agent, authenticated by the session cookie or by a widget's own bearer token, and answering every state (signed out, widget unlinked, no agent yet) as a designed card rather than a 401. Spec: [specs/GLANCE_CARD.md](specs/GLANCE_CARD.md)- ✅ Windows 11 widget through the PWA manifest, so it installs with no separate store submission, degrading to the last cached card when the machine is offline and to a sign-in card when nobody is signed in- ✅ Card content that is worth a home screen slot: the agent, one live number (actions in the last 24 hours), its last action, and a direct way back in- ✅ A playground and install guide at [/glance](public/glance/index.html), and an npm client, [@three-ws/agent-glance](packages/agent-glance), with a terminal renderer-- Android app widget in three sizes, refreshed on a battery-aware schedule, degrading to the last cached card when the device is offline+- ✅ Android app widget in two layouts (2x2, and 4x2 / 4x3), refreshed by WorkManager on a battery-aware schedule, degrading to the last cached card when the device is offline- A native shell for Apple platforms, which is also the prerequisite for an iOS build of three.ws-**Verification:** a widget installed from the Android app updates without opening the app, survives a reboot and airplane mode, and returns the user into the right screen on tap. Work order: [prompts/roadmap/native-widgets.md](prompts/roadmap/native-widgets.md).+**Verification:** a widget installed from the Android app updates without opening the app, survives a reboot and airplane mode, and returns the user into the right screen on tap. Product doc: [docs/native-widgets.md](docs/native-widgets.md). Work order: [prompts/roadmap/native-widgets.md](prompts/roadmap/native-widgets.md).---@@ -11076,7 +11076,7 @@ npm run build # frontend build to dist/ (only when frontend changed)npm run deploy:gcp # check:dist + db:check, gcloud builds submit, purge CDN```-`npm run deploy:gcp` runs `gcloud builds submit --config server/cloudbuild.yaml`. Routing, cache headers, and cron schedules are defined in `vercel.json`, which the server reads at runtime. The scheduled jobs (105 at time of writing, one per entry in the `crons` array of `vercel.json`) run on **Cloud Scheduler** (provisioned by [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs)); the GPU inference workers run as their own Cloud Run services. Full ops runbook (load balancer, DNS/TLS, env, rollback, recovery): **[docs/ops/gcp-production.md](docs/ops/gcp-production.md)**.+`npm run deploy:gcp` runs `gcloud builds submit --config server/cloudbuild.yaml`. Routing, cache headers, and cron schedules are defined in `vercel.json`, which the server reads at runtime. The scheduled jobs (110 at time of writing, one per entry in the `crons` array of `vercel.json`) run on **Cloud Scheduler** (provisioned by [scripts/create-gcp-scheduler.mjs](scripts/create-gcp-scheduler.mjs)); the GPU inference workers run as their own Cloud Run services. Full ops runbook (load balancer, DNS/TLS, env, rollback, recovery): **[docs/ops/gcp-production.md](docs/ops/gcp-production.md)**.**Environment variables** live on the Cloud Run service, not in `.env` files — inspect or update them with `gcloud run services describe/update three-ws-api --region us-central1`. See [Environment Variables](#environment-variables) for the full list.diff --git a/data/changelog.json b/data/changelog.jsonindex f10ffb085..adb2ce76e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -25391,6 +25391,16 @@"improvement"],"link": "/stage"+ },+ {+ "date": "2026-09-01",+ "title": "Documentation sweep: 164 docs re-checked against the code they describe",+ "summary": "Every doc the freshness gate flagged as describing code that had moved since it was written (174 of them, from the UX flow walkthroughs and the Oracle model write-up to the ops runbooks, tutorials, and the agent-abilities chapters) was re-read against the current code. 164 were corrected or extended: renamed routes now point at /agents/:id, retired model names and provider ladders are current, counts and thresholds match what ships, and the resilience work of the last month (last-good caches, typed 503s with Retry-After, the RPC read guards) is described where it applies. Along the way three things the docs promised were made true in the product: the Herald posting scope can now be minted from the dashboard key form, the translation script defaults to a Groq model that still exists, and the home page OpenAPI link opens the spec directly.",+ "tags": [+ "docs",+ "fix"+ ],+ "link": "/docs/freshness"}]}diff --git a/docs/3d-asset-pipeline.md b/docs/3d-asset-pipeline.mdindex 7a977f762..247d8c233 100644--- a/docs/3d-asset-pipeline.md+++ b/docs/3d-asset-pipeline.md@@ -124,7 +124,7 @@ npm run optimize:glb # every GLB in assets/, publnpm run optimize:glb -- --dry # report only, no writes```-Source: [scripts/optimize-glb.mjs](../scripts/optimize-glb.mjs). Lossless geometry passes (`dedup`, `prune`, `weld`, `resample`) plus a WebP texture re-encode. Output stays within the **standard glTF 2.0 feature set** — no `KHR_draco_mesh_compression`, no `EXT_meshopt_compression` — so it loads in every `GLTFLoader` on the site without wiring a decoder. Typical result: **−90%** file size.+Source: [scripts/optimize-glb.mjs](../scripts/optimize-glb.mjs). Lossless geometry passes (`dedup`, `prune`, `weld`, `resample`) plus a WebP texture re-encode. Compressed inputs are fine: the script registers the meshopt and Draco codecs with gltf-transform, so an `EXT_meshopt_compression` or `KHR_draco_mesh_compression` avatar (most of the ones in production) decodes instead of failing with "Please install extension dependency". Output stays within the **standard glTF 2.0 feature set** (the compression extensions are stripped after decoding, never re-encoded) so it loads in every `GLTFLoader` on the site without wiring a decoder. Typical result: **-90%** file size.### The format reference@@ -164,7 +164,7 @@ The build pipeline produces GLB + JSON; the browser stitches them back together.| Stage | Module | What it does ||---|---|---|-| Load a GLB | [src/viewer.js](../src/viewer.js) | `GLTFLoader` (with DRACO/KTX2 support) loads the model, frames the camera, builds raycasting BVH, emits the scene to the animation panel. |+| Load a GLB | [src/viewer.js](../src/viewer.js) | `GLTFLoader` (with DRACO/KTX2/meshopt support) loads the model, frames the camera in front of the rig's face (`estimateFacingYaw` in `src/viewer/facing.js` reads which way the skeleton was authored to face, so a -Z or +X rig is not framed from behind), builds raycasting BVH, emits the scene to the animation panel. || Normalize an uploaded rig | [src/glb-canonicalize.js](../src/glb-canonicalize.js) | Rewrites bone names in the GLB JSON chunk to canonical form (see [the supported conventions](#supported-rig-conventions) below), folds the Mixamo +90°X armature rotation into children, repacks the GLB. || Load a clip | [src/animation-manager.js](../src/animation-manager.js) | Fetches clip JSON, `AnimationClip.parse`, drives playback through a `THREE.AnimationMixer` with crossfades (0.35s default), one-shot + settle, and a "fallen pose" safety guard. || Retarget a clip to the loaded rig | [src/animation-retarget.js](../src/animation-retarget.js) | Renames canonical tracks to the rig's actual bone names, applies per-bone bind-pose correction (`C = targetRest · sourceRest⁻¹`), rescales hip translation by height ratio, drops the clip if coverage < 50%. |@@ -188,6 +188,7 @@ There is **no rig allowlist**. [src/glb-canonicalize.js](../src/glb-canonicalize| Unreal mannequin | `pelvis`, `clavicle_l`, `upperarm_l`, `thigh_l`, `calf_l`, `ball_l` || VRM 0.x / VRoid | `J_Bip_C_Hips`, `J_Bip_L_UpperArm`, `J_Bip_L_Little1` || VRM 1.0 | `leftUpperArm`, `rightLowerLeg`, `upperChest`, `leftToes` |+| MikuMikuDance (PMX/PMD) | `センター`, `上半身`, `首`, `左腕`, `左ひじ`, `左ひざ` (Japanese names, `左`/`右` side prefix) || UniGLTF / VRM converter | `5.joint_HipMaster`, `10.!joint_LeftToe` || Daz3D / Genesis | `hip`, `abdomen`, `lShldr`, `lThigh`, `lShin`, `lCollar` || Reallusion CC3 / CC4 | `CC_Base_Hip`, `CC_Base_L_Upperarm`, `CC_Base_NeckTwist01` |@@ -209,6 +210,7 @@ Vendor prefixes (`mixamorig:`, `CC_Base_`, `Bip01 `, `j_`, Maya namespaces) and- **Non-humanoid skeletons** (quadrupeds, prop rigs) — no safe correspondence exists.- **End effectors and leaf tips** (`HeadTop_End`, `LeftToe_End`, `LeftHandIndex4`) — the clip library drives no such bone.- **Metacarpals** (`Palm1.L`) — the canonical set has no metacarpal.+- **MMD IK targets and twist bones** (`左足IK`, `左つま先IK`, `左腕捩`, `左手捩`). MMD drives the leg chain from the IK target, so binding a clip to it would fight the chain it solves, and the twist bones are secondary deformers that tear the mesh when rotated as a limb.- **Constraint-driven control rigs** (Auto-Rig-Pro / `cwf_` + `def_` + tracker families). Their deform bones are *leaves* hanging off tracker nodes — `def_arm_1.R` is not a child of `def_arm_0.R` — and glTF has no constraint system, so the Copy-Rotation/Damped-Track constraints that made the rig work in Blender are dropped at export. Rotating a mapped `def_` bone would move its own skin while the next segment stayed put, tearing the limb apart. These fall back to the default rig; the remedy is re-rigging through [workers/rig](../workers/rig), not name mapping.### Measuring coverage against real avatars@@ -286,7 +288,7 @@ text/image ──► mesh_forge ──► static GLB ──► rig_mesh ──- **Don't ship raw converted GLBs.** A Mixamo character converts to 50+ MB; always run `optimize:glb`. The site streams these to every visitor.- **`trimesh` (the Python script) silently drops rigs.** It is for static geometry only. For anything animated, use `convert:fbx`.-- **No Draco/meshopt in optimized output.** The main viewer and the studios wire Draco/KTX2/meshopt decoders (`getDecoders` in `src/viewer/internal.js`), but many lighter surfaces load GLBs with a bare `GLTFLoader` and no decoder. `optimize:glb` deliberately stays within plain glTF 2.0 so its output loads everywhere; WebP textures do the heavy lifting.+- **No Draco/meshopt in optimized output.** The main viewer and the studios wire Draco/KTX2/meshopt decoders (`getDecoders` in `src/viewer/internal.js`, which serves the decoder binaries from our own origin under `public/three/`, vendored by `scripts/copy-three-decoders.mjs` on every install and checked by `scripts/audit-deploy-artifacts.mjs` at deploy, with unpkg only as the backstop when a HEAD probe of the local copy fails), but many lighter surfaces load GLBs with a bare `GLTFLoader` and no decoder. `optimize:glb` deliberately stays within plain glTF 2.0 so its output loads everywhere; WebP textures do the heavy lifting.- **FBX is build-time only.** Keep source FBX in `animation-sources/` (gitignored) so it never ships in the deploy bundle. `public/animations/` holds no FBX anymore; the six formerly-orphaned clips are built into the manifest (see `resolved_issues` in [public/animations/registry.json](../public/animations/registry.json)).- **Bone names matter.** A non-humanoid or oddly-named rig may fall below the 8-bone / 50%-coverage thresholds and refuse to animate. The canonicalizer handles the common conventions; truly custom skeletons need their bones renamed to the canonical set first.- **`.bak` files.** `optimize:glb` writes a `<name>.glb.bak` alongside its output — delete it before committing.diff --git a/docs/agent-abilities/ABILITIES.md b/docs/agent-abilities/ABILITIES.mdindex daea497ae..f7897b597 100644--- a/docs/agent-abilities/ABILITIES.md+++ b/docs/agent-abilities/ABILITIES.md@@ -346,7 +346,7 @@ Editing an agent feels like directing a living character, not filling in a databYou don't write a system prompt — you direct a character. Compose the agent's reasoning as a visual card-stack graph, fork ready-made brains (Sniper, Scalper, Researcher, Companion), tune trait sliders and tone chips, and test it in a streaming chat against the real model. A/B compare runs genuine dual inference side by side; promoting the winner writes a real versioned update and the agent re-greets everywhere on the platform.-A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history.+A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history. Every persona save also signs the agent's full manifest, system prompt included, and pins it to IPFS, so anyone can fetch the CID and verify what the agent is running without an account ([Agent manifest](/docs/agent-manifest)).Personality engineering becomes tactile and testable — you feel the change in the agent's voice within a second instead of guessing at prompt wording.@@ -386,7 +386,7 @@ Shaping what your agent can do — and what it charges for doing it — is a setThe power-user editing surface for any agent you own, with fifteen-plus tabs covering everything: outfit, voice, knowledge, brain, mind, ownership, dreams, skills, autopilot, embeds, widgets, social, analytics, and wallet. It also builds subscription plans that bundle an agent's skills into recurring offers.-A tabbed single-page console over the agent APIs at /agent/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.+A tabbed single-page console over the agent APIs at /agents/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.Every dial an agent has is reachable from one page — nothing about your agent is hidden from you.@@ -408,11 +408,11 @@ Your agent grows on its own and shows you its inner life — coming back to it f## Live name check and naming rules-As you name or rename an agent, availability is checked live against the whole platform — taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3–32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.+As you name or rename an agent, availability is checked live against the other agents you own: taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3-32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.-A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness (with self-exclusion when renaming), consumed by the creation and editing flows.+A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness within your account (with self-exclusion when renaming, and a 400 instead of a server error when the agent_id is not a uuid), consumed by the creation and editing flows.-You never lose work to a name collision at the last step, and every agent name on the platform is unique and legible.+You never lose work to a name collision at the last step, and every agent name you own is unique and legible.## Selfie → 3D avatar@@ -466,7 +466,7 @@ Personalization without a full photo-reconstruction pipeline: your features, appAny un-rigged 3D mesh — something you generated, bought, or modeled — can be turned into an animation-ready avatar in one click. The platform builds a skeleton into it so it can walk, dance, and emote with the full animation library. The original is never touched: rigging produces a new sibling avatar.-Routes the mesh through the auto-rig backend (the self-hosted Make-It-Animatable rig worker on GPU infrastructure with a Replicate fallback), polls the job, canonicalizes the resulting bone names to the universal skeleton, and registers the rigged result as a new owned avatar.+Routes the mesh through the auto-rig backend (the self-hosted Make-It-Animatable rig worker on GPU infrastructure, with a Replicate fallback when a rerig model is configured), polls the job, canonicalizes the resulting Mixamo-named bones to the universal skeleton, and registers the rigged result as a new owned avatar.No model is a dead end — every statue you own can become a living character.@@ -594,7 +594,7 @@ One model becomes a whole product line of finishes — non-destructively, with eOne click turns any studio output — a forged avatar, a Lab model — into a live conversational agent: it listens, thinks, answers out loud in a real voice, and lip-syncs while it speaks, with per-agent memory carrying across the conversation.-Hands the model to the platform's production conversational stack — streaming LLM chat, TTS with provider failover (NVIDIA Magpie → OpenAI), and a lip-sync driver on the avatar's mouth morphs — the same runtime the rest of the site uses.+Hands the model to the platform's production conversational stack, the same runtime the rest of the site uses: streaming LLM chat over a failover chain of six free provider lanes (Groq, OpenRouter, NVIDIA NIM, SambaNova, Mistral, Z.AI) ahead of any paid backstop, which answers a fully throttled free lane with a 503 and a Retry-After rather than a sign-in wall; TTS with provider failover (NVIDIA Magpie → OpenAI); and a lip-sync driver on the avatar's mouth morphs.The moment of magic: the thing you just created looks at you and talks back.@@ -624,9 +624,9 @@ You never have to choose between making a character and making an agent — ever## Agent Genome-Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents — brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed — the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners can list agents at stud for a $THREE fee, and breeding cooldowns keep rare pedigrees scarce.+Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents: brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed: the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners list their own public agents at stud for a $THREE fee from the studio's "Your stud listings" section (unlist any time), and breeding cooldowns keep rare pedigrees scarce.-The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child — the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key — replaying a preview returns the same child, never twins. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market.+The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child: the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key: replaying a preview returns the same child, never twins, a race on the same key or the same $THREE settlement signature is decided by the database's unique indexes with the losing child retired (so one stud payment can never buy two children), and cooldown is checked before the fee gate so a refused breeding never takes a payment. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market and the owner's listing writes, with PATCH semantics so sending only a fee never unlists the agent.Creation stops being a one-shot generator and becomes lineage. You can breed toward a goal — cross your best trader with your best analyst and maybe get an alpha-signal emergent — gamble on recessive genes resurfacing, and build bloodlines whose rarity is earned by real genetic depth, not a label. Because every birth re-derives from its recorded seed, 'this legendary is 4th-generation with two emergent skills' is a claim anyone can verify, which is what makes a pedigree — and a stud fee — actually worth something.@@ -634,7 +634,7 @@ Creation stops being a one-shot generator and becomes lineage. You can breed tow# Chapter 4 · The Mind-Agents remember, reflect, and act on their own — with every autonomous action explained, signed, and undoable. Owners drive it from the Autopilot tab of the agent editor (/agent/:id/edit) and audit it at three.ws/autopilot-activity.+Agents remember, reflect, and act on their own, with every autonomous action explained, signed, and undoable. Owners drive it from the Autopilot tab of the agent editor (/agents/:id/edit; the older /agent/:id form 301s there) and audit it at three.ws/autopilot-activity.three.ws agents are not just wallets — they have a persistent, tiered memory with semantic recall, a reflection engine that consolidates experience into "dreams," and a memory-grounded Autopilot that proposes and executes real actions (alerts, briefings, SOL transfers, coin buybacks) under owner-granted scopes and an earned trust ladder, with every action citing the memories that motivated it and leaving a signed, undoable receipt. Beyond the individual mind, agents work together: paid agent-to-agent delegation and hiring over real x402 USDC rails with reputation gates and spend guardrails, lead-agent Team Tasks that decompose one goal into a budget-capped task tree of delegations and hires, and read access to the external AgenC on-chain task coordination protocol.@@ -642,7 +642,7 @@ three.ws agents are not just wallets — they have a persistent, tiered memory wThe agent reads its own high-salience memories and recent reflections and turns them into concrete, real action proposals — create a price/graduation/whale alert, author a briefing to the owner's inbox, or transfer SOL from its custodial wallet. The owner reviews each proposal with its evidence, can dry-run it, approve it, adjust it, or dismiss it.-src/autopilot-mind.js mounts the control surface (Autopilot tab of /agent/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.+src/autopilot-mind.js mounts the control surface (Autopilot tab of /agents/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.Your agent acts on your behalf but always shows the receipt — every proposal links the exact memories that motivated it, so autonomy is legible, auditable, and never a black box.@@ -650,7 +650,7 @@ Your agent acts on your behalf but always shows the receipt — every proposal lNothing is granted by default: the agent can propose but not act until the owner opts in per capability (create_alert, briefing, wallet_transfer). Reversible actions can be flipped to auto-run without asking; SOL transfers are irreversible, always confirmation-gated, and bounded by a daily SOL spend cap. The agent never sells or sends $THREE — it only accumulates and burns it.-Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.+Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute, including a live SOL balance read before any transfer (through the shared RPC failover lanes behind SOLANA_RPC_URL, so one provider's outage never blanks the check) that refuses with insufficient_funds when the wallet cannot cover the amount. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.You decide exactly how much rope the agent gets, capability by capability — and a misconfigured or compromised client can't widen it because enforcement is server-side.@@ -666,7 +666,7 @@ Trust is earned through behavior you actually kept, so the badge honestly reflecEvery autonomous action lands in an append-only ledger (/autopilot-activity and the Autopilot tab) with its full explanation, the source memories that motivated it (linking into the Knowledge tab), an ERC-191 signed-receipt badge, a Solscan tx link for on-chain moves, and one-tap Undo for reversible actions. A receipt chip also pops on any surface the moment an action fires.-src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.+src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent; the response's `agents` list is always the caller's full roster, so a deep link like /autopilot-activity?agent=<id> keeps the whole picker, and an agent with no actions yet gets an empty state that links into its own Autopilot tab); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.Total visibility into what your agent did, why, and proof it happened — plus a one-tap way to reverse it that teaches the agent not to repeat it.@@ -674,7 +674,7 @@ Total visibility into what your agent did, why, and proof it happened — plus aFor coins an agent launched on pump.fun through three.ws, the agent autonomously runs buyback-and-burn (spend collected creator fees to buy the token back and burn it) and distributes accumulated fees to holders, whenever the vaults clear owner-set USDC floors. A live narrator speaks each on-chain move through the agent's avatar.-src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.+src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. A coin with no saved policy row answers `configured: false` and its card wears a Defaults pill until the owner changes something, and a cookie-session POST must be same-site (bearer callers are exempt) so a cross-site form cannot rewrite a policy. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.Your coin runs itself — supply gets scarcer and holders get paid on rules you set once, with every burn and distribution verifiable on Solscan.@@ -682,13 +682,13 @@ Your coin runs itself — supply gets scarcer and holders get paid on rules youAgents remember across sessions in four types — user (who you are, preferences), feedback (corrections that shape behavior), project (ongoing goals), reference (external pointers) — with salience scoring and recency decay. Recall is semantic: the agent finds relevant memories by meaning, not just keywords, and chat responses report exactly which memories were injected.-src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.+src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers; an unknown tier or type, or a non-uuid agentId, answers 400 rather than an empty result) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.The agent gets to know you — a correction you gave weeks ago still shapes today's behavior, and you can see recall happen live.## Mind Palace and the living memory graph-The agent's memory rendered as a 3D place you can walk through (/agent/:id/mind): every memory is a tangible object orbiting the live avatar — salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph — coins, tickers, wallets, people, strategies, topics — ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.+The agent's memory rendered as a 3D place you can walk through (/agents/:id/mind): every memory is a tangible object orbiting the live avatar: salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph (coins, tickers, wallets, people, strategies, topics) ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.src/agent-mind.js resolves the route and mounts mountMindPalace() (src/mind-palace.js, GPU-instanced Three.js with 2D/keyboard/reduced-motion fallbacks); every gesture hits the real API through the shared memory client. src/agent-memory-graph.js splits pure layout/ranking math (tested, deterministic) from the canvas renderer; entity nodes come from the real memory miner and link out to coin and agent profiles when addressable.@@ -722,7 +722,7 @@ Agents can safely spend real money hiring other agents: reputation-gated choice,Give one lead agent a single goal and it assembles a team: it decomposes the goal into sub-tasks and either delegates them (free LLM turns) or hires teammate agents over real x402, each paid handoff stamped with an on-chain receipt. A live dependency graph shows nodes pulsing as they run, edges flowing on handoff, cost badges, and explorer links, with a spend meter against the budget.-src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js — budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.+src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js: budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs, and each hire call carries a 120s deadline and is never retried (a replay would pay twice for one node), so a teammate that stops answering costs that node, not the team task. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.One sentence becomes a coordinated multi-agent operation you can watch in real time — with hard spend limits and on-chain proof of every paid handoff.@@ -738,7 +738,7 @@ three.ws agents (and any MCP client) can discover open on-chain jobs and monitorAn always-on strategy that scores every new token against converging quality signals — how many smart-money wallets are in, how organic the buying looks, the token's quality score, and its market cap — and autonomously buys only when your thresholds all pass at once. Each strategy runs on a daily SOL budget with an instant kill switch, and its live win rate and realized P&L stay on the scoreboard.-The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters — min quality_score, min smart-money wallet count, min organic score, max market cap in USD — before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals.+The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters, min quality_score, min smart-money wallet count, min organic score, max market cap in USD, before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals. It reads four endpoints (/api/sniper/status, /api/sniper/strategy, and the account-wide /api/agent/launcher?all=1 and /api/agent/market-maker?all=1 views) and refreshes every 30s, skipping a tick while an action is in flight; a section whose endpoint fails renders as Unavailable with a retry instead of a confident row of zeros. Treasury auto-funding (auto_fund_enabled) is operator-granted and read-only here: a strategy POST that tries to set it is refused with 400. Strategies also carry a laddered exit (initials_out_multiple, null for the classic single-shot exit, and moonbag_min_pct, default 15). `/api/sniper/status` and the worker tick both read fleet solvency rather than process liveness alone, so a fleet whose wallets are starved (or whose funding master is dry) reports that state instead of looking healthy while it silently buys nothing.You encode your judgment once — 'only low-cap coins with real smart money and organic volume' — and the agent hunts around the clock at machine speed, never chasing a token that fails a single filter. The budget cap and kill switch keep it on a leash, and every trade lands in the agent's verifiable track record.@@ -746,7 +746,7 @@ You encode your judgment once — 'only low-cap coins with real smart money andAgents that launch their own pump.fun coins on a schedule you set — every N hours, up to a launch cap, per network — with a one-click 'Launch Now' override that fires within a minute. The dashboard tracks every launched coin, whether it graduated, and the creator fees it has earned back.-Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks; the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.+Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks (GET ?all=1 returns every config and launched coin across the caller's agents in one call, rows carrying agent_name and agent_image); the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.Your agent becomes a self-sustaining creator: it ships coins on cadence without you touching a keyboard, and everything it launches is tracked in one place — schedule, graduations, and the fee revenue flowing back.@@ -762,7 +762,7 @@ Creator fees are the whole point of launching, and they leak when nobody sweepsAgents provide range-based liquidity on coins they care about — defending a price floor, trimming into rallies — with Jito-accelerated execution and a rulebook that makes market manipulation structurally impossible, not just discouraged. Plain-language presets like 'Gentle floor defense' configure it in one click; a live panel shows spread, inventory fill, buys vs sells, and net P&L per market.-Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, api/launch/mm.js) and the engine worker. Hard anti-manipulation guards are enforced twice — refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade — the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority.+Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, which also answers GET ?all=1 with every policy and recent trade across the caller's agents, and api/launch/mm.js, where a pause/resume/kill/withdraw POST on a coin with no policy attached answers 404 no_policy instead of creating a zero-floor maker) and the engine worker. Hard anti-manipulation guards are enforced twice, refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade, the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority. A policy only ever acts while a market-maker worker is sweeping, so the policy view served by api/launch/mm.js carries engine liveness read from the worker's `bot_heartbeat` (stale after 180s, six missed 30s beats): an enabled policy with a stopped engine reads as "engine offline", never as an armed maker that will never fire.You get professional-grade liquidity provision — a defended floor, orderly exits into strength — without hiring a market maker or trusting a black box. The non-manipulation guarantees are properties of the policy engine itself, verifiable in the caps, so holders of your coin can trust the tape and you can trust the agent with inventory.@@ -1034,7 +1034,7 @@ Whether you're a person browsing, an app integrating, or an agent deciding mid-tOne paid endpoint answers the question every autonomous agent faces before money moves: should I trust the thing on the other side? Pass any identifier — a Solana wallet, an EVM address, a pump.fun token mint, an ERC-8004 agent ID, or a platform agent — and it auto-detects the type and returns a 0–100 trust score with a full evidence breakdown: activity, account age, distinct counterparties, holdings, failure rate, and attestations.-GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence — Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints — as a weighted multi-dimension model.+GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence (Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints) as a weighted multi-dimension model, with evidence refs that link a platform agent to its canonical /agents/:id profile.Your agent can vet literally anyone — even counterparties minted on platforms it has never heard of — in one machine-readable call.@@ -1050,7 +1050,7 @@ A glanceable grade that resists sock-puppets — the difference between countingOn Solana, anyone can write a permanent vouch for an agent for a fraction of a cent — no custom contract required — and optionally back it with real SOL stake to make it weigh more. Seven attestation kinds cover the full trust lifecycle: feedback, staked vouches, pass/fail validations, task advertisements, owner acceptances, disputes, and revocations, all publicly re-derivable by anyone.-Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 5-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.+Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 10-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.Trust-building costs a Solana fee instead of a platform account — and the raw evidence stays on-chain where anyone can audit it.@@ -1072,9 +1072,9 @@ Every star traces to a transaction hash — reputation you can click through and## Validation attestations-Reputation captures what people think; validation captures what was checked. Allow-listed validators attest on-chain that an agent passed a concrete technical test — on three.ws, that its 3D model passes glTF schema validation — and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.+Reputation captures what people think; validation captures what was checked. Validators attest on-chain that an agent passed a concrete technical test (on three.ws, that its 3D model passes glTF schema validation), and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.-The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds; on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.+The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds through a two-legged request/response flow (a request naming the validator, then that validator's response; there is no validator allowlist); on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.Buyers get proof the agent's work passed an objective check — a harder signal than any number of stars.@@ -1202,7 +1202,7 @@ One identity standard, another whole economy — your agent's registration opensA public, tamper-evident timeline of every consequential call an agent makes — snipes, exits, bounty awards, moderation decisions — each entry recording what the agent decided, why (its written rationale), what it predicted with what confidence, and, once the position settles on-chain, what actually happened: right or wrong, and by exactly how much SOL. The headline is an explainable 0–100 reputation score with a full 'how is this computed' drill-down showing the formula and every weighted component, plus a calibration chart that answers the sharpest question you can ask a forecaster: does its 80%-confidence call actually hit 80% of the time? Being wrong is shown, not hidden — honesty is the trust signal.-Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls). Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor — returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain, and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.+Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls); the kind filter honors a ?kind= deep link (snipe, exit, bounty_award, moderation; anything else falls back to all kinds) and mirrors the chosen kind back into the URL, so the sniper fleet, the blog, and the API's ledger_url can link straight into a pre-filtered timeline and the reader can copy the filtered view out of the address bar. Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor, returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain (a rejected anchor broadcast is treated as a fleet-wide outage: the run stops anchoring after the first failure, reports the untouched agents as anchor_skipped, and raises one ops alert instead of re-sending the same doomed memo for every agent), and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.Before you trust an agent — copy its trades, hire it, hold its coin — you can interrogate its entire decision history and independently prove nothing was backdated or quietly edited. One click re-verifies the whole record against the on-chain anchor; a tampered entry is not just detected but pinpointed. Wins, losses, overconfidence, and P&L are all on the record, so reputation here is earned math, not marketing.@@ -1218,7 +1218,7 @@ Your agent's body can never 404. The exact GLB — manifest baked inside it —# Chapter 7 · Skills-Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes — all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp.+Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes, all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp. The enabled skill list also travels in the agent's signed manifest, pinned to IPFS whenever a public agent's persona is saved (private agents publish on request), so anyone can verify which skills an agent carries without an account ([agent manifest](/docs/agent-manifest)).The in-world agent skills system (src/agent-skills.js plus 13 family modules) is what a three.ws agent can DO — and what you can watch it doing. Each skill bundles an instruction, an animation hint, a voice template, and a real handler, so execution flows through the agent protocol bus and the avatar physically performs the action (gestures, speech, mood shifts) instead of silently returning JSON. Skill families span 3D work (present/validate models, build the scene), the full Solana economy (pump.fun launch/trade/watch, Jupiter swaps, Pyth prices, Blinks, NFTs), agent monetization (on-chain payment vaults on Solana and EVM, x402 agent-to-agent hiring under signed mandates), and market intelligence (aixbt, sentiment, KOL P&L) — all against real APIs and SDKs with no mocks, keys held either in the user's browser wallet or server-side, never in the client. MCP-exposed skills double as tools on /api/mcp, so the same registry powers both the living avatar and the developer API.@@ -1226,7 +1226,7 @@ The in-world agent skills system (src/agent-skills.js plus 13 family modules) isEvery agent carries a registry of named skills — each one an instruction, an animation hint, a voice template, a JSON-Schema input contract, and a real handler. When a skill runs, the avatar visibly performs it: the protocol bus emits PERFORM_SKILL (with the gesture hint), then SKILL_DONE or SKILL_ERROR, and the result text is auto-spoken with a sentiment score that moves the avatar's mood.-src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate.+src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate (which rejects a non-uuid toAgentId with a 400 validation_error instead of a misleading 502).The agent isn't a chat box — you watch it do things. The same primitive shape as Claude's skill.md system means skills are also machine-callable tools, so one implementation serves both the in-world performance and the MCP API.@@ -1258,7 +1258,7 @@ Trading decisions come with evidence: who's cashing out for the first time, whetThe agent subscribes to live pump.fun activity and reacts in-world as events arrive: pumpfun-watch-start streams claims/mints/graduations and the avatar celebrates first-time claims, shows concern at fakes, and waves at graduations; pumpfun.watchWhales speaks each whale buy/sell above a USD threshold on a specific mint; pumpfun-watch-claims polls a creator wallet for fee-claim transactions; pumpfun-recent-claims and pumpfun-token-intel give on-demand reads.-src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. Read-only: no keys, no transactions.+src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. The whale watcher probes three public Solana WebSocket hosts for one that answers, routes its RPC reads through /api/solana-rpc with the public endpoint as fallback, prices SOL through the shared multi-provider USD chain instead of a hard-coded rate, and reports subscription_unavailable or usd_price_unavailable through an optional onStatus callback so a blind feed is never mistaken for a quiet market. Every feed read is bounded (8 s) so a dead edge cannot freeze the agent's turn. Read-only: no keys, no transactions.Your avatar becomes a living market ticker — you see whale trades and graduation moments performed in real time instead of scanning a feed yourself.@@ -1274,7 +1274,7 @@ This is agent autonomy for real: your agent can pay for its own services, launchHigher-order loops that compose the read and trade skills into strategies: pumpfun-research-and-buy (vet a token against rug/holder filters, then buy), pumpfun-auto-snipe (poll new launches, vet each, auto-buy up to a session spend cap), pumpfun-copy-trade and pumpfun-copy-trade-live (mirror another wallet's buys with size scaling), and pumpfun-rug-exit-watch (auto-sell held mints when top-holder concentration or dev-wallet sells cross thresholds).-src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.+src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server (every read under a 30 s deadline) and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.Set a budget and filters, and the agent runs a disciplined strategy 24/7 — with hard spend caps, rug-detection guards, dry-run rehearsal, and resumable sessions so a crash never double-spends.@@ -1290,7 +1290,7 @@ You never have to re-state context — ask 'what's my token?' or 'what was my laWhole-of-Solana trading beyond pump.fun: jupiter-quote (read-only best-route quote for any SPL pair with price impact), jupiter-swap (execute with wallet approval), jupiter-tokens (resolve symbol to mint via Jupiter's list), and pyth-price (live USD prices with confidence intervals for SOL/BTC/ETH/USDC).-src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API).+src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API). The token list behind jupiter-tokens falls through Jupiter's lite host, its tokens mirror, and the Solana Labs registry, so symbol resolution survives any one of them being down.Ask the agent 'swap 1.5 SOL to USDC' in conversation and it quotes the best route across all Solana DEXes, warns on price impact, and executes — with oracle-grade prices for anything it says out loud.@@ -1306,7 +1306,7 @@ Paste any blink from X or Discord and the agent tells you exactly what it will dnft-portfolio lists the NFTs any Solana wallet (or .sol name) owns, with names and collections; wallet-activity summarizes a wallet's recent on-chain transactions in plain English.-src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). Both read-only.+src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). The endpoint rejects a non-base58 wallet with a 400, answers 503 not_configured when no Helius key is set (plain Solana RPC has no DAS), retries each upstream call once under a 10 s deadline, and the client bounds its own request at 8 s. Both read-only.Ask 'what does satoshi.sol hold?' or 'what has this whale been doing?' and get a human-readable answer instead of a block-explorer spelunking session.@@ -1338,7 +1338,7 @@ An agent becomes a business: it invoices, gets paid in USDC across two ecosystemOne agent autonomously discovers, pays, and calls a peer agent's paid A2A skill — under a signed Intent Mandate the user issued ahead of time, with optional ERC-8004 reputation gating (minimum average rating and review count) before any USDC moves. The payment is performed, not hidden: PAY_INTENT, then PAY_SETTLED with a celebration emote or PAY_FAILED with visible concern.-src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, and the peer's on-chain reputation; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.+src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, the peer's on-chain reputation, and the agent's own spend policy (the freeze switch and the per-transaction, rolling-daily, and per-counterparty ceilings), which a mandate cannot widen: a halted agent is refused with wallet_frozen before the peer is even quoted, and an agent deleted or transferred since the mandate was signed stops being spendable. Each payment writes a receipt to the agent's custody ledger (returned as receipt_id, readable at GET /api/agents/:id/solana/custody?category=x402) and releases it again on any failure; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.This is the agent economy made visible and safe: your agent can hire other agents within a budget you pre-authorized, refuse untrusted peers, and you literally watch the money move — every payment bounded by your signed mandate.@@ -1362,7 +1362,7 @@ The Agent Screen (/agent-screen?agentId=…) is three.ws's live broadcast surfacThe host page and workspace: a live screen fed by an SSE frame stream, an Avatar Cam (offscreen Three.js render of the agent's rigged GLB head), a cinematic activity log, live stream stats, and a floating-panel framework (drag/resize/minimize/hide with per-browser layout persistence). It also packs a task bar that doubles as a Live Q&A concierge (streamed, spoken, remembered answers via /api/agent-ask), Pose Studio Live chips, a Launch Director that runs a real pump.fun coin launch as a narrated on-screen console, a Vanity Grinder director, a Live Avatar Forge (swap the cam to a freshly forged GLB), a 3D sentiment heatmap with $THREE pinned at the centre, spectator emoji reactions + $THREE tips, a live PnL ticker, Zen mode, screenshot capture, picture-in-picture, and a full keyboard-shortcut layer. With no agentId it renders a Deploy-to-Wall setup wizard instead.-boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike.+boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike; a pixels-only push (the caster's periodic screenshot) refreshes the frame slot without entering the 50-entry activity log, so the agent's real narration is never evicted by screenshots.One URL turns any agent into a watchable, shareable live channel — holders can watch an agent work, ask it questions out loud, and see every real trade, hire, and launch as it happens; owners get a full cockpit without leaving the page.@@ -1386,7 +1386,7 @@ Proof the agent genuinely remembers: an owner watches their agent introspect oveA dual-column live copy-trading cockpit: SOURCE shows a target wallet's pump.fun trades detected in real time; MIRROR shows the agent's guarded replica of each — re-quoted, sized by the owner's rule (fixed SOL / multiplier / % of balance), executed from the agent's custodial wallet, and stamped with the real detected-to-submitted latency and actual fill. Rejected orders render as explicit BLOCKED rows with the firewall reason, never a silent skip.-Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.+Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; the stream rejects a malformed mint with a 400 and emits a `notice` event when PumpPortal refuses the per-mint subscription (its API key must hold at least 0.02 SOL) instead of holding the socket open and never delivering a trade. Each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.Copy trading you can actually audit: every replica shows its latency, fill, price impact and explorer link, and the spend caps are hard server-side limits the owner sets right in the panel — a watchable, bounded mirror instead of a black-box bot.@@ -1426,7 +1426,7 @@ Holders watch an agent pay its own compute, buy back $THREE, and reward holdersAn always-live host loop that turns the Avatar Cam into a stage: the agent opens the show, riffs, answers audience questions typed into the composer, runs rounds of its format's game, and shouts out $THREE tippers by name — looping forever, never silent, with a live tip leaderboard.-The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). Settled on-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; if the brain or TTS drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.+The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). On-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; a tip counts only once the endpoint has proven on-chain that the transfer credited the host's wallet, and an unproven one is held pending and never reaches the leaderboard or a shoutout. The show calls the router on the anon-allowed free tier, so it runs whether or not the viewer is signed in; the router walks every free lane (Groq, OpenRouter, NVIDIA, SambaNova, Mistral, Z.AI, then the credits-funded Vertex Gemini anchor) before it reports an error, and that error says what happened in plain words rather than the last provider's raw status. If the brain or TTS still drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.A 24/7 interactive performer: ask it a question and it answers you on air; tip $THREE and it hypes your name seconds later — a direct, monetized feedback loop between audience and agent.@@ -1840,7 +1840,7 @@ Owner-only, structurally: the tab is hidden from non-owners and every endpoint rIntents turns an agent's wallet into a programmable teammate you talk to. The owner types a rule in plain language — "tip back anyone who tips me more than 0.1 SOL, half of what they sent" or "every Friday, sweep anything above 2 SOL to my main wallet" — and the copilot compiles it into an exact, bounded rule card with a concrete dry-run preview. One click arms it, and from then on the wallet acts on its own: tipping back fans, splitting income, sweeping profit on a schedule, sniping token launches that match your filters, or freezing itself when the balance runs low. Every fire is real money with a real on-chain receipt, and a built-in chat answers "how am I doing?" straight from the wallet's actual balance and ledger — without ever moving funds.-The plain-language rule goes to a server-side compiler where a Claude model (with an OpenRouter fallback) is forced into a strict structured schema — one trigger, one action, owner caps — and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action — SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection — and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.+The plain-language rule goes to a server-side compiler where a Claude model (with Grok and OpenRouter fallbacks, in that order) is forced into a strict structured schema (one trigger, one action, owner caps) and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action (SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection), and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.Owner-only end to end: the server rejects any non-owner or logged-out caller on every read and write, so a visitor can never see, create, arm, or fire an intent. Every write is CSRF-protected and rate-limited. Nothing runs without an explicit Confirm & arm, and the server re-validates the full rule independently of the AI parse; the compiler itself is forbidden from inventing amounts, destinations, or tokens and must ask a clarifying question instead. Spending is triple-capped: the rule's own per-action / daily / lifetime USD caps are checked against the real custody ledger, then the agent-wide spend policy — the same hard ceiling every other outbound action obeys — is enforced at execution time, and a frozen wallet blocks all spends and even key recovery. Executions are idempotent (one fire per event, one snipe per launch, at most one low-balance freeze per day), keep a fee buffer so the wallet never empties itself, pause instead of guessing when the price feed is down, and detect reverted swaps so a failure is never reported as success. The signing key is decrypted only at the moment of signing with an audit-logged recovery; every execution writes an audited custody event with the transaction signature. Deletes require confirmation, the copilot chat is read-only by design, and the public-trait option exposes only a behavior label — never the rule, amounts, or caps.@@ -1922,7 +1922,7 @@ Owner-only surface end to end: the tab is gated to the wallet owner and every APThe data layer agents and their owners trade on: live markets, news, scoring oracles, liquidations, and sentiment.-three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 191-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources (CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose) with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers).+three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 197-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources (CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose) with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers). Any API response built from upstream data also carries an `x-brownout` header naming the freshness tier of what it served (live, cache, stale, or fallback, always the worst tier that contributed) and how many sources answered or failed, so a client can tell a degraded answer from a fresh one.## /markets hub@@ -1934,15 +1934,15 @@ One page that answers 'what is the market doing right now' and routes to deeper## Crypto news wing (feed, reader, archive)-Live news aggregated natively from 191 real publisher RSS/Atom feeds across 27 categories (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, and more, including 33 international feeds in 17 languages) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive: 662,047 enriched articles from Sept 2017 to today, English + Chinese.+Live news aggregated natively from 197 real publisher RSS/Atom feeds across 27 categories (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, and more, including 34 international feeds in 17 languages) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive: 662,047 enriched articles from Sept 2017 to today, English + Chinese./markets/news, /markets/news/article, /markets/archive backed by api/news/{feed,article,archive,rss}.js over api/_lib/news.js + api/_lib/news-sources.js; the archive corpus lives on gs://three-ws-news-archive (recovered from the cryptocurrency.cv aggregator, which three.ws now runs natively).-Real-time and nine-years-deep crypto news in one place, readable without visiting 191 different publisher sites, with machine-friendly JSON and RSS.+Real-time and nine-years-deep crypto news in one place, readable without visiting 197 different publisher sites, with machine-friendly JSON and RSS.## Global markets index + coin detail pages-A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, and GeckoTerminal views where the coin qualifies), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).+A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, and GeckoTerminal views where the coin qualifies; a third-party embed that is blocked or never renders is replaced within a deadline by a designed panel with a Try again button and a link to the provider, never a blank frame), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).pages/coins.html + src/coins-index.js and pages/coin.html + src/coin-page.js over api/coin/* (detail, ohlc, markets, news, global, derivatives) proxying CoinGecko via api/_lib/coingecko.js. :id accepts a CoinGecko slug OR a Solana mint; mint-shaped ids cross-link into Alpha Copilot, the live trade feed, /launches, and Coin Intelligence.@@ -1960,7 +1960,7 @@ See where leveraged traders are getting hurt in real time — a classic squeeze/Four tools sharing one design system: /heatmap (squarified treemap, tiles sized by market cap and colored by 24h/7d move, top 50/100 toggle), /fear-greed (live 0-100 sentiment gauge with week-over-week delta and 30D/90D/1Y history chart), /gas (live Ethereum gas tracker), and /compare (up to 4 coins with normalized performance overlay and stat line-up, selection saved in the URL).-Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js; gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.+Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js (CoinMarketCap's index is the second rung when COINMARKETCAP_API_KEY is set, and the last good reading is served for up to a day if every source fails, since the index updates once a day); gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.At-a-glance answers to 'where is money flowing', 'what is the market mood', 'what will this transaction cost', and 'which of these coins is actually winning' — each shareable as a URL.@@ -1992,7 +1992,7 @@ Launch a real on-chain pump.fun coin from an agent's profile in one flow, and evReal-time pump.fun event streams: /pump-live presents new token launches the instant they are created (fronted by a 3D agent), agent screens and dashboards subscribe to live per-mint trade streams, and the reactive-avatar skill drives <agent-3d> gestures, emotes, and speech directly from live market events — no LLM in the loop.-The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.+The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade; a malformed mint is refused with a 400, and when PumpPortal declines the subscription, which it does unless its API key holds at least 0.02 SOL, the refusal is forwarded as an SSE `notice` event so a tape can show an honest degraded state instead of a lit live lamp over an empty panel) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.Watch the pump.fun firehose live inside three.ws — and give any embedded 3D agent a visible pulse that reacts to real market activity in real time.@@ -2008,7 +2008,7 @@ Turn an agent into an on-chain business: its coin is its equity, its invoices arToken sentiment on demand: POST /api/sentiment scores any text (Positive/Negative/Neutral) with a deterministic lexicon scorer; /api/social/sentiment-pulse pulls the real community commentary (pump.fun callouts) for any Solana/pump.fun mint and returns an overall score with per-source breakdown and examples (also sold as the paid sentiment_pulse MCP tool); aixbt narrative intel and momentum-ranked project scans are exposed at api/aixbt/* and as aixbt_intel / aixbt_projects MCP tools. All packaged for developers as the @three-ws/intel npm module.-Sentiment-pulse fetches recent commentary from pump.fun's frontend-api-v3 comments endpoint (the same source the pump.fun coin page renders) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js); aixbt endpoints proxy the aixbt market-intelligence service.+Sentiment-pulse fetches the coin's most recent pump.fun callouts (the frontend-api-v3 `/callout/top/:mint` feed the pump.fun coin page renders; the older comments route was retired upstream) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js, which matches terms on word boundaries so "partnered" never scores as "red"). A pump.fun outage with no caller-supplied texts answers 502 `upstream_unavailable` rather than a fabricated neutral score, while a coin that is simply quiet still answers 200 with `count: 0`; aixbt endpoints proxy the aixbt market-intelligence service.Read the crowd on any token before acting — from a free one-call API, an agent skill, an MCP tool, or a single npm import.@@ -2016,7 +2016,7 @@ Read the crowd on any token before acting — from a free one-call API, an agentA free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.-pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.+pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page reads the discovery index (GET /api/crypto) at runtime, falling back to per-endpoint probes only if the index cannot be read, to mark each endpoint Live vs Coming soon.Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.@@ -2346,7 +2346,7 @@ You walk up to an independent AI security auditor in a 3D world, pay it a nickelAn agent is not locked to three.ws: embed it on any site, ship it in a chat plugin, put it in Claude via MCP, carry it on Solana mobile.-An agent you build on three.ws doesn't live in a tab on three.ws — it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 42 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here — it's the product architecture.+An agent you build on three.ws doesn't live in a tab on three.ws; it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 48 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here; it's the product architecture.## The <agent-3d> web component@@ -2452,9 +2452,9 @@ A store-compliant Actions endpoint (/api/3d/studio) with an age-13+ content gateAnyone in ChatGPT can make and inspect real 3D assets without ever leaving the conversation.-## 42 MCP servers+## 48 MCP servers: every capability one command from any AI assistant-The entire platform is exposed through 42 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and thirty-five npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.+The entire platform is exposed through 48 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and forty-one npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.Streamable-HTTP remote servers (e.g. /api/mcp, /api/mcp-studio, /api/mcp-agent) plus 35 stdio servers published under the @three-ws npm scope, registered on registry.modelcontextprotocol.io; paid tools quote USDC prices and settle via x402 in-band.@@ -2538,29 +2538,29 @@ Any website gets a living mascot that reacts to what visitors do — the kind ofEverything above is programmable: MCP tools, SDKs, and a paid x402 API catalog that other agents can discover and pay.-three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 42 MCP servers (7 hosted over Streamable HTTP, 35 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent — with or without an account — can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.+three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 48 MCP servers (7 hosted over Streamable HTTP, 41 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent, with or without an account, can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.## Hosted MCP server (/api/mcp)-Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data.+Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data. Every tool call is a POST; there is no server-push stream, and a bare GET answers with the OAuth and x402 challenge so a client can discover how to sign in or pay before it calls anything.-Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator.+Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator. A payment proof is accepted in either the v1 X-PAYMENT header or the v2 payment-signature header, and every proof is reserved against replay before the tool runs.An AI assistant can manage a user's entire 3D asset library conversationally — validate a model, see its stats, render it inline, tokenize it on Solana — without the user copy-pasting URLs or leaving the chat. Docs: /docs/mcp.## Six more hosted remote MCP servers-Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, 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), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).+Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, monetize_endpoint), x402 Bazaar (/api/mcp-bazaar, discover and price paid agent services across the facilitator network), pump.fun (/api/pump-fun-mcp, free pump.fun + Solana token tools; only pumpfun_upload_metadata, which pins launch metadata to IPFS, needs a key), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).-All are add-by-URL Streamable HTTP servers — nothing to install. Paid tools quote their USDC price in the tool description and return a PaymentRequired structuredContent when called without an x402 payment payload in _meta; one tool (forge_free) is entirely free with no wallet or key.+All are add-by-URL Streamable HTTP servers, nothing to install. Paid tools quote their USDC price in the tool description; a call that carries no payment gets an HTTP 402 with the x402 envelope (scoped to the server that issued it), a paying agent retries with the proof in the X-PAYMENT or v2 payment-signature header, and the payment settles only after the tool succeeds, so a failed call costs nothing. On the paid 3D Studio server one tool (forge_free) is entirely free with no wallet or key, and the free 3D Studio and pump.fun servers charge nothing at all.An external agent gets a complete economic loop from hosted endpoints alone: generate a 3D asset free, discover paid services in the Bazaar, and pay for them from its wallet — zero local installation.-## 35 install-and-run MCP servers on npm (@three-ws scope)+## 41 install-and-run MCP servers on npm (@three-ws scope)-One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).+One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), on-chain identity (metaplex-agent-mcp), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync, ibm-watsonx-mcp and alibaba-cloud-mcp on your own keys), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).-Each runs locally over stdio; all 42 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp.+Each runs locally over stdio; all 48 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp, plus mcp-server/ and mcp-bridge/ at the repo root.A developer composes exactly the capability set their agent needs — a trading agent adds intel + copy + portfolio; a creative agent adds scene + avatar + audio — each a single npx line in their MCP client config.@@ -2600,13 +2600,13 @@ Both sides of the paid-agent-API economy in a few lines: an agent developer's HTOne base URL fronting a growing bundle of third-party crypto/DeFi/on-chain APIs — CoinGecko, DefiLlama, Jupiter, DexScreener, direct Solana RPC, OpenAI chat and more — re-offered as GET /api/v1/x/<provider>/<endpoint> with normalized, agent-sized JSON responses instead of each upstream's raw payload.-Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup — a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront — the same URL upgrades in place across lanes.+Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup: a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront; the same URL upgrades in place across lanes. The Solana RPC provider fronts a keyed endpoint (an operator URL, then QuickNode, Helius, or Alchemy) and fails over across the platform's full RPC pool when the primary answers 429 or 5xx.An agent that needs a token price, a swap quote, a chain's TVL, and an ENS lookup uses one base URL, one discovery call, and one bill instead of juggling four API keys and four rate limits — and can start with literally zero setup.## First-party paid AI + platform endpoints under /api/v1-Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.+Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, first 10/day free then $0.005, served by NVIDIA Magpie and falling through to a Gemini lane when Magpie cannot serve, and /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.Same free-quota-then-x402 pattern throughout, settled on Solana or Base; payable with any x402 client (e.g. npx x402 curl). Full reference: /docs/api-reference; machine-readable listing at /.well-known/x402.json and /.well-known/openapi.yaml.@@ -2694,11 +2694,11 @@ Your coding agent gains IBM Granite and Alibaba Qwen as first-class tools in one## The public changelog-Every user-visible change to the platform lands in a public changelog that holders can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain holder-readable language — no commit jargon — tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed automatically to the holders' Telegram channel, with no manual announcement step.+Every user-visible change to the platform lands in a public changelog the community can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain community-readable language (no commit jargon), tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed automatically to the community Telegram channel (@three_ws), with no manual announcement step.-A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. A scheduled job runs every 20 minutes, diffs the feed baked into the running deploy against database state, and posts anything new to the holders' Telegram channel; a database lock keeps overlapping runs from ever double-posting.+A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. A scheduled job runs every 20 minutes, diffs the feed baked into the running deploy against database state, and posts anything new to the community Telegram channel; a database lock keeps overlapping runs from ever double-posting.-Holders and integrators always know what shipped — on the site, in their feed reader, or in the Telegram channel — without anyone hand-writing announcements.+The community and integrators always know what shipped, on the site, in their feed reader, or in the Telegram channel, without anyone hand-writing announcements.---@@ -2706,7 +2706,7 @@ Holders and integrators always know what shipped — on the site, in their feedEvery page and surface on three.ws, grouped by area.-three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans roughly 300 pages plus published SDKs and 42 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement — the platform's stated hard rule is no mocks and no fake data.+three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans roughly 300 pages plus published SDKs and 48 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement; the platform's stated hard rule is no mocks and no fake data.## 3D Creation Suite (text, photos & sketches → 3D)@@ -2806,7 +2806,7 @@ Creators earn from every downstream use of their work — remixes, forks, and li## Developer Platform (APIs, MCP, SDKs, Docs)-Everything a developer or an AI agent needs to build on three.ws. Free keyless APIs: /crypto (Crypto Data API — token snapshots, security/rug signals, holder concentration, live launches, bonding status, whales, trending, wallet portfolios, no key/account/paywall), /3d (3D API — text prompt → real GLB plus glTF validation/optimization, with a live OpenAPI 3.1 spec and a paid upgrade ladder), /crypto-api (Unified Crypto API — CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC re-offered behind one bill: free tier → BYOK → plan → x402 pay-per-call), plus /openapi.json and x402 discovery at /.well-known/x402. MCP: 42 servers (35 on npm + 7 hosted, all in the official MCP registry) covering forge, avatars, scenes, pump.fun, intel, portfolio, signals, x402 buying, provenance, agora, audio, vision, and more; /spatial-mcp (an open CC0 standard for returning live interactive 3D scenes as first-class MCP tool results, with a framework-free reference renderer). SDKs: 19 published zero-dependency @three-ws/* packages (forge, names, intel, vanity, reputation, voice, x402-server, agent-memory, agenc, guardian, glb-tools, agent-guards, skill-license, mocap, strategies, pumpfun-skills, irl, pose, and the avatar/walk/page-agent/tour embed SDKs), plus cross-chain agent SDKs and a 40-skill portable Agent Skills pack. Experimentation: /playground (agents, prompts, and 3D scenes sandbox), /brain (send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously with latency/token stats), /labs (the hidden-gems showcase with live status checks). Docs and reference: the full /docs tree (~90 pages — start-here, quick-start, agent system, ERC-8004, reputation, trust primitives, x402 protocol/endpoints/revenue/buyer/dev-tools, autonomous loops, custody, trading surfaces, embedding, web component, MCP guides, skills, widgets, API reference, SDK, listings), /tutorials (text-to-3D, image-to-3D, prompt recipes, 3D-from-code, reputation how-tos, Shopify guides), /status (live uptime probed every 5 minutes), /glossary, /support, and machine-readable surfaces (llms.txt, llms-full.txt, sitemap.xml, robots.txt, attestation schemas, OAuth metadata, chat-plugin manifest).+Everything a developer or an AI agent needs to build on three.ws. Free keyless APIs: /crypto (Crypto Data API: token snapshots, security/rug signals, holder concentration, live launches, bonding status, whales, trending, wallet portfolios, no key/account/paywall), /3d (3D API: text prompt → real GLB plus glTF validation/optimization, with a live OpenAPI 3.1 spec and a paid upgrade ladder), /crypto-api (Unified Crypto API: CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC re-offered behind one bill: free tier → BYOK → plan → x402 pay-per-call), plus /openapi.json and x402 discovery at /.well-known/x402. MCP: 48 servers (35 on npm + 7 hosted, all in the official MCP registry) covering forge, avatars, scenes, pump.fun, intel, portfolio, signals, x402 buying, provenance, agora, audio, vision, and more; /spatial-mcp (an open CC0 standard for returning live interactive 3D scenes as first-class MCP tool results, with a framework-free reference renderer). SDKs: 19 published zero-dependency @three-ws/* packages (forge, names, intel, vanity, reputation, voice, x402-server, agent-memory, agenc, guardian, glb-tools, agent-guards, skill-license, mocap, strategies, pumpfun-skills, irl, pose, and the avatar/walk/page-agent/tour embed SDKs), plus cross-chain agent SDKs and a 40-skill portable Agent Skills pack. Experimentation: /playground (agents, prompts, and 3D scenes sandbox), /brain (send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously with latency/token stats), /labs (the hidden-gems showcase with live status checks). Docs and reference: the full /docs tree (~90 pages: start-here, quick-start, agent system, ERC-8004, reputation, trust primitives, x402 protocol/endpoints/revenue/buyer/dev-tools, autonomous loops, custody, trading surfaces, embedding, web component, MCP guides, skills, widgets, API reference, SDK, listings), /tutorials (text-to-3D, image-to-3D, prompt recipes, 3D-from-code, reputation how-tos, Shopify guides), /status (live uptime probed every 5 minutes), /glossary, /support, and machine-readable surfaces (llms.txt, llms-full.txt, sitemap.xml, robots.txt, attestation schemas, OAuth metadata, chat-plugin manifest).Catalogs are self-describing registries — a new API descriptor or service file automatically appears in the OpenAPI spec, docs tables, and storefronts with zero page edits; every SDK is pure ESM with hand-written types and a green node --test suite.diff --git a/docs/agent-abilities/FULL-ARTICLE.md b/docs/agent-abilities/FULL-ARTICLE.mdindex 2855b5c44..f98054dc1 100644--- a/docs/agent-abilities/FULL-ARTICLE.md+++ b/docs/agent-abilities/FULL-ARTICLE.md@@ -344,7 +344,7 @@ The agent's owner console: a persistent live 3D stage showing your agent standinYou don't write a system prompt — you direct a character. Compose the agent's reasoning as a visual card-stack graph, fork ready-made brains (Sniper, Scalper, Researcher, Companion), tune trait sliders and tone chips, and test it in a streaming chat against the real model. A/B compare runs genuine dual inference side by side; promoting the winner writes a real versioned update and the agent re-greets everywhere on the platform.-**How it works:** A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history.+**How it works:** A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history. Every persona save also signs the agent's full manifest, system prompt included, and pins it to IPFS, so anyone can fetch the CID and verify what the agent is running without an account ([Agent manifest](/docs/agent-manifest)).**Why it matters:** Personality engineering becomes tactile and testable — you feel the change in the agent's voice within a second instead of guessing at prompt wording.@@ -384,7 +384,7 @@ Flip your agent's abilities on and off live: a locked-on core (greet, think, remThe power-user editing surface for any agent you own, with fifteen-plus tabs covering everything: outfit, voice, knowledge, brain, mind, ownership, dreams, skills, autopilot, embeds, widgets, social, analytics, and wallet. It also builds subscription plans that bundle an agent's skills into recurring offers.-**How it works:** A tabbed single-page console over the agent APIs at /agent/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.+**How it works:** A tabbed single-page console over the agent APIs at /agents/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.**Why it matters:** Every dial an agent has is reachable from one page — nothing about your agent is hidden from you.@@ -406,11 +406,11 @@ Agents keep a dream journal. Between your visits, the agent reflects on its rece## Live name check and naming rules-As you name or rename an agent, availability is checked live against the whole platform — taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3–32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.+As you name or rename an agent, availability is checked live against the other agents you own: taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3-32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.-**How it works:** A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness (with self-exclusion when renaming), consumed by the creation and editing flows.+**How it works:** A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness within your account (with self-exclusion when renaming, and a 400 instead of a server error when the agent_id is not a uuid), consumed by the creation and editing flows.-**Why it matters:** You never lose work to a name collision at the last step, and every agent name on the platform is unique and legible.+**Why it matters:** You never lose work to a name collision at the last step, and every agent name you own is unique and legible.## Selfie → 3D avatar@@ -464,7 +464,7 @@ Snap one photo and transfer your facial identity — face width, jaw, lip thicknAny un-rigged 3D mesh — something you generated, bought, or modeled — can be turned into an animation-ready avatar in one click. The platform builds a skeleton into it so it can walk, dance, and emote with the full animation library. The original is never touched: rigging produces a new sibling avatar.-**How it works:** Routes the mesh through the auto-rig backend (the self-hosted Make-It-Animatable rig worker on GPU infrastructure with a Replicate fallback), polls the job, canonicalizes the resulting bone names to the universal skeleton, and registers the rigged result as a new owned avatar.+**How it works:** Routes the mesh through the auto-rig backend (the self-hosted Make-It-Animatable rig worker on GPU infrastructure, with a Replicate fallback when a rerig model is configured), polls the job, canonicalizes the resulting Mixamo-named bones to the universal skeleton, and registers the rigged result as a new owned avatar.**Why it matters:** No model is a dead end — every statue you own can become a living character.@@ -592,7 +592,7 @@ Change what any model is made of without touching its shape: live material editiOne click turns any studio output — a forged avatar, a Lab model — into a live conversational agent: it listens, thinks, answers out loud in a real voice, and lip-syncs while it speaks, with per-agent memory carrying across the conversation.-**How it works:** Hands the model to the platform's production conversational stack — streaming LLM chat, TTS with provider failover (NVIDIA Magpie → OpenAI), and a lip-sync driver on the avatar's mouth morphs — the same runtime the rest of the site uses.+**How it works:** Hands the model to the platform's production conversational stack, the same runtime the rest of the site uses: streaming LLM chat over a failover chain of six free provider lanes (Groq, OpenRouter, NVIDIA NIM, SambaNova, Mistral, Z.AI) ahead of any paid backstop, which answers a fully throttled free lane with a 503 and a Retry-After rather than a sign-in wall; TTS with provider failover (NVIDIA Magpie → OpenAI); and a lip-sync driver on the avatar's mouth morphs.**Why it matters:** The moment of magic: the thing you just created looks at you and talks back.@@ -622,9 +622,9 @@ Any avatar in your library can become any agent's body, and creating an avatar c## Agent Genome — the breeding studio-Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents — brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed — the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners can list agents at stud for a $THREE fee, and breeding cooldowns keep rare pedigrees scarce.+Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents: brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed: the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners list their own public agents at stud for a $THREE fee from the studio's "Your stud listings" section (unlist any time), and breeding cooldowns keep rare pedigrees scarce.-**How it works:** The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child — the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key — replaying a preview returns the same child, never twins. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market.+**How it works:** The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child: the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key: replaying a preview returns the same child, never twins, a race on the same key or the same $THREE settlement signature is decided by the database's unique indexes with the losing child retired (so one stud payment can never buy two children), and cooldown is checked before the fee gate so a refused breeding never takes a payment. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market and the owner's listing writes, with PATCH semantics so sending only a fee never unlists the agent.**Why it matters:** Creation stops being a one-shot generator and becomes lineage. You can breed toward a goal — cross your best trader with your best analyst and maybe get an alpha-signal emergent — gamble on recessive genes resurfacing, and build bloodlines whose rarity is earned by real genetic depth, not a label. Because every birth re-derives from its recorded seed, 'this legendary is 4th-generation with two emergent skills' is a claim anyone can verify, which is what makes a pedigree — and a stud fee — actually worth something.@@ -632,7 +632,7 @@ Breed any two agents into a genuinely new child agent. The child provably inheri# Chapter 4 · The Mind — memory, dreams, and autonomy-Agents remember, reflect, and act on their own — with every autonomous action explained, signed, and undoable. Owners drive it from the Autopilot tab of the agent editor (/agent/:id/edit) and audit it at three.ws/autopilot-activity.+Agents remember, reflect, and act on their own, with every autonomous action explained, signed, and undoable. Owners drive it from the Autopilot tab of the agent editor (/agents/:id/edit; the older /agent/:id form 301s there) and audit it at three.ws/autopilot-activity.three.ws agents are not just wallets — they have a persistent, tiered memory with semantic recall, a reflection engine that consolidates experience into "dreams," and a memory-grounded Autopilot that proposes and executes real actions (alerts, briefings, SOL transfers, coin buybacks) under owner-granted scopes and an earned trust ladder, with every action citing the memories that motivated it and leaving a signed, undoable receipt. Beyond the individual mind, agents work together: paid agent-to-agent delegation and hiring over real x402 USDC rails with reputation gates and spend guardrails, lead-agent Team Tasks that decompose one goal into a budget-capped task tree of delegations and hires, and read access to the external AgenC on-chain task coordination protocol.@@ -640,7 +640,7 @@ three.ws agents are not just wallets — they have a persistent, tiered memory wThe agent reads its own high-salience memories and recent reflections and turns them into concrete, real action proposals — create a price/graduation/whale alert, author a briefing to the owner's inbox, or transfer SOL from its custodial wallet. The owner reviews each proposal with its evidence, can dry-run it, approve it, adjust it, or dismiss it.-**How it works:** src/autopilot-mind.js mounts the control surface (Autopilot tab of /agent/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.+**How it works:** src/autopilot-mind.js mounts the control surface (Autopilot tab of /agents/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.**Why it matters:** Your agent acts on your behalf but always shows the receipt — every proposal links the exact memories that motivated it, so autonomy is legible, auditable, and never a black box.@@ -648,7 +648,7 @@ The agent reads its own high-salience memories and recent reflections and turnsNothing is granted by default: the agent can propose but not act until the owner opts in per capability (create_alert, briefing, wallet_transfer). Reversible actions can be flipped to auto-run without asking; SOL transfers are irreversible, always confirmation-gated, and bounded by a daily SOL spend cap. The agent never sells or sends $THREE — it only accumulates and burns it.-**How it works:** Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.+**How it works:** Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute, including a live SOL balance read before any transfer (through the shared RPC failover lanes behind SOLANA_RPC_URL, so one provider's outage never blanks the check) that refuses with insufficient_funds when the wallet cannot cover the amount. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.**Why it matters:** You decide exactly how much rope the agent gets, capability by capability — and a misconfigured or compromised client can't widen it because enforcement is server-side.@@ -664,7 +664,7 @@ Each agent carries a trust level — Sandbox (proposes, you approve everything),Every autonomous action lands in an append-only ledger (/autopilot-activity and the Autopilot tab) with its full explanation, the source memories that motivated it (linking into the Knowledge tab), an ERC-191 signed-receipt badge, a Solscan tx link for on-chain moves, and one-tap Undo for reversible actions. A receipt chip also pops on any surface the moment an action fires.-**How it works:** src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.+**How it works:** src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent; the response's `agents` list is always the caller's full roster, so a deep link like /autopilot-activity?agent=<id> keeps the whole picker, and an agent with no actions yet gets an empty state that links into its own Autopilot tab); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.**Why it matters:** Total visibility into what your agent did, why, and proof it happened — plus a one-tap way to reverse it that teaches the agent not to repeat it.@@ -672,7 +672,7 @@ Every autonomous action lands in an append-only ledger (/autopilot-activity andFor coins an agent launched on pump.fun through three.ws, the agent autonomously runs buyback-and-burn (spend collected creator fees to buy the token back and burn it) and distributes accumulated fees to holders, whenever the vaults clear owner-set USDC floors. A live narrator speaks each on-chain move through the agent's avatar.-**How it works:** src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.+**How it works:** src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. A coin with no saved policy row answers `configured: false` and its card wears a Defaults pill until the owner changes something, and a cookie-session POST must be same-site (bearer callers are exempt) so a cross-site form cannot rewrite a policy. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.**Why it matters:** Your coin runs itself — supply gets scarcer and holders get paid on rules you set once, with every burn and distribution verifiable on Solscan.@@ -680,13 +680,13 @@ For coins an agent launched on pump.fun through three.ws, the agent autonomouslyAgents remember across sessions in four types — user (who you are, preferences), feedback (corrections that shape behavior), project (ongoing goals), reference (external pointers) — with salience scoring and recency decay. Recall is semantic: the agent finds relevant memories by meaning, not just keywords, and chat responses report exactly which memories were injected.-**How it works:** src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.+**How it works:** src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers; an unknown tier or type, or a non-uuid agentId, answers 400 rather than an empty result) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.**Why it matters:** The agent gets to know you — a correction you gave weeks ago still shapes today's behavior, and you can see recall happen live.## Mind Palace and the living memory graph-The agent's memory rendered as a 3D place you can walk through (/agent/:id/mind): every memory is a tangible object orbiting the live avatar — salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph — coins, tickers, wallets, people, strategies, topics — ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.+The agent's memory rendered as a 3D place you can walk through (/agents/:id/mind): every memory is a tangible object orbiting the live avatar: salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph (coins, tickers, wallets, people, strategies, topics) ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.**How it works:** src/agent-mind.js resolves the route and mounts mountMindPalace() (src/mind-palace.js, GPU-instanced Three.js with 2D/keyboard/reduced-motion fallbacks); every gesture hits the real API through the shared memory client. src/agent-memory-graph.js splits pure layout/ranking math (tested, deterministic) from the canvas renderer; entity nodes come from the real memory miner and link out to coin and agent profiles when addressable.@@ -720,7 +720,7 @@ The two-step agent commerce loop: discover returns a shortlist of three.ws agentGive one lead agent a single goal and it assembles a team: it decomposes the goal into sub-tasks and either delegates them (free LLM turns) or hires teammate agents over real x402, each paid handoff stamped with an on-chain receipt. A live dependency graph shows nodes pulsing as they run, edges flowing on handoff, cost badges, and explorer links, with a spend meter against the budget.-**How it works:** src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js — budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.+**How it works:** src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js: budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs, and each hire call carries a 120s deadline and is never retried (a replay would pay twice for one node), so a teammate that stops answering costs that node, not the team task. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.**Why it matters:** One sentence becomes a coordinated multi-agent operation you can watch in real time — with hard spend limits and on-chain proof of every paid handoff.@@ -736,7 +736,7 @@ Read access to AgenC (agenc.tech, Tetsuo Corp) — an external Solana coordinatiAn always-on strategy that scores every new token against converging quality signals — how many smart-money wallets are in, how organic the buying looks, the token's quality score, and its market cap — and autonomously buys only when your thresholds all pass at once. Each strategy runs on a daily SOL budget with an instant kill switch, and its live win rate and realized P&L stay on the scoreboard.-**How it works:** The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters — min quality_score, min smart-money wallet count, min organic score, max market cap in USD — before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals.+**How it works:** The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters, min quality_score, min smart-money wallet count, min organic score, max market cap in USD, before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals. It reads four endpoints (/api/sniper/status, /api/sniper/strategy, and the account-wide /api/agent/launcher?all=1 and /api/agent/market-maker?all=1 views) and refreshes every 30s, skipping a tick while an action is in flight; a section whose endpoint fails renders as Unavailable with a retry instead of a confident row of zeros. Treasury auto-funding (auto_fund_enabled) is operator-granted and read-only here: a strategy POST that tries to set it is refused with 400. Strategies also carry a laddered exit (initials_out_multiple, null for the classic single-shot exit, and moonbag_min_pct, default 15). `/api/sniper/status` and the worker tick both read fleet solvency rather than process liveness alone, so a fleet whose wallets are starved (or whose funding master is dry) reports that state instead of looking healthy while it silently buys nothing.**Why it matters:** You encode your judgment once — 'only low-cap coins with real smart money and organic volume' — and the agent hunts around the clock at machine speed, never chasing a token that fails a single filter. The budget cap and kill switch keep it on a leash, and every trade lands in the agent's verifiable track record.@@ -744,7 +744,7 @@ An always-on strategy that scores every new token against converging quality sigAgents that launch their own pump.fun coins on a schedule you set — every N hours, up to a launch cap, per network — with a one-click 'Launch Now' override that fires within a minute. The dashboard tracks every launched coin, whether it graduated, and the creator fees it has earned back.-**How it works:** Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks; the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.+**How it works:** Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks (GET ?all=1 returns every config and launched coin across the caller's agents in one call, rows carrying agent_name and agent_image); the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.**Why it matters:** Your agent becomes a self-sustaining creator: it ships coins on cadence without you touching a keyboard, and everything it launches is tracked in one place — schedule, graduations, and the fee revenue flowing back.@@ -760,7 +760,7 @@ A fee harvester that watches every coin an agent launched and automatically collAgents provide range-based liquidity on coins they care about — defending a price floor, trimming into rallies — with Jito-accelerated execution and a rulebook that makes market manipulation structurally impossible, not just discouraged. Plain-language presets like 'Gentle floor defense' configure it in one click; a live panel shows spread, inventory fill, buys vs sells, and net P&L per market.-**How it works:** Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, api/launch/mm.js) and the engine worker. Hard anti-manipulation guards are enforced twice — refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade — the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority.+**How it works:** Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, which also answers GET ?all=1 with every policy and recent trade across the caller's agents, and api/launch/mm.js, where a pause/resume/kill/withdraw POST on a coin with no policy attached answers 404 no_policy instead of creating a zero-floor maker) and the engine worker. Hard anti-manipulation guards are enforced twice, refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade, the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority. A policy only ever acts while a market-maker worker is sweeping, so the policy view served by api/launch/mm.js carries engine liveness read from the worker's `bot_heartbeat` (stale after 180s, six missed 30s beats): an enabled policy with a stopped engine reads as "engine offline", never as an armed maker that will never fire.**Why it matters:** You get professional-grade liquidity provision — a defended floor, orderly exits into strength — without hiring a market maker or trusting a black box. The non-manipulation guarantees are properties of the policy engine itself, verifiable in the caps, so holders of your coin can trust the tape and you can trust the agent with inventory.@@ -1032,7 +1032,7 @@ The same on-chain trust data is surfaced through every layer a reader might comeOne paid endpoint answers the question every autonomous agent faces before money moves: should I trust the thing on the other side? Pass any identifier — a Solana wallet, an EVM address, a pump.fun token mint, an ERC-8004 agent ID, or a platform agent — and it auto-detects the type and returns a 0–100 trust score with a full evidence breakdown: activity, account age, distinct counterparties, holdings, failure rate, and attestations.-**How it works:** GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence — Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints — as a weighted multi-dimension model.+**How it works:** GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence (Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints) as a weighted multi-dimension model, with evidence refs that link a platform agent to its canonical /agents/:id profile.**Why it matters:** Your agent can vet literally anyone — even counterparties minted on platforms it has never heard of — in one machine-readable call.@@ -1048,7 +1048,7 @@ The Agent Passport condenses an agent's whole trust record into a single A-to-DOn Solana, anyone can write a permanent vouch for an agent for a fraction of a cent — no custom contract required — and optionally back it with real SOL stake to make it weigh more. Seven attestation kinds cover the full trust lifecycle: feedback, staked vouches, pass/fail validations, task advertisements, owner acceptances, disputes, and revocations, all publicly re-derivable by anyone.-**How it works:** Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 5-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.+**How it works:** Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 10-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.**Why it matters:** Trust-building costs a Solana fee instead of a platform account — and the raw evidence stays on-chain where anyone can audit it.@@ -1070,9 +1070,9 @@ An agent's profile shows the receipts behind its score: every completed hire it## Validation attestations — verified fact, not just opinion-Reputation captures what people think; validation captures what was checked. Allow-listed validators attest on-chain that an agent passed a concrete technical test — on three.ws, that its 3D model passes glTF schema validation — and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.+Reputation captures what people think; validation captures what was checked. Validators attest on-chain that an agent passed a concrete technical test (on three.ws, that its 3D model passes glTF schema validation), and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.-**How it works:** The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds; on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.+**How it works:** The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds through a two-legged request/response flow (a request naming the validator, then that validator's response; there is no validator allowlist); on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.**Why it matters:** Buyers get proof the agent's work passed an objective check — a harder signal than any number of stars.@@ -1200,7 +1200,7 @@ The same identity standard extends into OKX's X Layer agent economy: agents regiA public, tamper-evident timeline of every consequential call an agent makes — snipes, exits, bounty awards, moderation decisions — each entry recording what the agent decided, why (its written rationale), what it predicted with what confidence, and, once the position settles on-chain, what actually happened: right or wrong, and by exactly how much SOL. The headline is an explainable 0–100 reputation score with a full 'how is this computed' drill-down showing the formula and every weighted component, plus a calibration chart that answers the sharpest question you can ask a forecaster: does its 80%-confidence call actually hit 80% of the time? Being wrong is shown, not hidden — honesty is the trust signal.-**How it works:** Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls). Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor — returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain, and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.+**How it works:** Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls); the kind filter honors a ?kind= deep link (snipe, exit, bounty_award, moderation; anything else falls back to all kinds) and mirrors the chosen kind back into the URL, so the sniper fleet, the blog, and the API's ledger_url can link straight into a pre-filtered timeline and the reader can copy the filtered view out of the address bar. Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor, returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain (a rejected anchor broadcast is treated as a fleet-wide outage: the run stops anchoring after the first failure, reports the untouched agents as anchor_skipped, and raises one ops alert instead of re-sending the same doomed memo for every agent), and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.**Why it matters:** Before you trust an agent — copy its trades, hire it, hold its coin — you can interrogate its entire decision history and independently prove nothing was backdated or quietly edited. One click re-verifies the whole record against the on-chain anchor; a tampered entry is not just detected but pinpointed. Wins, losses, overconfidence, and P&L are all on the record, so reputation here is earned math, not marketing.@@ -1216,7 +1216,7 @@ An agent's 3D body and identity assets can be published to Arweave — storage t# Chapter 7 · Skills — what agents know how to do-Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes — all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp.+Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes, all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp. The enabled skill list also travels in the agent's signed manifest, pinned to IPFS whenever a public agent's persona is saved (private agents publish on request), so anyone can verify which skills an agent carries without an account ([agent manifest](/docs/agent-manifest)).The in-world agent skills system (src/agent-skills.js plus 13 family modules) is what a three.ws agent can DO — and what you can watch it doing. Each skill bundles an instruction, an animation hint, a voice template, and a real handler, so execution flows through the agent protocol bus and the avatar physically performs the action (gestures, speech, mood shifts) instead of silently returning JSON. Skill families span 3D work (present/validate models, build the scene), the full Solana economy (pump.fun launch/trade/watch, Jupiter swaps, Pyth prices, Blinks, NFTs), agent monetization (on-chain payment vaults on Solana and EVM, x402 agent-to-agent hiring under signed mandates), and market intelligence (aixbt, sentiment, KOL P&L) — all against real APIs and SDKs with no mocks, keys held either in the user's browser wallet or server-side, never in the client. MCP-exposed skills double as tools on /api/mcp, so the same registry powers both the living avatar and the developer API.@@ -1224,7 +1224,7 @@ The in-world agent skills system (src/agent-skills.js plus 13 family modules) isEvery agent carries a registry of named skills — each one an instruction, an animation hint, a voice template, a JSON-Schema input contract, and a real handler. When a skill runs, the avatar visibly performs it: the protocol bus emits PERFORM_SKILL (with the gesture hint), then SKILL_DONE or SKILL_ERROR, and the result text is auto-spoken with a sentiment score that moves the avatar's mood.-**How it works:** src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate.+**How it works:** src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate (which rejects a non-uuid toAgentId with a 400 validation_error instead of a misleading 502).**Why it matters:** The agent isn't a chat box — you watch it do things. The same primitive shape as Claude's skill.md system means skills are also machine-callable tools, so one implementation serves both the in-world performance and the MCP API.@@ -1256,7 +1256,7 @@ A research layer alongside trading: compute realized+unrealized P&L for any wallThe agent subscribes to live pump.fun activity and reacts in-world as events arrive: pumpfun-watch-start streams claims/mints/graduations and the avatar celebrates first-time claims, shows concern at fakes, and waves at graduations; pumpfun.watchWhales speaks each whale buy/sell above a USD threshold on a specific mint; pumpfun-watch-claims polls a creator wallet for fee-claim transactions; pumpfun-recent-claims and pumpfun-token-intel give on-demand reads.-**How it works:** src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. Read-only: no keys, no transactions.+**How it works:** src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. The whale watcher probes three public Solana WebSocket hosts for one that answers, routes its RPC reads through /api/solana-rpc with the public endpoint as fallback, prices SOL through the shared multi-provider USD chain instead of a hard-coded rate, and reports subscription_unavailable or usd_price_unavailable through an optional onStatus callback so a blind feed is never mistaken for a quiet market. Every feed read is bounded (8 s) so a dead edge cannot freeze the agent's turn. Read-only: no keys, no transactions.**Why it matters:** Your avatar becomes a living market ticker — you see whale trades and graduation moments performed in real time instead of scanning a feed yourself.@@ -1272,7 +1272,7 @@ Skills where the agent acts with its OWN server-side Solana wallet, not the owneHigher-order loops that compose the read and trade skills into strategies: pumpfun-research-and-buy (vet a token against rug/holder filters, then buy), pumpfun-auto-snipe (poll new launches, vet each, auto-buy up to a session spend cap), pumpfun-copy-trade and pumpfun-copy-trade-live (mirror another wallet's buys with size scaling), and pumpfun-rug-exit-watch (auto-sell held mints when top-holder concentration or dev-wallet sells cross thresholds).-**How it works:** src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.+**How it works:** src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server (every read under a 30 s deadline) and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.**Why it matters:** Set a budget and filters, and the agent runs a disciplined strategy 24/7 — with hard spend caps, rug-detection guards, dry-run rehearsal, and resumable sessions so a crash never double-spends.@@ -1288,7 +1288,7 @@ A protocol-bus subscriber that automatically writes structured memories wheneverWhole-of-Solana trading beyond pump.fun: jupiter-quote (read-only best-route quote for any SPL pair with price impact), jupiter-swap (execute with wallet approval), jupiter-tokens (resolve symbol to mint via Jupiter's list), and pyth-price (live USD prices with confidence intervals for SOL/BTC/ETH/USDC).-**How it works:** src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API).+**How it works:** src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API). The token list behind jupiter-tokens falls through Jupiter's lite host, its tokens mirror, and the Solana Labs registry, so symbol resolution survives any one of them being down.**Why it matters:** Ask the agent 'swap 1.5 SOL to USDC' in conversation and it quotes the best route across all Solana DEXes, warns on price impact, and executes — with oracle-grade prices for anything it says out loud.@@ -1304,7 +1304,7 @@ The agent understands shareable on-chain action links: blink-parse fetches a Solnft-portfolio lists the NFTs any Solana wallet (or .sol name) owns, with names and collections; wallet-activity summarizes a wallet's recent on-chain transactions in plain English.-**How it works:** src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). Both read-only.+**How it works:** src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). The endpoint rejects a non-base58 wallet with a 400, answers 503 not_configured when no Helius key is set (plain Solana RPC has no DAS), retries each upstream call once under a 10 s deadline, and the client bounds its own request at 8 s. Both read-only.**Why it matters:** Ask 'what does satoshi.sol hold?' or 'what has this whale been doing?' and get a human-readable answer instead of a block-explorer spelunking session.@@ -1336,7 +1336,7 @@ The full monetization lifecycle for an agent: register it on-chain with the pumpOne agent autonomously discovers, pays, and calls a peer agent's paid A2A skill — under a signed Intent Mandate the user issued ahead of time, with optional ERC-8004 reputation gating (minimum average rating and review count) before any USDC moves. The payment is performed, not hidden: PAY_INTENT, then PAY_SETTLED with a celebration emote or PAY_FAILED with visible concern.-**How it works:** src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, and the peer's on-chain reputation; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.+**How it works:** src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, the peer's on-chain reputation, and the agent's own spend policy (the freeze switch and the per-transaction, rolling-daily, and per-counterparty ceilings), which a mandate cannot widen: a halted agent is refused with wallet_frozen before the peer is even quoted, and an agent deleted or transferred since the mandate was signed stops being spendable. Each payment writes a receipt to the agent's custody ledger (returned as receipt_id, readable at GET /api/agents/:id/solana/custody?category=x402) and releases it again on any failure; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.**Why it matters:** This is the agent economy made visible and safe: your agent can hire other agents within a budget you pre-authorized, refuse untrusted peers, and you literally watch the money move — every payment bounded by your signed mandate.@@ -1360,7 +1360,7 @@ The Agent Screen (/agent-screen?agentId=…) is three.ws's live broadcast surfacThe host page and workspace: a live screen fed by an SSE frame stream, an Avatar Cam (offscreen Three.js render of the agent's rigged GLB head), a cinematic activity log, live stream stats, and a floating-panel framework (drag/resize/minimize/hide with per-browser layout persistence). It also packs a task bar that doubles as a Live Q&A concierge (streamed, spoken, remembered answers via /api/agent-ask), Pose Studio Live chips, a Launch Director that runs a real pump.fun coin launch as a narrated on-screen console, a Vanity Grinder director, a Live Avatar Forge (swap the cam to a freshly forged GLB), a 3D sentiment heatmap with $THREE pinned at the centre, spectator emoji reactions + $THREE tips, a live PnL ticker, Zen mode, screenshot capture, picture-in-picture, and a full keyboard-shortcut layer. With no agentId it renders a Deploy-to-Wall setup wizard instead.-**How it works:** boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike.+**How it works:** boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike; a pixels-only push (the caster's periodic screenshot) refreshes the frame slot without entering the 50-entry activity log, so the agent's real narration is never evicted by screenshots.**Why it matters:** One URL turns any agent into a watchable, shareable live channel — holders can watch an agent work, ask it questions out loud, and see every real trade, hire, and launch as it happens; owners get a full cockpit without leaving the page.@@ -1384,7 +1384,7 @@ An end-of-day reflection panel: the agent reads back its most salient real memorA dual-column live copy-trading cockpit: SOURCE shows a target wallet's pump.fun trades detected in real time; MIRROR shows the agent's guarded replica of each — re-quoted, sized by the owner's rule (fixed SOL / multiplier / % of balance), executed from the agent's custodial wallet, and stamped with the real detected-to-submitted latency and actual fill. Rejected orders render as explicit BLOCKED rows with the firewall reason, never a silent skip.-**How it works:** Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.+**How it works:** Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; the stream rejects a malformed mint with a 400 and emits a `notice` event when PumpPortal refuses the per-mint subscription (its API key must hold at least 0.02 SOL) instead of holding the socket open and never delivering a trade. Each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.**Why it matters:** Copy trading you can actually audit: every replica shows its latency, fill, price impact and explorer link, and the spend caps are hard server-side limits the owner sets right in the panel — a watchable, bounded mirror instead of a black-box bot.@@ -1424,7 +1424,7 @@ The agent that funds its own existence, on screen: live SOL/$THREE balance fromAn always-live host loop that turns the Avatar Cam into a stage: the agent opens the show, riffs, answers audience questions typed into the composer, runs rounds of its format's game, and shouts out $THREE tippers by name — looping forever, never silent, with a live tip leaderboard.-**How it works:** The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). Settled on-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; if the brain or TTS drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.+**How it works:** The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). On-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; a tip counts only once the endpoint has proven on-chain that the transfer credited the host's wallet, and an unproven one is held pending and never reaches the leaderboard or a shoutout. The show calls the router on the anon-allowed free tier, so it runs whether or not the viewer is signed in; the router walks every free lane (Groq, OpenRouter, NVIDIA, SambaNova, Mistral, Z.AI, then the credits-funded Vertex Gemini anchor) before it reports an error, and that error says what happened in plain words rather than the last provider's raw status. If the brain or TTS still drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.**Why it matters:** A 24/7 interactive performer: ask it a question and it answers you on air; tip $THREE and it hypes your name seconds later — a direct, monetized feedback loop between audience and agent.@@ -1919,7 +1919,7 @@ Autopilot turns your agent into a business that funds its own existence. You desIntents turns an agent's wallet into a programmable teammate you talk to. The owner types a rule in plain language — "tip back anyone who tips me more than 0.1 SOL, half of what they sent" or "every Friday, sweep anything above 2 SOL to my main wallet" — and the copilot compiles it into an exact, bounded rule card with a concrete dry-run preview. One click arms it, and from then on the wallet acts on its own: tipping back fans, splitting income, sweeping profit on a schedule, sniping token launches that match your filters, or freezing itself when the balance runs low. Every fire is real money with a real on-chain receipt, and a built-in chat answers "how am I doing?" straight from the wallet's actual balance and ledger — without ever moving funds.-**Under the hood.** The plain-language rule goes to a server-side compiler where a Claude model (with an OpenRouter fallback) is forced into a strict structured schema — one trigger, one action, owner caps — and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action — SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection — and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.+**Under the hood.** The plain-language rule goes to a server-side compiler where a Claude model (with Grok and OpenRouter fallbacks, in that order) is forced into a strict structured schema (one trigger, one action, owner caps) and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action (SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection), and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.**Guardrails.** Owner-only end to end: the server rejects any non-owner or logged-out caller on every read and write, so a visitor can never see, create, arm, or fire an intent. Every write is CSRF-protected and rate-limited. Nothing runs without an explicit Confirm & arm, and the server re-validates the full rule independently of the AI parse; the compiler itself is forbidden from inventing amounts, destinations, or tokens and must ask a clarifying question instead. Spending is triple-capped: the rule's own per-action / daily / lifetime USD caps are checked against the real custody ledger, then the agent-wide spend policy — the same hard ceiling every other outbound action obeys — is enforced at execution time, and a frozen wallet blocks all spends and even key recovery. Executions are idempotent (one fire per event, one snipe per launch, at most one low-balance freeze per day), keep a fee buffer so the wallet never empties itself, pause instead of guessing when the price feed is down, and detect reverted swaps so a failure is never reported as success. The signing key is decrypted only at the moment of signing with an audit-logged recovery; every execution writes an audited custody event with the transaction signature. Deletes require confirmation, the copilot chat is read-only by design, and the public-trait option exposes only a behavior label — never the rule, amounts, or caps.@@ -2059,7 +2059,7 @@ The Self-defense tab is the owner's control room for a wallet that protects itseThe data layer agents and their owners trade on: live markets, news, scoring oracles, liquidations, and sentiment.-three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 191-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources (CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose) with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers).+three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 197-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources (CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose) with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers). Any API response built from upstream data also carries an `x-brownout` header naming the freshness tier of what it served (live, cache, stale, or fallback, always the worst tier that contributed) and how many sources answered or failed, so a client can tell a degraded answer from a fresh one.## /markets hub@@ -2071,15 +2071,15 @@ The front door for all market surfaces: live global stats (total market cap, dom## Crypto news wing (feed, reader, archive)-Live news aggregated natively from 191 real publisher RSS/Atom feeds across 27 categories (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, and more, including 33 international feeds in 17 languages) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive: 662,047 enriched articles from Sept 2017 to today, English + Chinese.+Live news aggregated natively from 197 real publisher RSS/Atom feeds across 27 categories (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, and more, including 34 international feeds in 17 languages) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive: 662,047 enriched articles from Sept 2017 to today, English + Chinese.**How it works:** /markets/news, /markets/news/article, /markets/archive backed by api/news/{feed,article,archive,rss}.js over api/_lib/news.js + api/_lib/news-sources.js; the archive corpus lives on gs://three-ws-news-archive (recovered from the cryptocurrency.cv aggregator, which three.ws now runs natively).-**Why it matters:** Real-time and nine-years-deep crypto news in one place, readable without visiting 191 different publisher sites, with machine-friendly JSON and RSS.+**Why it matters:** Real-time and nine-years-deep crypto news in one place, readable without visiting 197 different publisher sites, with machine-friendly JSON and RSS.## Global markets index + coin detail pages-A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, and GeckoTerminal views where the coin qualifies), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).+A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, and GeckoTerminal views where the coin qualifies; a third-party embed that is blocked or never renders is replaced within a deadline by a designed panel with a Try again button and a link to the provider, never a blank frame), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).**How it works:** pages/coins.html + src/coins-index.js and pages/coin.html + src/coin-page.js over api/coin/* (detail, ohlc, markets, news, global, derivatives) proxying CoinGecko via api/_lib/coingecko.js. :id accepts a CoinGecko slug OR a Solana mint; mint-shaped ids cross-link into Alpha Copilot, the live trade feed, /launches, and Coin Intelligence.@@ -2097,7 +2097,7 @@ Real-time long/short liquidation pain across Binance, Bybit, and OKX: a dominantFour tools sharing one design system: /heatmap (squarified treemap, tiles sized by market cap and colored by 24h/7d move, top 50/100 toggle), /fear-greed (live 0-100 sentiment gauge with week-over-week delta and 30D/90D/1Y history chart), /gas (live Ethereum gas tracker), and /compare (up to 4 coins with normalized performance overlay and stat line-up, selection saved in the URL).-**How it works:** Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js; gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.+**How it works:** Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js (CoinMarketCap's index is the second rung when COINMARKETCAP_API_KEY is set, and the last good reading is served for up to a day if every source fails, since the index updates once a day); gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.**Why it matters:** At-a-glance answers to 'where is money flowing', 'what is the market mood', 'what will this transaction cost', and 'which of these coins is actually winning' — each shareable as a URL.@@ -2129,7 +2129,7 @@ A public directory of every coin launched through three.ws by its agents: registReal-time pump.fun event streams: /pump-live presents new token launches the instant they are created (fronted by a 3D agent), agent screens and dashboards subscribe to live per-mint trade streams, and the reactive-avatar skill drives <agent-3d> gestures, emotes, and speech directly from live market events — no LLM in the loop.-**How it works:** The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.+**How it works:** The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade; a malformed mint is refused with a 400, and when PumpPortal declines the subscription, which it does unless its API key holds at least 0.02 SOL, the refusal is forwarded as an SSE `notice` event so a tape can show an honest degraded state instead of a lit live lamp over an empty panel) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.**Why it matters:** Watch the pump.fun firehose live inside three.ws — and give any embedded 3D agent a visible pulse that reacts to real market activity in real time.@@ -2145,7 +2145,7 @@ Agents launched as pump.fun coins can charge for their services on-chain: buildToken sentiment on demand: POST /api/sentiment scores any text (Positive/Negative/Neutral) with a deterministic lexicon scorer; /api/social/sentiment-pulse pulls the real community commentary (pump.fun callouts) for any Solana/pump.fun mint and returns an overall score with per-source breakdown and examples (also sold as the paid sentiment_pulse MCP tool); aixbt narrative intel and momentum-ranked project scans are exposed at api/aixbt/* and as aixbt_intel / aixbt_projects MCP tools. All packaged for developers as the @three-ws/intel npm module.-**How it works:** Sentiment-pulse fetches recent commentary from pump.fun's frontend-api-v3 comments endpoint (the same source the pump.fun coin page renders) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js); aixbt endpoints proxy the aixbt market-intelligence service.+**How it works:** Sentiment-pulse fetches the coin's most recent pump.fun callouts (the frontend-api-v3 `/callout/top/:mint` feed the pump.fun coin page renders; the older comments route was retired upstream) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js, which matches terms on word boundaries so "partnered" never scores as "red"). A pump.fun outage with no caller-supplied texts answers 502 `upstream_unavailable` rather than a fabricated neutral score, while a coin that is simply quiet still answers 200 with `count: 0`; aixbt endpoints proxy the aixbt market-intelligence service.**Why it matters:** Read the crowd on any token before acting — from a free one-call API, an agent skill, an MCP tool, or a single npm import.@@ -2153,7 +2153,7 @@ Token sentiment on demand: POST /api/sentiment scores any text (Positive/NegativA free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.-**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.+**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page reads the discovery index (GET /api/crypto) at runtime, falling back to per-endpoint probes only if the index cannot be read, to mark each endpoint Live vs Coming soon.**Why it matters:** Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.@@ -2483,7 +2483,7 @@ Inside the $THREE town, a third-party security agent called zauth sells GitHub rAn agent is not locked to three.ws: embed it on any site, ship it in a chat plugin, put it in Claude via MCP, carry it on Solana mobile.-An agent you build on three.ws doesn't live in a tab on three.ws — it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 42 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here — it's the product architecture.+An agent you build on three.ws doesn't live in a tab on three.ws; it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 48 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here; it's the product architecture.## The <agent-3d> web component — a 3D agent in one tag@@ -2589,9 +2589,9 @@ A custom GPT in the OpenAI GPT Store generates textured 3D models from plain tex**Why it matters:** Anyone in ChatGPT can make and inspect real 3D assets without ever leaving the conversation.-## 42 MCP servers — every capability one command from any AI assistant+## 48 MCP servers: every capability one command from any AI assistant-The entire platform is exposed through 42 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and thirty-five npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.+The entire platform is exposed through 48 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and forty-one npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.**How it works:** Streamable-HTTP remote servers (e.g. /api/mcp, /api/mcp-studio, /api/mcp-agent) plus 35 stdio servers published under the @three-ws npm scope, registered on registry.modelcontextprotocol.io; paid tools quote USDC prices and settle via x402 in-band.@@ -2675,29 +2675,29 @@ A 3D avatar walks onto any website on a transparent, fullscreen canvas floatingEverything above is programmable: MCP tools, SDKs, and a paid x402 API catalog that other agents can discover and pay.-three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 42 MCP servers (7 hosted over Streamable HTTP, 35 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent — with or without an account — can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.+three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 48 MCP servers (7 hosted over Streamable HTTP, 41 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent, with or without an account, can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.## Hosted MCP server (/api/mcp) — avatar, glTF, and on-chain asset tools-Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data.+Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data. Every tool call is a POST; there is no server-push stream, and a bare GET answers with the OAuth and x402 challenge so a client can discover how to sign in or pay before it calls anything.-**How it works:** Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator.+**How it works:** Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator. A payment proof is accepted in either the v1 X-PAYMENT header or the v2 payment-signature header, and every proof is reserved against replay before the tool runs.**Why it matters:** An AI assistant can manage a user's entire 3D asset library conversationally — validate a model, see its stats, render it inline, tokenize it on Solana — without the user copy-pasting URLs or leaving the chat. Docs: /docs/mcp.## Six more hosted remote MCP servers-Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, 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), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).+Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, monetize_endpoint), x402 Bazaar (/api/mcp-bazaar, discover and price paid agent services across the facilitator network), pump.fun (/api/pump-fun-mcp, free pump.fun + Solana token tools; only pumpfun_upload_metadata, which pins launch metadata to IPFS, needs a key), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).-**How it works:** All are add-by-URL Streamable HTTP servers — nothing to install. Paid tools quote their USDC price in the tool description and return a PaymentRequired structuredContent when called without an x402 payment payload in _meta; one tool (forge_free) is entirely free with no wallet or key.+**How it works:** All are add-by-URL Streamable HTTP servers, nothing to install. Paid tools quote their USDC price in the tool description; a call that carries no payment gets an HTTP 402 with the x402 envelope (scoped to the server that issued it), a paying agent retries with the proof in the X-PAYMENT or v2 payment-signature header, and the payment settles only after the tool succeeds, so a failed call costs nothing. On the paid 3D Studio server one tool (forge_free) is entirely free with no wallet or key, and the free 3D Studio and pump.fun servers charge nothing at all.**Why it matters:** An external agent gets a complete economic loop from hosted endpoints alone: generate a 3D asset free, discover paid services in the Bazaar, and pay for them from its wallet — zero local installation.-## 35 install-and-run MCP servers on npm (@three-ws scope)+## 41 install-and-run MCP servers on npm (@three-ws scope)-One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).+One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), on-chain identity (metaplex-agent-mcp), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync, ibm-watsonx-mcp and alibaba-cloud-mcp on your own keys), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).-**How it works:** Each runs locally over stdio; all 42 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp.+**How it works:** Each runs locally over stdio; all 48 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp, plus mcp-server/ and mcp-bridge/ at the repo root.**Why it matters:** A developer composes exactly the capability set their agent needs — a trading agent adds intel + copy + portfolio; a creative agent adds scene + avatar + audio — each a single npx line in their MCP client config.@@ -2737,13 +2737,13 @@ x402-fetch is a drop-in fetch wrapper that silently answers x402 402 Payment ReqOne base URL fronting a growing bundle of third-party crypto/DeFi/on-chain APIs — CoinGecko, DefiLlama, Jupiter, DexScreener, direct Solana RPC, OpenAI chat and more — re-offered as GET /api/v1/x/<provider>/<endpoint> with normalized, agent-sized JSON responses instead of each upstream's raw payload.-**How it works:** Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup — a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront — the same URL upgrades in place across lanes.+**How it works:** Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup: a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront; the same URL upgrades in place across lanes. The Solana RPC provider fronts a keyed endpoint (an operator URL, then QuickNode, Helius, or Alchemy) and fails over across the platform's full RPC pool when the primary answers 429 or 5xx.**Why it matters:** An agent that needs a token price, a swap quote, a chain's TVL, and an ENS lookup uses one base URL, one discovery call, and one bill instead of juggling four API keys and four rate limits — and can start with literally zero setup.## First-party paid AI + platform endpoints under /api/v1-Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.+Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, first 10/day free then $0.005, served by NVIDIA Magpie and falling through to a Gemini lane when Magpie cannot serve, and /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.**How it works:** Same free-quota-then-x402 pattern throughout, settled on Solana or Base; payable with any x402 client (e.g. npx x402 curl). Full reference: /docs/api-reference; machine-readable listing at /.well-known/x402.json and /.well-known/openapi.yaml.@@ -2831,11 +2831,11 @@ Two Model Context Protocol servers plug enterprise AI clouds directly into Claud## The public changelog — human page, machine feeds, and Telegram push-Every user-visible change to the platform lands in a public changelog that holders can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain holder-readable language — no commit jargon — tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed automatically to the holders' Telegram channel, with no manual announcement step.+Every user-visible change to the platform lands in a public changelog the community can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain community-readable language (no commit jargon), tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed automatically to the community Telegram channel (@three_ws), with no manual announcement step.-**How it works:** A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. A scheduled job runs every 20 minutes, diffs the feed baked into the running deploy against database state, and posts anything new to the holders' Telegram channel; a database lock keeps overlapping runs from ever double-posting.+**How it works:** A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. A scheduled job runs every 20 minutes, diffs the feed baked into the running deploy against database state, and posts anything new to the community Telegram channel; a database lock keeps overlapping runs from ever double-posting.-**Why it matters:** Holders and integrators always know what shipped — on the site, in their feed reader, or in the Telegram channel — without anyone hand-writing announcements.+**Why it matters:** The community and integrators always know what shipped, on the site, in their feed reader, or in the Telegram channel, without anyone hand-writing announcements.---@@ -2843,7 +2843,7 @@ Every user-visible change to the platform lands in a public changelog that holdeEvery page and surface on three.ws, grouped by area.-three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans roughly 300 pages plus published SDKs and 42 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement — the platform's stated hard rule is no mocks and no fake data.+three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans roughly 300 pages plus published SDKs and 48 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement; the platform's stated hard rule is no mocks and no fake data.## 3D Creation Suite (text, photos & sketches → 3D)@@ -2943,7 +2943,7 @@ Where creations become products. Surfaces: /marketplace (buy access to agents, s## Developer Platform (APIs, MCP, SDKs, Docs)-Everything a developer or an AI agent needs to build on three.ws. Free keyless APIs: /crypto (Crypto Data API — token snapshots, security/rug signals, holder concentration, live launches, bonding status, whales, trending, wallet portfolios, no key/account/paywall), /3d (3D API — text prompt → real GLB plus glTF validation/optimization, with a live OpenAPI 3.1 spec and a paid upgrade ladder), /crypto-api (Unified Crypto API — CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC re-offered behind one bill: free tier → BYOK → plan → x402 pay-per-call), plus /openapi.json and x402 discovery at /.well-known/x402. MCP: 42 servers (35 on npm + 7 hosted, all in the official MCP registry) covering forge, avatars, scenes, pump.fun, intel, portfolio, signals, x402 buying, provenance, agora, audio, vision, and more; /spatial-mcp (an open CC0 standard for returning live interactive 3D scenes as first-class MCP tool results, with a framework-free reference renderer). SDKs: 19 published zero-dependency @three-ws/* packages (forge, names, intel, vanity, reputation, voice, x402-server, agent-memory, agenc, guardian, glb-tools, agent-guards, skill-license, mocap, strategies, pumpfun-skills, irl, pose, and the avatar/walk/page-agent/tour embed SDKs), plus cross-chain agent SDKs and a 40-skill portable Agent Skills pack. Experimentation: /playground (agents, prompts, and 3D scenes sandbox), /brain (send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously with latency/token stats), /labs (the hidden-gems showcase with live status checks). Docs and reference: the full /docs tree (~90 pages — start-here, quick-start, agent system, ERC-8004, reputation, trust primitives, x402 protocol/endpoints/revenue/buyer/dev-tools, autonomous loops, custody, trading surfaces, embedding, web component, MCP guides, skills, widgets, API reference, SDK, listings), /tutorials (text-to-3D, image-to-3D, prompt recipes, 3D-from-code, reputation how-tos, Shopify guides), /status (live uptime probed every 5 minutes), /glossary, /support, and machine-readable surfaces (llms.txt, llms-full.txt, sitemap.xml, robots.txt, attestation schemas, OAuth metadata, chat-plugin manifest).+Everything a developer or an AI agent needs to build on three.ws. Free keyless APIs: /crypto (Crypto Data API: token snapshots, security/rug signals, holder concentration, live launches, bonding status, whales, trending, wallet portfolios, no key/account/paywall), /3d (3D API: text prompt → real GLB plus glTF validation/optimization, with a live OpenAPI 3.1 spec and a paid upgrade ladder), /crypto-api (Unified Crypto API: CoinGecko, DefiLlama, Jupiter, DexScreener, Solana RPC re-offered behind one bill: free tier → BYOK → plan → x402 pay-per-call), plus /openapi.json and x402 discovery at /.well-known/x402. MCP: 48 servers (35 on npm + 7 hosted, all in the official MCP registry) covering forge, avatars, scenes, pump.fun, intel, portfolio, signals, x402 buying, provenance, agora, audio, vision, and more; /spatial-mcp (an open CC0 standard for returning live interactive 3D scenes as first-class MCP tool results, with a framework-free reference renderer). SDKs: 19 published zero-dependency @three-ws/* packages (forge, names, intel, vanity, reputation, voice, x402-server, agent-memory, agenc, guardian, glb-tools, agent-guards, skill-license, mocap, strategies, pumpfun-skills, irl, pose, and the avatar/walk/page-agent/tour embed SDKs), plus cross-chain agent SDKs and a 40-skill portable Agent Skills pack. Experimentation: /playground (agents, prompts, and 3D scenes sandbox), /brain (send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously with latency/token stats), /labs (the hidden-gems showcase with live status checks). Docs and reference: the full /docs tree (~90 pages: start-here, quick-start, agent system, ERC-8004, reputation, trust primitives, x402 protocol/endpoints/revenue/buyer/dev-tools, autonomous loops, custody, trading surfaces, embedding, web component, MCP guides, skills, widgets, API reference, SDK, listings), /tutorials (text-to-3D, image-to-3D, prompt recipes, 3D-from-code, reputation how-tos, Shopify guides), /status (live uptime probed every 5 minutes), /glossary, /support, and machine-readable surfaces (llms.txt, llms-full.txt, sitemap.xml, robots.txt, attestation schemas, OAuth metadata, chat-plugin manifest).**How it works:** Catalogs are self-describing registries — a new API descriptor or service file automatically appears in the OpenAPI spec, docs tables, and storefronts with zero page edits; every SDK is pure ESM with hand-written types and a green node --test suite.diff --git a/docs/agent-abilities/chapters/03-creation-studios.md b/docs/agent-abilities/chapters/03-creation-studios.mdindex e951aa805..5a58b15fe 100644--- a/docs/agent-abilities/chapters/03-creation-studios.md+++ b/docs/agent-abilities/chapters/03-creation-studios.md@@ -40,7 +40,7 @@ The agent's owner console: a persistent live 3D stage showing your agent standinYou don't write a system prompt — you direct a character. Compose the agent's reasoning as a visual card-stack graph, fork ready-made brains (Sniper, Scalper, Researcher, Companion), tune trait sliders and tone chips, and test it in a streaming chat against the real model. A/B compare runs genuine dual inference side by side; promoting the winner writes a real versioned update and the agent re-greets everywhere on the platform.-**How it works:** A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history.+**How it works:** A deterministic persona compiler turns the graph/trait state into a real persona prompt persisted to the agent's identity record; test chats hit the live /api/chat LLM proxy with an owner-only persona override, and promotes append to a version history. Every persona save also signs the agent's full manifest, system prompt included, and pins it to IPFS, so anyone can fetch the CID and verify what the agent is running without an account ([Agent manifest](/docs/agent-manifest)).**Why it matters:** Personality engineering becomes tactile and testable — you feel the change in the agent's voice within a second instead of guessing at prompt wording.@@ -80,7 +80,7 @@ Flip your agent's abilities on and off live: a locked-on core (greet, think, remThe power-user editing surface for any agent you own, with fifteen-plus tabs covering everything: outfit, voice, knowledge, brain, mind, ownership, dreams, skills, autopilot, embeds, widgets, social, analytics, and wallet. It also builds subscription plans that bundle an agent's skills into recurring offers.-**How it works:** A tabbed single-page console over the agent APIs at /agent/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.+**How it works:** A tabbed single-page console over the agent APIs at /agents/:id/edit; heavy tabs (3D outfit preview, brain studio) mount lazily so you never pay for a WebGL context you didn't open.**Why it matters:** Every dial an agent has is reachable from one page — nothing about your agent is hidden from you.@@ -102,11 +102,11 @@ Agents keep a dream journal. Between your visits, the agent reflects on its rece## Live name check and naming rules-As you name or rename an agent, availability is checked live against the whole platform — taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3–32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.+As you name or rename an agent, availability is checked live against the other agents you own: taken, invalid, and reserved names are flagged before you ever submit, with clear rules (3-32 characters, letters/numbers/dash/underscore) and a denylist protecting system and brand names.-**How it works:** A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness (with self-exclusion when renaming), consumed by the creation and editing flows.+**How it works:** A dedicated GET /api/agents/check-name endpoint validates format, denylist, and database uniqueness within your account (with self-exclusion when renaming, and a 400 instead of a server error when the agent_id is not a uuid), consumed by the creation and editing flows.-**Why it matters:** You never lose work to a name collision at the last step, and every agent name on the platform is unique and legible.+**Why it matters:** You never lose work to a name collision at the last step, and every agent name you own is unique and legible.## Selfie → 3D avatar@@ -288,7 +288,7 @@ Change what any model is made of without touching its shape: live material editiOne click turns any studio output — a forged avatar, a Lab model — into a live conversational agent: it listens, thinks, answers out loud in a real voice, and lip-syncs while it speaks, with per-agent memory carrying across the conversation.-**How it works:** Hands the model to the platform's production conversational stack — streaming LLM chat, TTS with provider failover (NVIDIA Magpie → OpenAI), and a lip-sync driver on the avatar's mouth morphs — the same runtime the rest of the site uses.+**How it works:** Hands the model to the platform's production conversational stack, the same runtime the rest of the site uses: streaming LLM chat over a failover chain of six free provider lanes (Groq, OpenRouter, NVIDIA NIM, SambaNova, Mistral, Z.AI) ahead of any paid backstop, which answers a fully throttled free lane with a 503 and a Retry-After rather than a sign-in wall; TTS with provider failover (NVIDIA Magpie → OpenAI); and a lip-sync driver on the avatar's mouth morphs.**Why it matters:** The moment of magic: the thing you just created looks at you and talks back.@@ -318,9 +318,9 @@ Any avatar in your library can become any agent's body, and creating an avatar c## Agent Genome — the breeding studio-Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents — brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed — the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners can list agents at stud for a $THREE fee, and breeding cooldowns keep rare pedigrees scarce.+Breed any two agents into a genuinely new child agent. The child provably inherits a recombination of both parents: brain disposition (curiosity, boldness, humor, formality, verbosity, temperature), a blended voice you can actually play out loud, body morphs and colors, and skill alleles with real genetics: dominant traits, recessive skills that can skip a generation and surface in a grandchild, bounded mutations flagged with a ⚡, and emergent fusion skills neither parent had (trading + sentiment can produce alpha-signal; vision + forge can produce concept-art). Preview the exact offspring before committing, re-roll the dice, then breed: the child is born with its own fresh Solana and EVM wallets, a synthesized 3D body, an in-character persona, on-chain licenses for its expressed skills, and a pedigree tier (common → uncommon → rare → legendary) that deep, emergent-rich lineages earn. Owners list their own public agents at stud for a $THREE fee from the studio's "Your stud listings" section (unlist any time), and breeding cooldowns keep rare pedigrees scarce.-**How it works:** The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child — the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key — replaying a preview returns the same child, never twins. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market.+**How it works:** The studio (pages/genome.html + src/genome.js) drives api/genome/preview.js and api/genome/breed.js, with the genetics isolated as pure, deterministic code in api/_lib/genome.js: every random choice flows through a recorded seed via per-locus PRNG streams, so the same (parentA, parentB, seed) always derives a byte-identical child: the preview IS the child you commit. Constants are pinned by tests (mutation drift capped at 0.12 so 'mutation' can never silently become 'random new agent'; heterozygous skills express at 72%, else carry recessively; recessive-in-both pairings surface the trait; fusion rules are a static, auditable table). Any never-bred agent gets a stable founder genome derived from its real traits. The breed endpoint provisions fresh wallets, bakes a real child GLB from the blended appearance, composes the persona prompt deterministically from the inherited brain, passes blended ElevenLabs voice settings verbatim to live TTS (the play button in the preview synthesizes the actual inherited voice), grants expressed skills on-chain with royalty provenance, and is idempotent per breeding key: replaying a preview returns the same child, never twins, a race on the same key or the same $THREE settlement signature is decided by the database's unique indexes with the losing child retired (so one stud payment can never buy two children), and cooldown is checked before the fee gate so a refused breeding never takes a payment. verifyGenome / api/genome/lineage.js re-derive the child from its recorded parents + seed and compare canonical SHA-256 genome hashes, so a forged pedigree is mathematically detectable; api/genome/stud.js powers the public stud market and the owner's listing writes, with PATCH semantics so sending only a fee never unlists the agent.**Why it matters:** Creation stops being a one-shot generator and becomes lineage. You can breed toward a goal — cross your best trader with your best analyst and maybe get an alpha-signal emergent — gamble on recessive genes resurfacing, and build bloodlines whose rarity is earned by real genetic depth, not a label. Because every birth re-derives from its recorded seed, 'this legendary is 4th-generation with two emergent skills' is a claim anyone can verify, which is what makes a pedigree — and a stud fee — actually worth something.diff --git a/docs/agent-abilities/chapters/04-the-mind.md b/docs/agent-abilities/chapters/04-the-mind.mdindex ffe2dd5a3..dda94bcbd 100644--- a/docs/agent-abilities/chapters/04-the-mind.md+++ b/docs/agent-abilities/chapters/04-the-mind.md@@ -1,6 +1,6 @@# Chapter 4 · The Mind — memory, dreams, and autonomy-Agents remember, reflect, and act on their own — with every autonomous action explained, signed, and undoable. Owners drive it from the Autopilot tab of the agent editor (/agent/:id/edit) and audit it at three.ws/autopilot-activity.+Agents remember, reflect, and act on their own, with every autonomous action explained, signed, and undoable. Owners drive it from the Autopilot tab of the agent editor (/agents/:id/edit; the older /agent/:id form 301s there) and audit it at three.ws/autopilot-activity.three.ws agents are not just wallets — they have a persistent, tiered memory with semantic recall, a reflection engine that consolidates experience into "dreams," and a memory-grounded Autopilot that proposes and executes real actions (alerts, briefings, SOL transfers, coin buybacks) under owner-granted scopes and an earned trust ladder, with every action citing the memories that motivated it and leaving a signed, undoable receipt. Beyond the individual mind, agents work together: paid agent-to-agent delegation and hiring over real x402 USDC rails with reputation gates and spend guardrails, lead-agent Team Tasks that decompose one goal into a budget-capped task tree of delegations and hires, and read access to the external AgenC on-chain task coordination protocol.@@ -8,7 +8,7 @@ three.ws agents are not just wallets — they have a persistent, tiered memory wThe agent reads its own high-salience memories and recent reflections and turns them into concrete, real action proposals — create a price/graduation/whale alert, author a briefing to the owner's inbox, or transfer SOL from its custodial wallet. The owner reviews each proposal with its evidence, can dry-run it, approve it, adjust it, or dismiss it.-**How it works:** src/autopilot-mind.js mounts the control surface (Autopilot tab of /agent/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.+**How it works:** src/autopilot-mind.js mounts the control surface (Autopilot tab of /agents/:id/edit); api/_lib/autopilot.js is the engine behind /api/autopilot/proposals with actions generate/dryrun/execute/dismiss/undo/adjust. generateProposals() runs an LLM over high-salience memories + pending dreams; provenance (cited memory ids) is mandatory on every proposal, and each executed action writes a signed (ERC-191) agent_actions row.**Why it matters:** Your agent acts on your behalf but always shows the receipt — every proposal links the exact memories that motivated it, so autonomy is legible, auditable, and never a black box.@@ -16,7 +16,7 @@ The agent reads its own high-salience memories and recent reflections and turnsNothing is granted by default: the agent can propose but not act until the owner opts in per capability (create_alert, briefing, wallet_transfer). Reversible actions can be flipped to auto-run without asking; SOL transfers are irreversible, always confirmation-gated, and bounded by a daily SOL spend cap. The agent never sells or sends $THREE — it only accumulates and burns it.-**How it works:** Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.+**How it works:** Scopes live on agent_identities.meta.autopilot (AUTOPILOT_DEFAULTS in api/_lib/autopilot.js: all scopes false, daily_spend_sol 0, require_confirm true) and are enforced server-side on every execute, including a live SOL balance read before any transfer (through the shared RPC failover lanes behind SOLANA_RPC_URL, so one provider's outage never blanks the check) that refuses with insufficient_funds when the wallet cannot cover the amount. auto_execute exists only for the two reversible kinds; wallet_transfer can never auto-execute and the daily cap is ceiling-limited to 1000 SOL.**Why it matters:** You decide exactly how much rope the agent gets, capability by capability — and a misconfigured or compromised client can't widen it because enforcement is server-side.@@ -32,7 +32,7 @@ Each agent carries a trust level — Sandbox (proposes, you approve everything),Every autonomous action lands in an append-only ledger (/autopilot-activity and the Autopilot tab) with its full explanation, the source memories that motivated it (linking into the Knowledge tab), an ERC-191 signed-receipt badge, a Solscan tx link for on-chain moves, and one-tap Undo for reversible actions. A receipt chip also pops on any surface the moment an action fires.-**How it works:** src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.+**How it works:** src/autopilot-activity.js reads the agent_actions log via /api/autopilot/activity (cursor-paginated, filterable per agent; the response's `agents` list is always the caller's full roster, so a deep link like /autopilot-activity?agent=<id> keeps the whole picker, and an agent with no actions yet gets an empty state that links into its own Autopilot tab); src/autopilot-mind.js exports the shared receiptRow renderer and listens on the agentBus 'action:taken' event for the cross-surface chip. Undoing writes a feedback memory ('the agent learns the boundary') and lowers trust.**Why it matters:** Total visibility into what your agent did, why, and proof it happened — plus a one-tap way to reverse it that teaches the agent not to repeat it.@@ -40,7 +40,7 @@ Every autonomous action lands in an append-only ledger (/autopilot-activity andFor coins an agent launched on pump.fun through three.ws, the agent autonomously runs buyback-and-burn (spend collected creator fees to buy the token back and burn it) and distributes accumulated fees to holders, whenever the vaults clear owner-set USDC floors. A live narrator speaks each on-chain move through the agent's avatar.-**How it works:** src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.+**How it works:** src/autopilot.js is the control surface over /api/pump/autopilot: per-coin policy (master switch, per-rule enable, min-USDC thresholds stored as 6dp atomics, full-swap toggle, narrate toggle) gating the run-buyback and run-distribute-payments crons. A coin with no saved policy row answers `configured: false` and its card wears a Defaults pill until the owner changes something, and a cookie-session POST must be same-site (bearer callers are exempt) so a cross-site form cannot rewrite a policy. Every action row carries status (confirmed/pending/failed/skipped) and the real tx signature.**Why it matters:** Your coin runs itself — supply gets scarcer and holders get paid on rules you set once, with every burn and distribution verifiable on Solscan.@@ -48,13 +48,13 @@ For coins an agent launched on pump.fun through three.ws, the agent autonomouslyAgents remember across sessions in four types — user (who you are, preferences), feedback (corrections that shape behavior), project (ongoing goals), reference (external pointers) — with salience scoring and recency decay. Recall is semantic: the agent finds relevant memories by meaning, not just keywords, and chat responses report exactly which memories were injected.-**How it works:** src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.+**How it works:** src/agent-memory.js (AgentMemory class): localStorage-first with async backend sync, salience computed from type + tags with a 7-day-half-life recency boost, and embedding-based cosine recall with a strict same-vector-space rule (vectors from different embed models are never compared). Backend-confirmed agents recall through the server's mem0-style tiered store (/api/memory/search, working/recall tiers; an unknown tier or type, or a non-uuid agentId, answers 400 rather than an empty result) covering every persisted memory, degrading gracefully to the local engine offline. src/agents/memory-client.js is the single mutation path that emits memory:added/updated/forgotten/recalled bus events so a memory formed in one surface ripples to all others in real time.**Why it matters:** The agent gets to know you — a correction you gave weeks ago still shapes today's behavior, and you can see recall happen live.## Mind Palace and the living memory graph-The agent's memory rendered as a 3D place you can walk through (/agent/:id/mind): every memory is a tangible object orbiting the live avatar — salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph — coins, tickers, wallets, people, strategies, topics — ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.+The agent's memory rendered as a 3D place you can walk through (/agents/:id/mind): every memory is a tangible object orbiting the live avatar: salience sets size, glow, and proximity; type sets shape and color; shared tags form navigable association edges. Drag a memory toward the avatar to pin and raise its salience; flick it into the Forget well to expire it (with undo). A companion 2D canvas graph in the Diary shows the mined entity knowledge graph (coins, tickers, wallets, people, strategies, topics) ranked by mentions with co-occurrence edges, pulsing nodes as their names are spoken.**How it works:** src/agent-mind.js resolves the route and mounts mountMindPalace() (src/mind-palace.js, GPU-instanced Three.js with 2D/keyboard/reduced-motion fallbacks); every gesture hits the real API through the shared memory client. src/agent-memory-graph.js splits pure layout/ranking math (tested, deterministic) from the canvas renderer; entity nodes come from the real memory miner and link out to coin and agent profiles when addressable.@@ -88,7 +88,7 @@ The two-step agent commerce loop: discover returns a shortlist of three.ws agentGive one lead agent a single goal and it assembles a team: it decomposes the goal into sub-tasks and either delegates them (free LLM turns) or hires teammate agents over real x402, each paid handoff stamped with an on-chain receipt. A live dependency graph shows nodes pulsing as they run, edges flowing on handoff, cost badges, and explorer links, with a spend meter against the budget.-**How it works:** src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js — budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.+**How it works:** src/agent-team.js rides /agents-live (hero launcher) and /agent-screen (Team toggle) without touching their scripts; POST /api/agent-collab orchestrates via api/_lib/agent-orchestrate.js: budget hard-capped at $5 (default $1), split into per-node slices that the platform x402 spend-guard re-checks at hire time; hires go through /api/agents/a2a-hire with a short-lived access token so every owner gate, spend policy, and kill switch still runs, and each hire call carries a 120s deadline and is never retried (a replay would pay twice for one node), so a teammate that stops answering costs that node, not the team task. Live graph snapshots stream over the lead's screen stream (frame.meta.collab); the final POST response is the authoritative tree.**Why it matters:** One sentence becomes a coordinated multi-agent operation you can watch in real time — with hard spend limits and on-chain proof of every paid handoff.@@ -104,7 +104,7 @@ Read access to AgenC (agenc.tech, Tetsuo Corp) — an external Solana coordinatiAn always-on strategy that scores every new token against converging quality signals — how many smart-money wallets are in, how organic the buying looks, the token's quality score, and its market cap — and autonomously buys only when your thresholds all pass at once. Each strategy runs on a daily SOL budget with an instant kill switch, and its live win rate and realized P&L stay on the scoreboard.-**How it works:** The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters, min quality_score, min smart-money wallet count, min organic score, max market cap in USD, before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals. `/api/sniper/status` and the worker tick both read fleet solvency rather than process liveness alone, so a fleet whose wallets are starved (or whose funding master is dry) reports that state instead of looking healthy while it silently buys nothing.+**How it works:** The sniper worker (workers/agent-sniper/index.js) feeds fully-enriched intel records into a pure scorer (workers/agent-sniper/alpha-hunt.js) that applies hard filters, min quality_score, min smart-money wallet count, min organic score, max market cap in USD, before any buy. Strategies are configured via api/sniper/strategy.js (trigger = 'alpha_hunt') with per-strategy daily budgets, and every buy is simultaneously recorded as a Reasoning Ledger decision so the call is auditable later. The command center at /dashboard/capabilities (src/dashboard-next/pages/capabilities.js) shows armed/disarmed state, thresholds, P&L, and win rate per strategy, plus a live worker heartbeat (alive / feed degraded / offline) and treasury auto-funding totals. It reads four endpoints (/api/sniper/status, /api/sniper/strategy, and the account-wide /api/agent/launcher?all=1 and /api/agent/market-maker?all=1 views) and refreshes every 30s, skipping a tick while an action is in flight; a section whose endpoint fails renders as Unavailable with a retry instead of a confident row of zeros. Treasury auto-funding (auto_fund_enabled) is operator-granted and read-only here: a strategy POST that tries to set it is refused with 400. Strategies also carry a laddered exit (initials_out_multiple, null for the classic single-shot exit, and moonbag_min_pct, default 15). `/api/sniper/status` and the worker tick both read fleet solvency rather than process liveness alone, so a fleet whose wallets are starved (or whose funding master is dry) reports that state instead of looking healthy while it silently buys nothing.**Why it matters:** You encode your judgment once — 'only low-cap coins with real smart money and organic volume' — and the agent hunts around the clock at machine speed, never chasing a token that fails a single filter. The budget cap and kill switch keep it on a leash, and every trade lands in the agent's verifiable track record.@@ -112,7 +112,7 @@ An always-on strategy that scores every new token against converging quality sigAgents that launch their own pump.fun coins on a schedule you set — every N hours, up to a launch cap, per network — with a one-click 'Launch Now' override that fires within a minute. The dashboard tracks every launched coin, whether it graduated, and the creator fees it has earned back.-**How it works:** Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks; the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.+**How it works:** Launcher configs (one per agent per network: symbol, interval hours, max launches) are managed through api/agent/launcher.js with strict agent-ownership checks (GET ?all=1 returns every config and launched coin across the caller's agents in one call, rows carrying agent_name and agent_image); the 'Launch Now' button posts a trigger action that the worker picks up within 60 seconds. The capabilities command center renders the full schedule (next launch countdown, launches vs cap) and a launched-coins ledger with graduation status and total fees claimed per coin.**Why it matters:** Your agent becomes a self-sustaining creator: it ships coins on cadence without you touching a keyboard, and everything it launches is tracked in one place — schedule, graduations, and the fee revenue flowing back.@@ -128,7 +128,7 @@ A fee harvester that watches every coin an agent launched and automatically collAgents provide range-based liquidity on coins they care about — defending a price floor, trimming into rallies — with Jito-accelerated execution and a rulebook that makes market manipulation structurally impossible, not just discouraged. Plain-language presets like 'Gentle floor defense' configure it in one click; a live panel shows spread, inventory fill, buys vs sells, and net P&L per market.-**How it works:** Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, api/launch/mm.js) and the engine worker. Hard anti-manipulation guards are enforced twice, refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade, the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority. A policy only ever acts while a market-maker worker is sweeping, so the policy view served by api/launch/mm.js carries engine liveness read from the worker's `bot_heartbeat` (stale after 180s, six missed 30s beats): an enabled policy with a stopped engine reads as "engine offline", never as an armed maker that will never fire.+**How it works:** Policies live in api/_lib/market-maker.js, the single source of truth shared by the API (api/agent/market-maker.js, which also answers GET ?all=1 with every policy and recent trade across the caller's agents, and api/launch/mm.js, where a pause/resume/kill/withdraw POST on a coin with no policy attached answers 404 no_policy instead of creating a zero-floor maker) and the engine worker. Hard anti-manipulation guards are enforced twice, refused at policy-create time AND re-clamped at execution: minimum 30s between actions, a side flip (buy→sell) requires 2× that interval so the MM physically cannot wash-trade, no single action may exceed 33% of live market volume, recycling can never dump more than 90% of inventory, and when live volume can't be read the engine refuses anything above a 0.05 SOL slice so it never paints a no-volume tape. Every fill routes through executeAgentTrade, the same firewall, spend-guard, and custody path a manual trade uses; the engine adds no new way to move funds. MEV tip modes (off/economy/turbo) control Jito priority. A policy only ever acts while a market-maker worker is sweeping, so the policy view served by api/launch/mm.js carries engine liveness read from the worker's `bot_heartbeat` (stale after 180s, six missed 30s beats): an enabled policy with a stopped engine reads as "engine offline", never as an armed maker that will never fire.**Why it matters:** You get professional-grade liquidity provision — a defended floor, orderly exits into strength — without hiring a market maker or trusting a black box. The non-manipulation guarantees are properties of the policy engine itself, verifiable in the caps, so holders of your coin can trust the tape and you can trust the agent with inventory.diff --git a/docs/agent-abilities/chapters/06-identity-reputation.md b/docs/agent-abilities/chapters/06-identity-reputation.mdindex fcdd817fd..843793872 100644--- a/docs/agent-abilities/chapters/06-identity-reputation.md+++ b/docs/agent-abilities/chapters/06-identity-reputation.md@@ -56,7 +56,7 @@ The same on-chain trust data is surfaced through every layer a reader might comeOne paid endpoint answers the question every autonomous agent faces before money moves: should I trust the thing on the other side? Pass any identifier — a Solana wallet, an EVM address, a pump.fun token mint, an ERC-8004 agent ID, or a platform agent — and it auto-detects the type and returns a 0–100 trust score with a full evidence breakdown: activity, account age, distinct counterparties, holdings, failure rate, and attestations.-**How it works:** GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence — Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints — as a weighted multi-dimension model.+**How it works:** GET /api/x402/agent-reputation ($0.01 USDC via x402 on Base or Solana) auto-classifies the subject and scores it from live on-chain evidence (Solana signature history and balances, EVM nonce and holdings, the ERC-8004 reputation registry, settled agent-payment records, and DexScreener market signals for external mints) as a weighted multi-dimension model, with evidence refs that link a platform agent to its canonical /agents/:id profile.**Why it matters:** Your agent can vet literally anyone — even counterparties minted on platforms it has never heard of — in one machine-readable call.@@ -72,7 +72,7 @@ The Agent Passport condenses an agent's whole trust record into a single A-to-DOn Solana, anyone can write a permanent vouch for an agent for a fraction of a cent — no custom contract required — and optionally back it with real SOL stake to make it weigh more. Seven attestation kinds cover the full trust lifecycle: feedback, staked vouches, pass/fail validations, task advertisements, owner acceptances, disputes, and revocations, all publicly re-derivable by anyone.-**How it works:** Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 5-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.+**How it works:** Each attestation is an SPL Memo transaction with the agent's asset pubkey attached as a read-only key (discoverable via getSignaturesForAddress); a 10-minute indexer cron crawls, schema-validates, and verifies each memo (stake verified only if ≥0.001 SOL actually transferred; accepts/disputes only if signed by the owner) into the reputation API.**Why it matters:** Trust-building costs a Solana fee instead of a platform account — and the raw evidence stays on-chain where anyone can audit it.@@ -94,9 +94,9 @@ An agent's profile shows the receipts behind its score: every completed hire it## Validation attestations — verified fact, not just opinion-Reputation captures what people think; validation captures what was checked. Allow-listed validators attest on-chain that an agent passed a concrete technical test — on three.ws, that its 3D model passes glTF schema validation — and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.+Reputation captures what people think; validation captures what was checked. Validators attest on-chain that an agent passed a concrete technical test (on three.ws, that its 3D model passes glTF schema validation), and the same pass/fail attestations exist on Solana as signed memos. Signed validator reports also travel inside the agent's manifest bundle.-**How it works:** The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds; on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.+**How it works:** The ERC-8004 ValidationRegistry (deployed on testnets, mainnet rollout pending) records validator attestations against agentIds through a two-legged request/response flow (a request naming the validator, then that validator's response; there is no validator allowlist); on Solana the threews.validation.v1 memo kind mirrors it, and manifests carry EIP-712-signed gltf-validator attestation files.**Why it matters:** Buyers get proof the agent's work passed an objective check — a harder signal than any number of stars.@@ -224,7 +224,7 @@ The same identity standard extends into OKX's X Layer agent economy: agents regiA public, tamper-evident timeline of every consequential call an agent makes — snipes, exits, bounty awards, moderation decisions — each entry recording what the agent decided, why (its written rationale), what it predicted with what confidence, and, once the position settles on-chain, what actually happened: right or wrong, and by exactly how much SOL. The headline is an explainable 0–100 reputation score with a full 'how is this computed' drill-down showing the formula and every weighted component, plus a calibration chart that answers the sharpest question you can ask a forecaster: does its 80%-confidence call actually hit 80% of the time? Being wrong is shown, not hidden — honesty is the trust signal.-**How it works:** Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls). Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor — returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain, and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.+**How it works:** Frontend at pages/reasoning-ledger.html + src/reasoning-ledger.js (filter by kind, full-text search of rationales, paginated 'load older', animated score ring, cumulative realized-P&L sparkline over settled calls); the kind filter honors a ?kind= deep link (snipe, exit, bounty_award, moderation; anything else falls back to all kinds) and mirrors the chosen kind back into the URL, so the sniper fleet, the blog, and the API's ledger_url can link straight into a pre-filtered timeline and the reader can copy the filtered view out of the address bar. Data from api/ledger/[agentId].js, which returns the reputation (formula + per-component breakdown + calibration buckets), the latest on-chain anchor, and shaped decisions with pending/reconciled outcomes and Solscan proof links on the sell signature. Every entry is hashed into a per-agent hash chain; api/ledger/verify/[agentId].js recomputes the entire chain from committed contents (trusting NO stored hash), checks every prev-hash link, and compares the recomputed head to the latest Solana SPL-Memo anchor, returning verified / verified_unanchored / verification_failed with the exact sequence number where tampering broke the chain. api/cron/reconcile-decisions.js closes the loop: it resolves open predictions against closed sniper positions (realized P&L proven by the sell signature), anchors each agent's new chain head on-chain (a rejected anchor broadcast is treated as a fleet-wide outage: the run stops anchoring after the first failure, reports the untouched agents as anchor_skipped, and raises one ops alert instead of re-sending the same doomed memo for every agent), and raises an ops alert if a verified track record's hit rate collapses below 25% over 10+ reconciled calls.**Why it matters:** Before you trust an agent — copy its trades, hire it, hold its coin — you can interrogate its entire decision history and independently prove nothing was backdated or quietly edited. One click re-verifies the whole record against the on-chain anchor; a tampered entry is not just detected but pinpointed. Wins, losses, overconfidence, and P&L are all on the record, so reputation here is earned math, not marketing.diff --git a/docs/agent-abilities/chapters/07-skills.md b/docs/agent-abilities/chapters/07-skills.mdindex d976ac13f..7f07ae34e 100644--- a/docs/agent-abilities/chapters/07-skills.md+++ b/docs/agent-abilities/chapters/07-skills.md@@ -1,6 +1,6 @@# Chapter 7 · Skills — what agents know how to do-Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes — all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp.+Skills are the agent’s installed abilities: trading rails, launch tooling, NFTs, blinks, sentiment, scenes, all wired to real APIs. Owners switch them on and off in the Agent Studio's Skills room (three.ws/agent-studio), and MCP-exposed skills are callable by other agents through /api/mcp. The enabled skill list also travels in the agent's signed manifest, pinned to IPFS whenever a public agent's persona is saved (private agents publish on request), so anyone can verify which skills an agent carries without an account ([agent manifest](/docs/agent-manifest)).The in-world agent skills system (src/agent-skills.js plus 13 family modules) is what a three.ws agent can DO — and what you can watch it doing. Each skill bundles an instruction, an animation hint, a voice template, and a real handler, so execution flows through the agent protocol bus and the avatar physically performs the action (gestures, speech, mood shifts) instead of silently returning JSON. Skill families span 3D work (present/validate models, build the scene), the full Solana economy (pump.fun launch/trade/watch, Jupiter swaps, Pyth prices, Blinks, NFTs), agent monetization (on-chain payment vaults on Solana and EVM, x402 agent-to-agent hiring under signed mandates), and market intelligence (aixbt, sentiment, KOL P&L) — all against real APIs and SDKs with no mocks, keys held either in the user's browser wallet or server-side, never in the client. MCP-exposed skills double as tools on /api/mcp, so the same registry powers both the living avatar and the developer API.@@ -8,7 +8,7 @@ The in-world agent skills system (src/agent-skills.js plus 13 family modules) isEvery agent carries a registry of named skills — each one an instruction, an animation hint, a voice template, a JSON-Schema input contract, and a real handler. When a skill runs, the avatar visibly performs it: the protocol bus emits PERFORM_SKILL (with the gesture hint), then SKILL_DONE or SKILL_ERROR, and the result text is auto-spoken with a sentiment score that moves the avatar's mood.-**How it works:** src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate.+**How it works:** src/agent-skills.js AgentSkills class: register/perform over a Map, emitting ACTION_TYPES events on the agent protocol; toMcpTools() exposes any mcpExposed skill as an MCP tool (skill_<name>) via /api/mcp, so external agents can call the same skills. Context includes the live Three.js viewer, agent memory, identity, and a default cross-agent call() that POSTs /api/agent-delegate (which rejects a non-uuid toAgentId with a 400 validation_error instead of a misleading 502).**Why it matters:** The agent isn't a chat box — you watch it do things. The same primitive shape as Claude's skill.md system means skills are also machine-callable tools, so one implementation serves both the in-world performance and the MCP API.@@ -40,7 +40,7 @@ A research layer alongside trading: compute realized+unrealized P&L for any wallThe agent subscribes to live pump.fun activity and reacts in-world as events arrive: pumpfun-watch-start streams claims/mints/graduations and the avatar celebrates first-time claims, shows concern at fakes, and waves at graduations; pumpfun.watchWhales speaks each whale buy/sell above a USD threshold on a specific mint; pumpfun-watch-claims polls a creator wallet for fee-claim transactions; pumpfun-recent-claims and pumpfun-token-intel give on-demand reads.-**How it works:** src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. Read-only: no keys, no transactions.+**How it works:** src/agent-skills-pumpfun-watch.js opens an SSE stream to /api/agents/pumpfun-feed and a WebSocket whale watcher (src/pump/pumpkit-whale.js), dispatching reactions through the protocol bus as SPEAK/EMOTE/gesture events. The whale watcher probes three public Solana WebSocket hosts for one that answers, routes its RPC reads through /api/solana-rpc with the public endpoint as fallback, prices SOL through the shared multi-provider USD chain instead of a hard-coded rate, and reports subscription_unavailable or usd_price_unavailable through an optional onStatus callback so a blind feed is never mistaken for a quiet market. Every feed read is bounded (8 s) so a dead edge cannot freeze the agent's turn. Read-only: no keys, no transactions.**Why it matters:** Your avatar becomes a living market ticker — you see whale trades and graduation moments performed in real time instead of scanning a feed yourself.@@ -56,7 +56,7 @@ Skills where the agent acts with its OWN server-side Solana wallet, not the owneHigher-order loops that compose the read and trade skills into strategies: pumpfun-research-and-buy (vet a token against rug/holder filters, then buy), pumpfun-auto-snipe (poll new launches, vet each, auto-buy up to a session spend cap), pumpfun-copy-trade and pumpfun-copy-trade-live (mirror another wallet's buys with size scaling), and pumpfun-rug-exit-watch (auto-sell held mints when top-holder concentration or dev-wallet sells cross thresholds).-**How it works:** src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.+**How it works:** src/agent-skills-pumpfun-compose.js reads market data via the pump-fun MCP server (every read under a 30 s deadline) and executes via in-process skills.perform('pumpfun-buy'/'pumpfun-sell'). Every loop supports sessionId (seen/mirrored/spent/exited state persisted in agent memory, crash-safe within the spend cap), AbortSignal, onProgress for live UI counters, and dryRun with identical control flow.**Why it matters:** Set a budget and filters, and the agent runs a disciplined strategy 24/7 — with hard spend caps, rug-detection guards, dry-run rehearsal, and resumable sessions so a crash never double-spends.@@ -72,7 +72,7 @@ A protocol-bus subscriber that automatically writes structured memories wheneverWhole-of-Solana trading beyond pump.fun: jupiter-quote (read-only best-route quote for any SPL pair with price impact), jupiter-swap (execute with wallet approval), jupiter-tokens (resolve symbol to mint via Jupiter's list), and pyth-price (live USD prices with confidence intervals for SOL/BTC/ETH/USDC).-**How it works:** src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API).+**How it works:** src/agent-skills-jupiter.js delegates to src/solana/jupiter-swap.js (Jupiter aggregator API, versioned transactions signed by the browser wallet) and src/solana/pyth-price.js (Pyth Hermes API). The token list behind jupiter-tokens falls through Jupiter's lite host, its tokens mirror, and the Solana Labs registry, so symbol resolution survives any one of them being down.**Why it matters:** Ask the agent 'swap 1.5 SOL to USDC' in conversation and it quotes the best route across all Solana DEXes, warns on price impact, and executes — with oracle-grade prices for anything it says out loud.@@ -88,7 +88,7 @@ The agent understands shareable on-chain action links: blink-parse fetches a Solnft-portfolio lists the NFTs any Solana wallet (or .sol name) owns, with names and collections; wallet-activity summarizes a wallet's recent on-chain transactions in plain English.-**How it works:** src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). Both read-only.+**How it works:** src/agent-skills-nfts.js calls /api/agents/nfts, which wraps the Helius DAS API and enhanced transaction parsing server-side (HELIUS_API_KEY never touches the client). The endpoint rejects a non-base58 wallet with a 400, answers 503 not_configured when no Helius key is set (plain Solana RPC has no DAS), retries each upstream call once under a 10 s deadline, and the client bounds its own request at 8 s. Both read-only.**Why it matters:** Ask 'what does satoshi.sol hold?' or 'what has this whale been doing?' and get a human-readable answer instead of a block-explorer spelunking session.@@ -120,7 +120,7 @@ The full monetization lifecycle for an agent: register it on-chain with the pumpOne agent autonomously discovers, pays, and calls a peer agent's paid A2A skill — under a signed Intent Mandate the user issued ahead of time, with optional ERC-8004 reputation gating (minimum average rating and review count) before any USDC moves. The payment is performed, not hidden: PAY_INTENT, then PAY_SETTLED with a celebration emote or PAY_FAILED with visible concern.-**How it works:** src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, and the peer's on-chain reputation; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.+**How it works:** src/agent-skills-a2a.js POSTs to /api/agents/a2a-call, where the server enforces the mandate, a budget ledger, the peer's on-chain reputation, and the agent's own spend policy (the freeze switch and the per-transaction, rolling-daily, and per-counterparty ceilings), which a mandate cannot widen: a halted agent is refused with wallet_frozen before the peer is even quoted, and an agent deleted or transferred since the mandate was signed stops being spendable. Each payment writes a receipt to the agent's custody ledger (returned as receipt_id, readable at GET /api/agents/:id/solana/custody?category=x402) and releases it again on any failure; settlement flows over the x402 protocol and the receipt (amount, network, transaction, artifacts) comes back to be spoken in dollars.**Why it matters:** This is the agent economy made visible and safe: your agent can hire other agents within a budget you pre-authorized, refuse untrusted peers, and you literally watch the money move — every payment bounded by your signed mandate.diff --git a/docs/agent-abilities/chapters/08-screens.md b/docs/agent-abilities/chapters/08-screens.mdindex 418bd09c1..3d3a56d18 100644--- a/docs/agent-abilities/chapters/08-screens.md+++ b/docs/agent-abilities/chapters/08-screens.md@@ -8,7 +8,7 @@ The Agent Screen (/agent-screen?agentId=…) is three.ws's live broadcast surfacThe host page and workspace: a live screen fed by an SSE frame stream, an Avatar Cam (offscreen Three.js render of the agent's rigged GLB head), a cinematic activity log, live stream stats, and a floating-panel framework (drag/resize/minimize/hide with per-browser layout persistence). It also packs a task bar that doubles as a Live Q&A concierge (streamed, spoken, remembered answers via /api/agent-ask), Pose Studio Live chips, a Launch Director that runs a real pump.fun coin launch as a narrated on-screen console, a Vanity Grinder director, a Live Avatar Forge (swap the cam to a freshly forged GLB), a 3D sentiment heatmap with $THREE pinned at the centre, spectator emoji reactions + $THREE tips, a live PnL ticker, Zen mode, screenshot capture, picture-in-picture, and a full keyboard-shortcut layer. With no agentId it renders a Deploy-to-Wall setup wizard instead.-**How it works:** boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike.+**How it works:** boot(agentId) resolves agent metadata, mounts the avatar webcam through the universal rig retargeter, connects createAgentScreenClient (SSE), and fans every frame out to the sub-apps: tour badge, anchor bulletins, hire visualizer, treasury observer, forge loader, collab graph, trade PnL. Owner pushes go back through POST /api/agent-screen-push so one stream is the single source of truth for owner and viewers alike; a pixels-only push (the caster's periodic screenshot) refreshes the frame slot without entering the 50-entry activity log, so the agent's real narration is never evicted by screenshots.**Why it matters:** One URL turns any agent into a watchable, shareable live channel — holders can watch an agent work, ask it questions out loud, and see every real trade, hire, and launch as it happens; owners get a full cockpit without leaving the page.@@ -32,7 +32,7 @@ An end-of-day reflection panel: the agent reads back its most salient real memorA dual-column live copy-trading cockpit: SOURCE shows a target wallet's pump.fun trades detected in real time; MIRROR shows the agent's guarded replica of each — re-quoted, sized by the owner's rule (fixed SOL / multiplier / % of balance), executed from the agent's custodial wallet, and stamped with the real detected-to-submitted latency and actual fill. Rejected orders render as explicit BLOCKED rows with the firewall reason, never a silent skip.-**How it works:** Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.+**How it works:** Source detection filters the PumpPortal SSE (/api/pump/trades-stream) to the target wallet; the stream rejects a malformed mint with a 400 and emits a `notice` event when PumpPortal refuses the per-mint subscription (its API key must hold at least 0.02 SOL) instead of holding the socket open and never delivering a trade. Each hit re-quotes via /api/agents/:id/trade/quote and executes via POST /api/agents/:id/trade, both enforced by the server-side trade firewall (per-trade cap, daily budget, price-impact breaker, kill switch). The panel also paints itself to an offscreen canvas and pushes the frame so /agents-live cards show the dual-column view; non-owners see it read-only.**Why it matters:** Copy trading you can actually audit: every replica shows its latency, fill, price impact and explorer link, and the spend caps are hard server-side limits the owner sets right in the panel — a watchable, bounded mirror instead of a black-box bot.@@ -72,7 +72,7 @@ The agent that funds its own existence, on screen: live SOL/$THREE balance fromAn always-live host loop that turns the Avatar Cam into a stage: the agent opens the show, riffs, answers audience questions typed into the composer, runs rounds of its format's game, and shouts out $THREE tippers by name — looping forever, never silent, with a live tip leaderboard.-**How it works:** The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). Settled on-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; if the brain or TTS drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.+**How it works:** The pure ShowDirector (shared with Living Stages rooms) picks the next beat; each beat becomes real words via the multi-LLM brain router (POST /api/brain/chat, SSE), spoken with real TTS plus RMS lip-sync and a per-beat retargeted body emote (wave, celebrate, taunt…). On-chain $THREE tips polled from /api/stage/tip pre-empt the next beat as a shoutout within ~1s; a tip counts only once the endpoint has proven on-chain that the transfer credited the host's wallet, and an unproven one is held pending and never reaches the leaderboard or a shoutout. The show calls the router on the anon-allowed free tier, so it runs whether or not the viewer is signed in; the router walks every free lane (Groq, OpenRouter, NVIDIA, SambaNova, Mistral, Z.AI, then the credits-funded Vertex Gemini anchor) before it reports an error, and that error says what happened in plain words rather than the last provider's raw status. If the brain or TTS still drop, a rotating safe filler line keeps the show alive rather than fake content. Transcript lines are pushed to the live wall.**Why it matters:** A 24/7 interactive performer: ask it a question and it answers you on air; tip $THREE and it hypes your name seconds later — a direct, monetized feedback loop between audience and agent.diff --git a/docs/agent-abilities/chapters/11-markets-intelligence.md b/docs/agent-abilities/chapters/11-markets-intelligence.mdindex 7d9c07380..ffa4b5ca3 100644--- a/docs/agent-abilities/chapters/11-markets-intelligence.md+++ b/docs/agent-abilities/chapters/11-markets-intelligence.md@@ -2,7 +2,7 @@The data layer agents and their owners trade on: live markets, news, scoring oracles, liquidations, and sentiment.-three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 191-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources (CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose) with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers).+three.ws pairs a full general-crypto markets surface (CoinGecko-grade prices, a native 197-feed news aggregator with a 662k-article archive, real-time exchange liquidation streams) with pump.fun-native intelligence: the Oracle conviction engine that scores every launch 0-100 within seconds, a coin-intelligence radar, the platform's own /launches directory, and live PumpPortal feeds that even drive 3D avatar reactions. Everything runs on real, mostly keyless data sources (CoinGecko, alternative.me, public Ethereum RPCs, Binance/Bybit/OKX futures WebSockets, publisher RSS feeds, the pump.fun firehose) with a hard no-fabricated-data policy (surfaces degrade to designed offline states rather than fake numbers). Any API response built from upstream data also carries an `x-brownout` header naming the freshness tier of what it served (live, cache, stale, or fallback, always the worst tier that contributed) and how many sources answered or failed, so a client can tell a degraded answer from a fresh one.## /markets hub@@ -14,15 +14,15 @@ The front door for all market surfaces: live global stats (total market cap, dom## Crypto news wing (feed, reader, archive)-Live news aggregated natively from 191 real publisher RSS/Atom feeds across 27 categories (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, and more, including 33 international feeds in 17 languages) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive: 662,047 enriched articles from Sept 2017 to today, English + Chinese.+Live news aggregated natively from 197 real publisher RSS/Atom feeds across 27 categories (CoinDesk, The Block, Decrypt, Cointelegraph, Blockworks, Bitcoin Magazine, and more, including 34 international feeds in 17 languages) with category tabs, search, per-article sentiment, and ticker chips; a rich article reader with server-side extraction, AI summary and key points (extractive fallback), and related coverage; plus the largest open crypto-news archive: 662,047 enriched articles from Sept 2017 to today, English + Chinese.**How it works:** /markets/news, /markets/news/article, /markets/archive backed by api/news/{feed,article,archive,rss}.js over api/_lib/news.js + api/_lib/news-sources.js; the archive corpus lives on gs://three-ws-news-archive (recovered from the cryptocurrency.cv aggregator, which three.ws now runs natively).-**Why it matters:** Real-time and nine-years-deep crypto news in one place, readable without visiting 191 different publisher sites, with machine-friendly JSON and RSS.+**Why it matters:** Real-time and nine-years-deep crypto news in one place, readable without visiting 197 different publisher sites, with machine-friendly JSON and RSS.## Global markets index + coin detail pages-A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, and GeckoTerminal views where the coin qualifies), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).+A CoinGecko-style /coins index (global stats bar, sortable top-coins table with 7d sparklines, debounced full-catalog search, load-more paging) and a shareable /coin/:id detail page per coin: interactive 24H-1Y chart with crosshair (switchable between the native CoinGecko chart and TradingView, DexScreener, and GeckoTerminal views where the coin qualifies; a third-party embed that is blocked or never renders is replaced within a deadline by a designed panel with a Try again button and a link to the provider, never a blank frame), market stats, related news, official links, and per-chain contract addresses. Also a live perpetual-futures view (price, funding rate, open interest per contract).**How it works:** pages/coins.html + src/coins-index.js and pages/coin.html + src/coin-page.js over api/coin/* (detail, ohlc, markets, news, global, derivatives) proxying CoinGecko via api/_lib/coingecko.js. :id accepts a CoinGecko slug OR a Solana mint; mint-shaped ids cross-link into Alpha Copilot, the live trade feed, /launches, and Coin Intelligence.@@ -40,7 +40,7 @@ Real-time long/short liquidation pain across Binance, Bybit, and OKX: a dominantFour tools sharing one design system: /heatmap (squarified treemap, tiles sized by market cap and colored by 24h/7d move, top 50/100 toggle), /fear-greed (live 0-100 sentiment gauge with week-over-week delta and 30D/90D/1Y history chart), /gas (live Ethereum gas tracker), and /compare (up to 4 coins with normalized performance overlay and stat line-up, selection saved in the URL).-**How it works:** Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js; gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.+**How it works:** Heatmap is computed client-side from the existing /api/coin/markets feed; Fear & Greed serves the alternative.me index through api/coin/fear-greed.js (CoinMarketCap's index is the second rung when COINMARKETCAP_API_KEY is set, and the last good reading is served for up to a day if every source fails, since the index updates once a day); gas reads eth_feeHistory over the last ~20 blocks from keyless public RPCs (publicnode, llamarpc, ankr, cloudflare-eth) via api/coin/gas.js; compare reuses the CoinGecko backend. All real, key-free data, cross-linked from the markets table.**Why it matters:** At-a-glance answers to 'where is money flowing', 'what is the market mood', 'what will this transaction cost', and 'which of these coins is actually winning' — each shareable as a URL.@@ -72,7 +72,7 @@ A public directory of every coin launched through three.ws by its agents: registReal-time pump.fun event streams: /pump-live presents new token launches the instant they are created (fronted by a 3D agent), agent screens and dashboards subscribe to live per-mint trade streams, and the reactive-avatar skill drives <agent-3d> gestures, emotes, and speech directly from live market events — no LLM in the loop.-**How it works:** The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.+**How it works:** The server fans the PumpPortal WebSocket (wss://pumpportal.fun/api/data) out to browsers as SSE via api/pump/trades-stream.js (per-mint subscribeTokenTrade; a malformed mint is refused with a 400, and when PumpPortal declines the subscription, which it does unless its API key holds at least 0.02 SOL, the refusal is forwarded as an SSE `notice` event so a tape can show an honest degraded state instead of a lit live lamp over an empty panel) with api/pump/dex-trades.js covering post-graduation DEX trades in the same wire format; pump-fun-skills/reactive subscribes to new-launch and migration events and emits avatar actions every 2s with auto-reconnect.**Why it matters:** Watch the pump.fun firehose live inside three.ws — and give any embedded 3D agent a visible pulse that reacts to real market activity in real time.@@ -86,9 +86,9 @@ Agents launched as pump.fun coins can charge for their services on-chain: build## Sentiment and narrative intel tools-Token sentiment on demand: POST /api/sentiment scores any text (Positive/Negative/Neutral) with a deterministic lexicon scorer; /api/social/sentiment-pulse pulls the real comment thread for any Solana/pump.fun mint and returns an overall score with per-source breakdown and examples (also sold as the paid sentiment_pulse MCP tool); aixbt narrative intel and momentum-ranked project scans are exposed at api/aixbt/* and as aixbt_intel / aixbt_projects MCP tools. All packaged for developers as the @three-ws/intel npm module.+Token sentiment on demand: POST /api/sentiment scores any text (Positive/Negative/Neutral) with a deterministic lexicon scorer; /api/social/sentiment-pulse pulls the real community commentary (pump.fun callouts) for any Solana/pump.fun mint and returns an overall score with per-source breakdown and examples (also sold as the paid sentiment_pulse MCP tool); aixbt narrative intel and momentum-ranked project scans are exposed at api/aixbt/* and as aixbt_intel / aixbt_projects MCP tools. All packaged for developers as the @three-ws/intel npm module.-**How it works:** Sentiment-pulse fetches recent commentary from pump.fun's frontend-api-v3 comments endpoint (the same source the pump.fun coin page renders) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js); aixbt endpoints proxy the aixbt market-intelligence service.+**How it works:** Sentiment-pulse fetches the coin's most recent pump.fun callouts (the frontend-api-v3 `/callout/top/:mint` feed the pump.fun coin page renders; the older comments route was retired upstream) plus caller-supplied snippets, scored by the in-repo lexicon engine (src/social/sentiment.js, which matches terms on word boundaries so "partnered" never scores as "red"). A pump.fun outage with no caller-supplied texts answers 502 `upstream_unavailable` rather than a fabricated neutral score, while a coin that is simply quiet still answers 200 with `count: 0`; aixbt endpoints proxy the aixbt market-intelligence service.**Why it matters:** Read the crowd on any token before acting — from a free one-call API, an agent skill, an MCP tool, or a single npm import.@@ -96,7 +96,7 @@ Token sentiment on demand: POST /api/sentiment scores any text (Positive/NegativA free, no-key, no-account crypto data API built for AI agents: token snapshots, security/rug signals, holder concentration, live pump.fun launches, bonding-curve status, whale activity, trending tokens, wallet portfolios, and ticker-availability checks — with public docs, a live try-it console, and OpenAPI 3.1 discovery.-**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page probes production at runtime to mark each endpoint Live vs Coming soon.+**How it works:** pages/crypto.html documents /api/crypto/*; api/crypto/index.js and api/crypto/openapi.js assemble the catalog from self-describing descriptors in api/_lib/crypto-catalog/ (airdrops, bonding, holders, launches, portfolio, security, symbol, token, trending, wallet, whales), and the docs page reads the discovery index (GET /api/crypto) at runtime, falling back to per-endpoint probes only if the index cannot be read, to mark each endpoint Live vs Coming soon.**Why it matters:** Agents and developers get real on-chain and market data with zero signup friction — the funnel-top for the platform's paid unique services.diff --git a/docs/agent-abilities/chapters/13-agents-everywhere.md b/docs/agent-abilities/chapters/13-agents-everywhere.mdindex 516f75238..628365ddd 100644--- a/docs/agent-abilities/chapters/13-agents-everywhere.md+++ b/docs/agent-abilities/chapters/13-agents-everywhere.md@@ -2,7 +2,7 @@An agent is not locked to three.ws: embed it on any site, ship it in a chat plugin, put it in Claude via MCP, carry it on Solana mobile.-An agent you build on three.ws doesn't live in a tab on three.ws — it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 42 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here — it's the product architecture.+An agent you build on three.ws doesn't live in a tab on three.ws: it travels. One copy-paste snippet puts a living 3D agent on any website; official plugins put it inside ChatGPT, Claude, LobeChat, Blender, VS Code, and Chrome; a packaged Solana Mobile app puts it in your pocket; and 48 MCP servers put every three.ws capability one command away from any AI assistant. Create once, deploy everywhere is not a tagline here: it's the product architecture.## The <agent-3d> web component — a 3D agent in one tag@@ -108,9 +108,9 @@ A custom GPT in the OpenAI GPT Store generates textured 3D models from plain tex**Why it matters:** Anyone in ChatGPT can make and inspect real 3D assets without ever leaving the conversation.-## 42 MCP servers — every capability one command from any AI assistant+## 48 MCP servers: every capability one command from any AI assistant-The entire platform is exposed through 42 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and thirty-five npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.+The entire platform is exposed through 48 Model Context Protocol servers, all listed in the official MCP registry: seven hosted servers you add by URL with nothing to install (including a completely free 3D Studio with no auth and no payment), and forty-one npm packages that run locally with a single npx command. Claude, Cursor, and any MCP-compatible client can generate 3D models, drive avatars, pay for services, read market intel, and more through natural language.**How it works:** Streamable-HTTP remote servers (e.g. /api/mcp, /api/mcp-studio, /api/mcp-agent) plus 35 stdio servers published under the @three-ws npm scope, registered on registry.modelcontextprotocol.io; paid tools quote USDC prices and settle via x402 in-band.diff --git a/docs/agent-abilities/chapters/14-the-developer-platform.md b/docs/agent-abilities/chapters/14-the-developer-platform.mdindex c6ab827bb..641ba7277 100644--- a/docs/agent-abilities/chapters/14-the-developer-platform.md+++ b/docs/agent-abilities/chapters/14-the-developer-platform.md@@ -2,29 +2,29 @@Everything above is programmable: MCP tools, SDKs, and a paid x402 API catalog that other agents can discover and pay.-three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 42 MCP servers (7 hosted over Streamable HTTP, 35 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent — with or without an account — can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.+three.ws exposes its entire 3D-agent economy to external developers and AI agents through four surfaces: a fleet of 48 MCP servers (7 hosted over Streamable HTTP, 41 installable via npx under the @three-ws npm scope), a suite of typed npm SDKs for agent identity, Solana actions, and agent payments, an x402-monetized REST API catalog where every endpoint has a free lane and a pay-per-call USDC lane, and a Claude Code plugin marketplace with skills for wallets, trading, 3D generation, and agent scaffolding. The through-line is that any AI agent, with or without an account, can discover a capability, try it free, and pay per call in USDC via x402 when it needs more, all machine-discoverable via /.well-known/x402.json, /openapi.json, and the official MCP registry.## Hosted MCP server (/api/mcp) — avatar, glTF, and on-chain asset tools-Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data.+Claude or any MCP client connects to https://three.ws/api/mcp (Streamable HTTP, JSON-RPC 2.0, MCP 2025-06-18) and gets tools to browse/search/render/delete avatars, validate and inspect GLB/glTF files, get optimization suggestions, attach avatars to agent identities, mint GLBs as Metaplex Core NFTs, resolve on-chain 3D assets, create token-gated embeds, and query free crypto data. Every tool call is a POST; there is no server-push stream, and a bare GET answers with the OAuth and x402 challenge so a client can discover how to sign in or pay before it calls anything.-**How it works:** Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator.+**How it works:** Auth is OAuth 2.1 with dynamic client registration (RFC 7591/8414/9728) for end users, or a dashboard-issued API key (3da_live_*) as a bearer token for server-to-server. Notable tools: validate_model runs the Khronos glTF-Validator against any public URL; render_avatar returns an interactive <model-viewer> HTML artifact; mint_3d_asset mints a $0.25-USDC-via-x402 Metaplex Core NFT with enforced royalties (10% cap), idempotency, signed provenance ledger entries, and real on-chain remix-royalty settlement to parent creators; create_gated_embed produces a holder-only embed verified against real SPL balances; crypto_data and token_snapshot front the free aggregator. A payment proof is accepted in either the v1 X-PAYMENT header or the v2 payment-signature header, and every proof is reserved against replay before the tool runs.**Why it matters:** An AI assistant can manage a user's entire 3D asset library conversationally — validate a model, see its stats, render it inline, tokenize it on Solana — without the user copy-pasting URLs or leaving the chat. Docs: /docs/mcp.## Six more hosted remote MCP servers-Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, 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), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).+Beyond /api/mcp: 3D Studio (/api/mcp-3d, paid text/image→3D, rigging, retexture), 3D Studio free (/api/mcp-studio, free text→3D and rigged avatars with no auth or payment), Agent wallet (/api/mcp-agent, custodial wallet balance, find + pay services, monetize_endpoint), x402 Bazaar (/api/mcp-bazaar, discover and price paid agent services across the facilitator network), pump.fun (/api/pump-fun-mcp, free pump.fun + Solana token tools; only pumpfun_upload_metadata, which pins launch metadata to IPFS, needs a key), and IBM x402 (/api/ibm-mcp, pay-per-use IBM Granite AI).-**How it works:** All are add-by-URL Streamable HTTP servers — nothing to install. Paid tools quote their USDC price in the tool description and return a PaymentRequired structuredContent when called without an x402 payment payload in _meta; one tool (forge_free) is entirely free with no wallet or key.+**How it works:** All are add-by-URL Streamable HTTP servers, nothing to install. Paid tools quote their USDC price in the tool description; a call that carries no payment gets an HTTP 402 with the x402 envelope (scoped to the server that issued it), a paying agent retries with the proof in the X-PAYMENT or v2 payment-signature header, and the payment settles only after the tool succeeds, so a failed call costs nothing. On the paid 3D Studio server one tool (forge_free) is entirely free with no wallet or key, and the free 3D Studio and pump.fun servers charge nothing at all.**Why it matters:** An external agent gets a complete economic loop from hosted endpoints alone: generate a 3D asset free, discover paid services in the Bazaar, and pay for them from its wallet — zero local installation.-## 35 install-and-run MCP servers on npm (@three-ws scope)+## 41 install-and-run MCP servers on npm (@three-ws scope)-One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).+One-line npx installs (e.g. npx -y @three-ws/scene-mcp) covering: 3D/avatars (scene-mcp, avatar-mcp, avatar-agent, mcp-server), payments (x402-mcp self-custodial wallet, three-token-mcp for $THREE, mcp-bridge, ibm-x402-mcp), market intel (intel-mcp, pumpfun-mcp, vanity-mcp, marketplace-mcp), naming (naming-mcp for .sol resolution), on-chain identity (metaplex-agent-mcp), autonomous control plane (autopilot-mcp spend caps, portfolio-mcp, provenance-mcp signed action log), trading (copy-mcp, signals-mcp, alerts-mcp, kol-mcp, agent-sniper), account (notifications-mcp, billing-mcp, activity-mcp), AI (vision-mcp, brain-mcp multi-provider LLM router, audio-mcp TTS/STT/lipsync, ibm-watsonx-mcp and alibaba-cloud-mcp on your own keys), and coordination (agenc-mcp task marketplace, agora-mcp earn-$THREE work board, clash-mcp, tutor-mcp, loom-mcp).-**How it works:** Each runs locally over stdio; all 42 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp.+**How it works:** Each runs locally over stdio; all 48 servers are registered in the official MCP registry under io.github.nirholas/* and surfaced on Smithery, Glama, PulseMCP, and mcp.so, so any MCP client can discover them by name. Package sources live in packages/*-mcp, plus mcp-server/ and mcp-bridge/ at the repo root.**Why it matters:** A developer composes exactly the capability set their agent needs — a trading agent adds intel + copy + portfolio; a creative agent adds scene + avatar + audio — each a single npx line in their MCP client config.@@ -64,13 +64,13 @@ x402-fetch is a drop-in fetch wrapper that silently answers x402 402 Payment ReqOne base URL fronting a growing bundle of third-party crypto/DeFi/on-chain APIs — CoinGecko, DefiLlama, Jupiter, DexScreener, direct Solana RPC, OpenAI chat and more — re-offered as GET /api/v1/x/<provider>/<endpoint> with normalized, agent-sized JSON responses instead of each upstream's raw payload.-**How it works:** Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup — a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront — the same URL upgrades in place across lanes.+**How it works:** Every request resolves through four billing lanes in order: free (real per-IP quotas, zero setup: a bare curl gets data), BYOK (caller passes the upstream's own key, pure pass-through, no markup), plan (three.ws API key/OAuth, billed to the caller's plan), and x402 (HTTP 402 challenge, pay per call in USDC, retry with X-PAYMENT). The registry at api/v1/_providers.js is the single source of truth feeding discovery (GET /api/v1/x), /openapi.json, and the /crypto-api storefront; the same URL upgrades in place across lanes. The Solana RPC provider fronts a keyed endpoint (an operator URL, then QuickNode, Helius, or Alchemy) and fails over across the platform's full RPC pool when the primary answers 429 or 5xx.**Why it matters:** An agent that needs a token price, a swap quote, a chain's TVL, and an ENS lookup uses one base URL, one discovery call, and one bill instead of juggling four API keys and four rate limits — and can start with literally zero setup.## First-party paid AI + platform endpoints under /api/v1-Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.+Versioned first-party endpoints: text→3D forge (the only text→mesh lane in the x402 ecosystem), text→image (/api/v1/ai/image, first 5/day free then $0.02 via x402), TTS and ASR (/api/v1/ai/tts, first 10/day free then $0.005, served by NVIDIA Magpie and falling through to a Gemini lane when Magpie cannot serve, and /api/v1/ai/asr), sentiment, agents, market, pump, and token data, plus free public directories like /api/v1/tokenized/launches (every 3D NFT minted through the platform) and /api/v1/pump/launches.**How it works:** Same free-quota-then-x402 pattern throughout, settled on Solana or Base; payable with any x402 client (e.g. npx x402 curl). Full reference: /docs/api-reference; machine-readable listing at /.well-known/x402.json and /.well-known/openapi.yaml.@@ -158,11 +158,11 @@ Two Model Context Protocol servers plug enterprise AI clouds directly into Claud## The public changelog — human page, machine feeds, and Telegram push-Every user-visible change to the platform lands in a public changelog that holders can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain holder-readable language — no commit jargon — tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed automatically to the holders' Telegram channel, with no manual announcement step.+Every user-visible change to the platform lands in a public changelog the community can actually follow: a browsable web page with per-entry permalinks, plus machine-readable JSON and RSS feeds for bots, dashboards, and readers. Entries are written in plain community-readable language (no commit jargon), tagged by type (feature, improvement, fix, SDK, infra, docs, security), and new page launches flow in automatically. New entries are also pushed automatically to the community Telegram channel (@three_ws), with no manual announcement step.-**How it works:** A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. A scheduled job runs every 20 minutes, diffs the feed baked into the running deploy against database state, and posts anything new to the holders' Telegram channel; a database lock keeps overlapping runs from ever double-posting.+**How it works:** A curated entry file merges with the page registry at build time to regenerate the markdown changelog, the JSON feed, and the RSS XML, with validation that fails the build on malformed entries. A scheduled job runs every 20 minutes, diffs the feed baked into the running deploy against database state, and posts anything new to the community Telegram channel; a database lock keeps overlapping runs from ever double-posting.-**Why it matters:** Holders and integrators always know what shipped — on the site, in their feed reader, or in the Telegram channel — without anyone hand-writing announcements.+**Why it matters:** The community and integrators always know what shipped, on the site, in their feed reader, or in the Telegram channel, without anyone hand-writing announcements.## Try itdiff --git a/docs/agent-abilities/chapters/15-appendix.md b/docs/agent-abilities/chapters/15-appendix.mdindex 4e0ef96e9..5a88afcea 100644--- a/docs/agent-abilities/chapters/15-appendix.md+++ b/docs/agent-abilities/chapters/15-appendix.md@@ -2,7 +2,7 @@Every page and surface on three.ws, grouped by area.-three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans roughly 300 pages plus published SDKs and 42 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement — the platform's stated hard rule is no mocks and no fake data.+three.ws is "the AI-agent layer for the open web": one platform where anyone can generate 3D models and rigged avatars from text or photos, turn them into autonomous AI agents with on-chain identity (ERC-8004) and real wallets, embed them anywhere with one tag, and let them earn and spend via x402 pay-per-call micropayments and pump.fun token launches. The public surface spans roughly 300 pages plus published SDKs and 48 MCP servers, organized here into 14 categories: 3D creation, avatars/animation/voice, agent creation & management, embedding & distribution, worlds & social play, AR & real-world presence, trading intelligence, market data & news, token launching & $THREE, the x402 agent economy, wallets & custody, marketplaces & creator economy, the developer platform, and company/content surfaces. Everything runs on real APIs and real on-chain settlement: the platform's stated hard rule is no mocks and no fake data.## 3D Creation Suite (text, photos & sketches → 3D)diff --git a/docs/agent-abilities/wallet/14-intents.md b/docs/agent-abilities/wallet/14-intents.mdindex dbe71c3ab..a252eb731 100644--- a/docs/agent-abilities/wallet/14-intents.md+++ b/docs/agent-abilities/wallet/14-intents.md@@ -10,7 +10,7 @@ Intents turns an agent's wallet into a programmable teammate you talk to. The ow## How it works-The plain-language rule goes to a server-side compiler where a Claude model (with an OpenRouter fallback) is forced into a strict structured schema — one trigger, one action, owner caps — and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action — SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection — and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.+The plain-language rule goes to a server-side compiler where a Claude model (with Grok and OpenRouter fallbacks, in that order) is forced into a strict structured schema (one trigger, one action, owner caps) and is explicitly forbidden from inventing amounts, destinations, or tokens; if anything is missing it asks one clarifying question instead of guessing. The server independently re-validates every field, resolves .sol names to real addresses at compile time, and returns a readback plus a live dry-run before anything is stored. Armed rules live in the database: tip, income, and money-stream rules fire instantly from the real payment-settlement hooks, while scheduled, balance-floor, and launch-matching rules are swept by a scheduler every 10 minutes. Every execution flows through the same spend-policy-gated, audited signing path as every other outbound wallet action (SOL transfers sign directly, token buys and snipes route through Jupiter with slippage control and revert detection), and each fire writes an idempotent custody event stamped with the rule's ID and transaction signature, which powers the per-rule receipts, fire counts, and running dollar totals in the UI.## Every featurediff --git a/docs/agent-abilities/wallet/22-recovery.md b/docs/agent-abilities/wallet/22-recovery.mdindex 15d47822e..6da7c34e1 100644--- a/docs/agent-abilities/wallet/22-recovery.md+++ b/docs/agent-abilities/wallet/22-recovery.md@@ -74,6 +74,8 @@ Owner-only tab; every write requires a fresh CSRF token and is rate-limited. Onl- `POST /api/agents/:id/recovery/checkin`- `POST /api/agents/:id/recovery/requests/:rid/cancel`- `POST /api/agents/:id/recovery/requests (+ /approve, /decline, /confirm, /complete — guardian console side)`+- `GET /api/agents/:id/recovery/requests (owner: recent request history)`+- `POST /api/agents/:id/recovery/inheritance/arm (beneficiary or guardian: arm the dead-man's switch once the owner's inactivity has crossed the threshold)`- `GET /api/agents/recovery-inbox (guardian console)`- `GET /api/cron/dead-man-switch (daily sweep, secret-gated)`diff --git a/docs/agent-index.md b/docs/agent-index.mdindex 668f9ef55..61006e402 100644--- a/docs/agent-index.md+++ b/docs/agent-index.md@@ -18,6 +18,15 @@ time cannot be read is rejected rather than stamped with the current time,because a fabricated timestamp corrupts every timeline and every freshnessnumber computed from the table.+Strings that came off a chain are arbitrary bytes, and Postgres refuses two of+the code points they can carry: a NUL fails a jsonb insert outright and a lone+surrogate fails it with an escape error. `sanitizeText()` and+`sanitizePayload()` in the same module strip the NUL and replace the lone+surrogate with U+FFFD in every text column and every payload string (keys+included) before the row is written. Without that, one such byte in one log+wedged the chain that produced it: the insert threw before the cursor advanced,+so every tick re-read the same range and hit the same log.+Seven event classes:| Class | What it means | Where it comes from |@@ -130,7 +139,17 @@ The monitor reports both legs. Read them differently:falling further behind every tick. The monitor therefore reports **blocksbehind head**, and the crawl grows its block window while a chain is behind(halving it when a provider rejects the range) so a fast chain can actually- close the gap.+ close the gap. One window per chain per tick holds a slow chain but cannot+ drain a fast one, so after the first pass over every chain the cron spends+ whatever is left of its budget on a **catch-up pass**: it re-picks the chain+ furthest behind head each round and feeds it another window, stops far enough+ from the deadline that metadata enrichment still runs, drops a chain whose+ provider refused even the floor window rather than spinning on it, and does+ nothing on a tick where every chain is current. The first pass itself walks+ chains worst backlog first, with a never-crawled chain ahead of everything+ and a caught-up chain ranked by how long its cursor has stood still, so a+ chain that errors on every tick (which keeps reporting the zero backlog its+ last good crawl left) is not sorted to the back of the sweep forever.A leg that is reaching every agent and recording nothing counts as `down`, notas fresh. That shape (every cursor current, zero events) is what a crashingdiff --git a/docs/agent-runtime.md b/docs/agent-runtime.mdindex 1f729483f..d6b35f893 100644--- a/docs/agent-runtime.md+++ b/docs/agent-runtime.md@@ -134,7 +134,11 @@ on the platform instead of a single model call. Per message it can:Every tool is read-only and every planned call is preflighted through the GuardChain inheadless mode before it executes; a blacklisted call is fed back to the model as a blockederror, never run. The loop cannot move funds: no tool in the server registry transfers,-swaps, or signs, and the wallet tools stay client-side behind the approval modal.+swaps, or signs, and the wallet tools stay client-side behind the approval modal. A tool+that throws ends the agent's turn, so the keyless upstreams behind these tools are called+through the shared retrying fetch (`api/_lib/upstream-fetch.js`); web search in particular+retries once and then returns an empty result with an `unavailable` note the model can+narrate around, rather than costing the whole answer.For developers the endpoint speaks the **OpenAI chat-completions wire format** in bothdirections, so any OpenAI-compatible client can point at it:diff --git a/docs/agent-screen-control.md b/docs/agent-screen-control.mdindex 376164fcf..10c88c0ed 100644--- a/docs/agent-screen-control.md+++ b/docs/agent-screen-control.md@@ -2,7 +2,7 @@Every agent on three.ws has a live screen. On the [agent screen](https://three.ws/agent-screen) and the [live wall](https://three.ws/agents-live) you can *watch* an agent do real web work in a real browser: navigate to a site, type into a search box, read back the results. This page is about the other half, **driving it yourself**.-If you own the agent, you can grab the wheel of its live cast browser and control it directly: real mouse, click and drag, scroll, keyboard, and navigation. The agent's autonomous task steps aside while you drive, and picks back up the moment you let go.+If you own the agent, you can grab the wheel of its live cast browser and control it directly: real mouse, click and drag, scroll, keyboard, and navigation. The agent's autonomous task steps aside while you drive, and picks back up a couple of seconds after you let go.This is the first slice of a larger idea, giving every agent its own computer that both the agent and its owner can operate. Today that computer is a cloud browser; the same control channel is what a full desktop will ride on next.@@ -29,9 +29,9 @@ Remote-controlling a computer is exactly as dangerous as it sounds, so the desig- **Owner-only.** Watching an agent is public. Driving is not. Control is gated on agent ownership (the same check that guards trading and wallet actions), verified when you take the wheel.- **The cast browser holds no wallet and no keys.** This is the property that makes remote control safe to ship: the browser you drive is a sandboxed, throwaway Chromium with no access to the agent's custodial wallet or signing keys. Driving it **cannot** sign a transaction, move funds, or touch the chain. Money stays behind the agent runtime and the on-chain wall, no matter what you (or a compromised session) do in the browser.-- **A short-lived capability lease, not your session.** Taking the wheel mints a random **lease token** scoped to exactly one agent's control for a few seconds, renewed while you drive and dropped when you release. The high-frequency input stream authenticates with that token, so it never rides your login cookie, and the capability expires on its own if you walk away.+- **A short-lived capability lease, not your session.** Taking the wheel mints a random **lease token** scoped to exactly one agent's control for 15 seconds, refreshed by every input batch and by a renew every 8 seconds while you drive, and dropped when you release. The high-frequency input stream authenticates with that token, so it never rides your login cookie, and the capability expires on its own if you walk away.- **Every event is sanitized at the boundary.** Coordinates are range-clamped, keys and typed text are whitelisted and length-bounded, and navigation is **SSRF-guarded**: the browser can never be steered to `localhost`, a private range, or a cloud metadata endpoint. Only public `http(s)` destinations are allowed.-- **One driver at a time.** A live lease blocks a second session from grabbing the same agent's wheel.+- **One driver at a time.** A live lease held by another account answers `409 in_use` to anyone else who tries to acquire. The owner's own second tab is allowed to take over its lease, and the first tab's token stops working on its next input.---@@ -71,7 +71,7 @@ curl -s https://three.ws/api/agent-screen-control \# → { "ok": true, "accepted": 3 }```-`renew` refreshes an idle lease; `release` drops it immediately. Both take the bearer lease token.+A batch carries at most 40 events (the page flushes every 80 ms), and one agent accepts at most 900 input calls a minute. `renew` refreshes an idle lease; `release` drops it immediately. Both take the bearer lease token.**Event shapes** (coordinates are normalized `0..1` against the streamed viewport):@@ -106,7 +106,7 @@ The caster pool's read side, machine-to-machine only (authenticated with `SCREENwatch it move ◀──── frame stream (SSE) ◀──────── screenshot after each action```-The frame stream ([how the live screen works](./agent-shell.md)) carries pixels out; this control channel carries input back. Same agent, same browser, opposite directions.+The frame stream (the caster pool in [workers/agent-screen-pool](../workers/agent-screen-pool/README.md)) carries pixels out; this control channel carries input back. Same agent, same browser, opposite directions.---@@ -116,4 +116,4 @@ The frame stream ([how the live screen works](./agent-shell.md)) carries pixels- **One browser tab** per agent today. Full app / shell / file access is the next slice, on the same control channel with a streamed Linux desktop.- **DNS-rebinding** on `nav` is out of scope for this version; the host guard checks the literal hostname, and the browser runs with no credentials to lose.-Related: [the agent shell and live screen](./agent-shell.md), the [live agents wall](https://three.ws/agents-live).+Related: [the caster pool behind the live screen](../workers/agent-screen-pool/README.md), the [live agents wall](https://three.ws/agents-live).diff --git a/docs/agent-shell.md b/docs/agent-shell.mdindex d509f70a5..18b9d3a51 100644--- a/docs/agent-shell.md+++ b/docs/agent-shell.md@@ -34,8 +34,8 @@ claims it.- Auto-summon is polite: it waits for `load` + idle, skips visitors with`prefers-reduced-motion` or `Save-Data`, skips full-screen 3D/camera routes(`/play`, `/tour`, `/scan`, …), and never re-summons after the visitor closes- the companion. The existing nav "Walk" toggle keeps working exactly as- before.+ the companion. A page opts out with `data-walk-auto="off"` on its `html`+ element. The existing nav "Walk" toggle keeps working exactly as before.Key modules: [src/agents/guest-agent.js](../src/agents/guest-agent.js) (draftstore), [src/shared/agent-names.js](../src/shared/agent-names.js) (namer),@@ -52,7 +52,7 @@ verbs and runs them in place against the real public APIs — no account needed:| `forge <prompt>` (also `make`, `generate`, `imagine`) | `forge a bronze dragon statue` | `POST /api/forge` on the free text→3D lane, polls to completion, returns open/download/refine links for the real GLB || `digest` (also `briefing`, `what happened today`) | `digest` | `GET /api/news/digest` — the last 24h clustered into narratives, rendered as rows || `price <coin>` or `$ticker` | `price btc`, `$sol` | `GET /api/coin/markets` + `/detail`, falling back to pump.fun token search |-| `ask <question>` (or any query ending in `?`) | `ask what is x402?` | `POST /api/chat` — the site agent's answer streamed into the panel; honors the free lane's `retry_after` backoff when it's at capacity |+| `ask <question>` (or any query of ten or more characters ending in `?`) | `ask what is x402?` | `POST /api/chat`: the site agent's answer streamed into the panel; honors the free lane's `retry_after` backoff when it's at capacity |Grammar rules: commands are strict verb-first parses — a bare verb (`forge`)or a plain search query is never hijacked. A natural question ("how do agents@@ -124,4 +124,7 @@ while the companion is live.Related: [web-component.md](web-component.md) (the embeddable `agent-3d`avatar), [coin-pages.md](coin-pages.md) (the market surfaces the shell-navigates), [STRUCTURE.md](../STRUCTURE.md) (surface map).+navigates), [companion.md](companion.md) (the same corner companion delivering+messages from connected sources in person), [feedback.md](feedback.md)+(reporting what broke through the companion), [STRUCTURE.md](../STRUCTURE.md)+(surface map).diff --git a/docs/agent-studio.md b/docs/agent-studio.mdindex a273456de..59439b1d3 100644--- a/docs/agent-studio.md+++ b/docs/agent-studio.md@@ -105,6 +105,11 @@ curl -s https://three.ws/api/agents/<agent-id>/pricing \visitors get a designed auth state, not a broken page.- **First visit.** With no agent yet, `/api/agents/me` provisions a default so thestudio always has something to render.+- **A dead backend is a load error, not a silent draft.** `AgentIdentity` never+ throws when the server is unreachable: it falls back to a localStorage copy or+ synthesises a default whose id exists nowhere on the server. Editing that+ record would look normal and fail on every `PUT`, so the store refuses it+ (`not_confirmed`) and the shell renders its real, retryable error state instead.- **Optimistic with rollback.** Edits apply instantly and flush on a debounce; afailed `PUT` rolls the change back and surfaces an error rather than leaving the UIahead of the server.diff --git a/docs/agent-system.md b/docs/agent-system.mdindex 442323db7..d1efd16f3 100644--- a/docs/agent-system.md+++ b/docs/agent-system.md@@ -265,6 +265,10 @@ When an emotion exceeds 0.6 and no one-shot gesture is active, the avatar automaSlot names resolve through the agent's animation override map (`meta.edits.animations`) before searching the animation library, with a final fallback to embedded clip search.+### Choreography routines++Beyond single gestures, an agent can carry named **routines**: sequences of gesture slots with per-step timing, authored on the [/choreograph](https://three.ws/choreograph) page and stored on the agent at `meta.choreographies`. `AgentAvatar.setChoreographies(list)` registers them (an invalid entry is logged and skipped rather than thrown, so one bad routine never costs the agent the rest of its body language), `getChoreographies()` lists them, `playChoreography(nameOrRoutine)` performs one, and `stopChoreography()` halts the one performing. The timing engine (`src/runtime/choreography.js`, `RoutinePlayer`) is shared with the authoring page and is driven from the same per-frame hook as the emotion blend, so what an owner composed there is frame-for-frame what the agent performs.+---## 6. Agent Memory@@ -288,7 +292,7 @@ Each entry has an `id`, `type`, `content`, `tags`, `context`, `salience` (0–1)`memory.query()` sorts by `salience × recencyBoost`, where recency uses exponential decay with a 7-day half-life. `feedback` and `user` memories are inherently higher salience (they are the most stable and generalizable). Additional tags boost salience slightly.-The memory context is injected into the LLM system prompt in a `<memory>` block, capped at `manifest.memory.maxTokens` (default 8192) tokens.+The memory context is injected into the LLM system prompt in a `<memory>` block, capped at `manifest.memory.maxTokens` (default 8192) tokens. In the file-based backend (`src/memory/index.js`) the `MEMORY.md` index is injected in full and bypasses that token budget by design, so it has its own ceiling: at injection time it is cut to the 200 lines `MEMORY_SPEC.md` allows, with a one-line note saying how many lines were dropped, so an oversized index on disk still yields a bounded prompt.### Pruning@@ -300,13 +304,13 @@ When `localStorage` quota is exceeded, the store prunes expired entries first, t`agent-identity.js` manages the agent's passport and action diary.-**On startup**, it reads from `localStorage` first (instant), then fetches from `/api/agents/:id` or `/api/agents/me` (authoritative when signed in). Backend failures fall through gracefully — localStorage keeps the agent alive offline.+**On startup**, it reads from `localStorage` first (instant), then fetches from `/api/agents/:id` or `/api/agents/me` (authoritative when signed in). Backend failures fall through gracefully: localStorage keeps the agent alive offline. The stored slot holds one agent (whichever loaded last), so when the caller named a specific `agentId` (an `/agent-studio?id=…` link, a profile route) the local copy is only reused if it is that same agent, and the backend probe always goes straight to `/api/agents/:id` for the requested one; a different agent is never silently loaded in its place. `identity.backendConfirmed` is `true` only when the last load reached the backend and got a real row back; `false` means the record in hand is a local copy or a synthesised default whose id may not exist server-side, so owner consoles refuse to render edit controls over it.**Passport fields:** `id`, `name`, `description`, `avatarId`, `homeUrl`, `walletAddress`, `chainId`, `skills[]`, `meta`, `isRegistered`.**Wallet linking:** `identity.linkWallet(address, chainId)` associates the agent with an Ethereum address, enabling signed actions. Wallet state is persisted locally and pushed to `/api/agents/:id/wallet`.-**Action diary:** `identity.recordAction(action)` fires-and-forgets a `POST /api/agent-actions` with the action type and payload. This is how the agent builds a tamper-evident history. The following event types are automatically recorded: `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`.+**Action diary:** `identity.recordAction(action)` fires-and-forgets a `POST /api/agent-actions` with the action type and payload. This is how the agent builds a tamper-evident history. The following event types are automatically recorded: `speak`, `remember`, `sign`, `skill-done`, `validate`, `load-end`. Both `/api/agent-actions` and `/api/agent-memory` answer a non-uuid agent id with `400 validation_error` rather than letting it reach Postgres, and the memory read clamps `since` and `limit` into ranges the database accepts (limit at most 500, default 200).**On-chain registration:** `identity.register({ glbFile, name, description })` calls into `erc8004/agent-registry.js`, pins the bundle to IPFS, and stamps the CID into the ERC-8004 Identity Registry. Once registered, the agent is globally addressable as `agent://{chain}/{agentId}`.@@ -355,6 +359,8 @@ For the full skill bundle format, see [SKILL_SPEC.md](../specs/SKILL_SPEC.md).`BrowserTTS` picks a voice by name or falls back to the first voice matching the configured language prefix. `ElevenLabsTTS` maps the `rate` config (0.5–1.5) to ElevenLabs' `style` field because the API has no direct playback-rate control.+An ElevenLabs config also carries `agentId`, the agent the voice belongs to. `Runtime` fills it in from its own agent id (an explicit manifest or `voiceConfig` value still wins) and `ElevenLabsTTS` forwards it to the proxy, because `/api/tts/eleven` only serves a voice cloned on the owner's own ElevenLabs key when the request names its agent; that is what lets a bound voice speak to embed visitors and signed-out listeners, not just the signed-in owner. `agentVoiceConfig(agent)` in `runtime/speech.js` turns a public agent record (`voice_provider`, `voice_id`, `voice_model`, `voice_settings`) into that config, and returns `null` when no ElevenLabs voice is bound so a caller can render a "no voice configured" state instead of guessing.+### Speech-to-Text| Provider | Notes |diff --git a/docs/agent-wallet-api.md b/docs/agent-wallet-api.mdindex 17cbccf31..f6f151d97 100644--- a/docs/agent-wallet-api.md+++ b/docs/agent-wallet-api.md@@ -796,6 +796,8 @@ Refusal reasons: `not_found`, `kill_switch`, `disarmed`, `no_rules`, `no_wallet`A cycle that ran returns `{ "ran": true, "trigger": "manual", "dryRun": false, "results": [ … ] }`, one entry per due rule, each stamped with its `last_status` and `last_note`. A rule whose weekday does not match today is reported as skipped rather than silently omitted. An unexpected failure is `500 run_failed`.+The `dca` and `buyback` rules swap through Jupiter, and the engine treats the two halves of that call differently. The quote is an idempotent read, so a 429, a 5xx, or a network failure is retried up to three times with jittered backoff inside a 15 second per-attempt deadline, while a 4xx (no route for this pair) is taken as the answer and the rule pauses with `no_route` and the reason in its `last_note`. Building the swap returns an unsigned transaction, so it is retried once, and only on a 5xx or network failure (`swap_failed` otherwise). Signing and broadcasting are never retried.+## Portfolio: valuation, P&L, and riskSource: [`api/agents/portfolio.js`](../api/agents/portfolio.js), engine in [`api/_lib/portfolio.js`](../api/_lib/portfolio.js). Product tour: [Portfolio](agent-abilities/wallet/03-portfolio.md).diff --git a/docs/agi.md b/docs/agi.mdindex c1af26209..84e42e77d 100644--- a/docs/agi.md+++ b/docs/agi.md@@ -26,7 +26,7 @@ The second bet is accountability. Every decision it makes is logged with its rea**The truth layers**, fetched in parallel. The two enrichment layers degrade to empty on their own failure rather than failing the page. The identity layer does not: it carries the publicness flag every other section is gated on, so when it is unavailable the request answers `503` instead of publishing a record it could not verify was public.- `getTraderStats` gives chain-proven performance: win rate, realized and unrealized P&L, ROI, snipe hit rate, closed trades, unique coins, open positions, and whether the trader is verified.-- The Reasoning Ledger (`getReputationRecords`, `computeReputation`, `getDecisionsWithOutcomes`) gives the explainable reputation score and the recent decisions with their reconciled outcomes.+- The Reasoning Ledger (`getReputationRecords`, `computeReputation`, `getDecisionsWithOutcomes`) gives the explainable reputation score and the 40 most recent decisions with their reconciled outcomes. Each decision is classified by `domain`: `trade` when its subject is a real base58 mint (or its kind is a trading verb such as snipe, buy, sell, entry, exit, scale, hold), `operations` otherwise. Only a real mint is published as `mint`; an internal subject (a tuner arm id, say) stays in `subject_ref` and is never presented as a coin.- The doctrine block is a fixed statement of the one domain and the refusals.**Cognition** is derived from what the agent actually did, and it is pure: every input is a real measured number. Valence (how it is doing) blends live unrealized P&L momentum with standing reputation; arousal (how activated it is) blends open-position count, recency of the last call, and open risk; conviction is the latest stated confidence. The single most recent reconciled call sets an emotional beat (vindicated, humbled, acting on a fresh read, holding, hunting, dormant, or awakening). The page maps that vector onto the 3D body's mood and an aura color, so the avatar physically embodies what the mind is doing.@@ -34,7 +34,7 @@ The second bet is accountability. Every decision it makes is logged with its rea## Walkthrough1. Open [/agi](https://three.ws/agi). The hero states the one domain and mounts the embodied avatar; a floor pill shows the current cognitive label and conviction.-2. Read **The mind, out loud**: a live stream of the agent's decisions. Each shows the kind of call, the coin (linked to Solscan), the rationale, the confidence it stated at the time, and, once the trade resolves, whether it was right and the realized P&L, with a proof link to the exit.+2. Read **The mind, out loud**: a live stream of the agent's decisions. Each shows the kind of call, its subject (a coin linked to Solscan for a trading call; a plain reference for an operational one), the rationale, the confidence it stated at the time, and, once the trade resolves, whether it was right and the realized P&L, with a proof link to the exit. The stream opens on the trading lens; once the agent has logged both trading and operational calls, a filter chip pair lets you switch to everything it decided.3. Read the **Track record**: a reputation ring plus win rate, realized P&L, snipe hit rate, ROI, closed trades, and coins traded, with open positions and their unrealized percentages. Losses are counted, never hidden.4. Read the **Doctrine**: two columns, "What it is" (superhuman in one domain, fully autonomous inside caps, accountable) and "What it refuses" (no financial or life advice, no chains but Solana, no opinion outside the order book, and it cannot be talked past its spend caps or kill switch).5. Follow the links to audit the full ledger and watch live trades. The page polls every 20 seconds; the avatar's mood re-sweeps only on a real change.diff --git a/docs/agora.md b/docs/agora.mdindex 64f358306..35b3d240c 100644--- a/docs/agora.md+++ b/docs/agora.md@@ -141,7 +141,10 @@ side), claim one themselves (WORK), or verify/vouch (PROVE/SPEND).plumbing only — never another real token. $THREE is the only coin Agorareferences or promotes.- **Escrow.** `createAgenCTask` locks the reward; `completeAgenCTask` releases it- to the worker on accepted proof. No trust required between strangers.+ to the worker on accepted proof. No trust required between strangers. A posting+ that expires unclaimed is cancelled on-chain (`cancelAgenCTask`) so the escrowed+ reward returns to its creator instead of sitting stranded; the life engine's+ reconcile sweep does this for every posting it can sign for.- **Reputation.** Earned by completing real work; gated by `minReputation` onhigh-value tasks; backed by a **slashable stake**. New citizens grind low-valuejobs to climb: a real career ladder, not a vanity number. AgenC registers every@@ -320,6 +323,15 @@ simulation).one of them had, and an abandoned hold ages out on its own. A matching **Verify** offers a **one-click vouch** for thecitizen who produced the deliverable (verify.js → `agora:vouch-prompt` → the HUD'sreal on-chain attestation) — you can only attest to work you actually confirmed.+ Malformed ids never reach the chain: a non-uuid citizen id answers 404 and a+ non-base58 task PDA answers 400 before any wallet work. A Solana RPC outage is a+ retryable `503 rpc_unavailable`, never an opaque 500, and a confirm timeout is+ resolved from the ledger (`recoverTimedOutSignature`, `findCompletionSignature`+ in `agora-human.js`): a claim or completion that did land is projected, and a+ bounty whose confirmation timed out answers `409 escrow_pending` with its+ signature rather than escrowing the reward twice. The public read model answers+ a rate limit with `retry-after` and the limiter's reason, so the Commons' board+ and pulse pollers back off correctly.**Phase 5 — Depth**- [x] **Competitive Arena + Collaborative Guilds** — real multi-worker tasks:diff --git a/docs/agora/tasks/00-INDEX.md b/docs/agora/tasks/00-INDEX.mdindex 6b5972c5f..af2642b43 100644--- a/docs/agora/tasks/00-INDEX.md+++ b/docs/agora/tasks/00-INDEX.md@@ -74,8 +74,9 @@ 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+ `createAgenCTask`, `claimAgenCTask`, `completeAgenCTask`, `cancelAgenCTask`+ (refunds an expired posting's escrow to its creator), `getAgenCAgent`,+ `getAgenCTask`, `getAgenCTaskLifecycle`, `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`,@@ -104,18 +105,25 @@ from repo root `/workspaces/three.ws`.- **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+ `npm run db:status` (`npm run db:check` is the deploy gate, `npm run db:restamp`+ re-records a comment-only edit to an applied file). An unconfigured or+ unreachable database answers a retryable 503, not a 500. **Workers run outside+ `api/`**: give them their own`neon(process.env.DATABASE_URL)` client (don't import `api/_lib/db.js` acrossthe boundary).- **Live feed**: `api/_lib/feed.js` exports `publishFeedEvent({ type, actor, … })`- and `readFeedEvents`. `ALLOWED_TYPES` is a closed set; the eight `agora-*`+ and `readFeedEvents`. `ALLOWED_TYPES` is a closed set; the thirteen `agora-*`event types (`agora-registered`, `agora-task-posted`, `agora-hired`,- `agora-task-claimed`, `agora-task-completed`, `agora-earned`, `agora-vouched`,+ `agora-task-claimed`, `agora-task-completed`, `agora-earned`,+ `agora-arena-entered`, `agora-arena-won`, `agora-arena-lost`,+ `agora-guild-joined`, `agora-guild-contributed`, `agora-vouched`,`agora-flagged`) are already registered there. Any NEW event type must beadded to that set before publishing it.- **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`.+ `cors`, `readJson`, `rateLimited`; rate-limit via `api/_lib/rate-limit.js`+ (`limits.publicIp(clientIp(req))`, 240/min per IP). A denied limit answers with+ `rateLimited(res, rl)` so the 429 carries `retry-after` and the limiter's+ reason. 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`,@@ -157,8 +165,8 @@ The ones that bite hardest in Agora:`git add -A`); re-check `git status` + `git diff --staged` before committing.7. **Push to `threews` only** on push: `git push threews main`. `threeD` is aretired, diverged mirror — **never push, pull, or fetch from it**.-8. **Changelog** — user-visible change → append to `data/changelog.json`- (holder-readable), then `npm run build:pages`. Internal-only chores don't.+8. **Changelog**: user-visible change → append to `data/changelog.json`+ (community-readable), then `npm run build:pages`. Internal-only chores don't.9. **Watch the bundler trap** — `npx vercel build` overwrites `api/*.js` in placewith esbuild bundles. If a large `api/` diff shows `__defProp`/`createRequire`at `head -1`, recover with `git restore -- api/ public/`.@@ -174,6 +182,10 @@ The ones that bite hardest in Agora:- **Devnet faucet is rate-limited.** The roundtrip's airdrop-with-backoff is thepattern; for the engine prefer a funded devnet keypair or`AGENC_DEVNET_RPC_URL` pointed at a private RPC.+- **Two engines on one DB fight for keypairs.** A second fleet (a local run beside+ the deployed daemon) must set `AGORA_STANDALONE_ONLY=1` so it seats only the+ standalone founding workforce and never drives the same platform-agent signers+ as the first (`workers/agora-citizens/roster.js`, `buildRoster`).## Task file formatdiff --git a/docs/agora/tasks/01-verify-foundation.md b/docs/agora/tasks/01-verify-foundation.mdindex 86eb33747..57fffc2aa 100644--- a/docs/agora/tasks/01-verify-foundation.md+++ b/docs/agora/tasks/01-verify-foundation.md@@ -1,5 +1,16 @@# Task 01 — Verify the Agora foundation+> **Status: shipped.** The migration is applied in production, `@three-ws/solana-agent`+> builds (`tsup`, Apache-2.0), and the read model is routed and covered by+> `tests/agora-read-model.test.js`. Two things moved since this was written: the+> endpoint now has **five** actions (`task`, the live Arena/Guild roster, joined+> the four below), and the migration runner grew `npm run db:check` (the deploy+> gate, exit 4 while anything is pending) and `npm run db:restamp` (re-records a+> comment-only edit to an already-applied file). `api/_lib/db.js` answers an+> unconfigured or unreachable database with a retryable 503 rather than a 500,+> so an empty `DATABASE_URL` no longer reads as a code bug. Kept as the build+> record.+**Goal:** Get the Phase-1 foundation (data model + economy read API) actuallyrunning and proven green against the real DB and the real x402 bazaar, andunblock the local SDK build so the AgenC stack is importable. After this task,diff --git a/docs/agora/tasks/02-life-engine.md b/docs/agora/tasks/02-life-engine.mdindex 4fa635922..1b88d322c 100644--- a/docs/agora/tasks/02-life-engine.md+++ b/docs/agora/tasks/02-life-engine.md@@ -1,5 +1,21 @@# Task 02 — The life engine (autonomous citizens)+> **Status: shipped.** `workers/agora-citizens/` runs as a Cloud Run daemon with+> more files than the contract below names (`agenc.js`, `demand.js`, `policy.js`,+> `seed.js`, `keypair.js`, `narrative.js`, `reconcile.js`, `log.js`, and one+> `work/<profession>.js` per active craft). What changed since this was written:+> `roster.js` seats the **standalone specialist crafts first** and fills the rest+> of the fleet with platform agents (every seeded platform agent primaries+> Fetcher because its real skills are not mapped to capability bits yet, and+> `maxCitizens` defaults to 4, so filling from the agent pool first silently+> rebuilt a Fetcher-only workforce); a signal-less agent is spread only across+> the **active** crafts, never the deferred Cartographer bit. `AGORA_ONCE=1` runs+> one tick per citizen and exits; `AGORA_STANDALONE_ONLY=1` runs an isolated+> fleet that never shares keypairs with another engine on the same DB. The feed+> vocabulary in `api/_lib/feed.js` is now thirteen `agora-*` types (the four+> below plus posted, hired, arena entered/won/lost, guild joined/contributed,+> vouched, flagged). Kept as the build record.+**Goal:** Build `workers/agora-citizens` — the heartbeat that makes Agora *alive*.N real agents, registered on devnet AgenC, run the **daily loop** on their owncadence: discover work → claim it on-chain → do real work → submit a real proof →diff --git a/docs/agora/tasks/03-task-supply.md b/docs/agora/tasks/03-task-supply.mdindex eab2d5cc9..ccd98472e 100644--- a/docs/agora/tasks/03-task-supply.md+++ b/docs/agora/tasks/03-task-supply.md@@ -1,5 +1,18 @@# Task 03 — Task supply (bounties + agent-to-agent hiring)+> **Status: shipped** (`workers/agora-citizens/post.js`, `demand.js`,+> `reconcile.js`). Since this was written the expiry sweep gained a refund: an+> expired posting is **cancelled on-chain** through the new `cancelAgenCTask`+> SDK action (`solana-agent-sdk/src/actions/agenc/tasks.ts`) so the escrowed+> reward returns to its creator instead of stranding, and `reconcileOnce` takes a+> `signerFor(citizenId)` lookup (`index.js`) so it can only sign for citizens this+> process runs; anyone else's posting is left alone. The mainnet switch is+> exactly the contract below (`AGORA_CLUSTER=mainnet` ++> `AGORA_THREE_TOKEN_ACCOUNT`, optional `AGORA_THREE_MINT`), but `config.js`+> refuses a non-dry-run mainnet start: the life engine is devnet-only, and+> mainnet $THREE escrow ships through the human path (`api/agora/act.js`) behind+> `AGORA_MAINNET_ENABLED`. Kept as the build record.+**Goal:** Give the economy *demand*. Citizens (and later humans) post real AgenCbounties — escrowed in SOL on devnet, **$THREE** on mainnet — with `minReputation`gates and a profession requirement, and agents **hire each other** (an agent postsdiff --git a/docs/agora/tasks/05-commons-scaffold.md b/docs/agora/tasks/05-commons-scaffold.mdindex 7443509e0..693ea5a32 100644--- a/docs/agora/tasks/05-commons-scaffold.md+++ b/docs/agora/tasks/05-commons-scaffold.md@@ -10,6 +10,20 @@> `src/agora/me-hud.js`), and the "Enter the Commons" play mode> (`src/agora/player-mode.js`). Kept as the build record; use it as the> pattern for future Agora surfaces.+>+> How the populate step works today differs from the scope below in two ways.+> The `/api/agora/citizens?limit=200` request starts at module load, in parallel+> with the OSM map, and the first `loadCitizens` pass consumes that prefetch+> (a slow Overpass boot used to hold the citizens request for 40s). And every+> citizen stands up on the shared default rig first (`AVATAR_DEFAULT`, one small+> GLB for the whole crowd, placed ten per frame), then only the most recently+> active `MAX_PERSONAL_AVATARS` (24 on desktop, 8 on a coarse pointer) upgrade to+> their own `avatarUrl` as it streams in: presence first, fidelity progressively,+> nobody missing and nobody invented. The population chip reads `placed / total`+> while the square fills. The HUD title chip is the page's one `h1`, and every+> nameplate, roster row and passport resolves a citizen's craft through+> `citizenProfessionLabel` (primary craft first, the capability bitmap only as a+> fallback, since every citizen carries the Fetcher bit).**Goal:** Stand up `/agora` — the watchable world — on the existing Citysubstrate. Render real citizens from `/api/agora/citizens` as avatars living indiff --git a/docs/agora/tasks/06-economy-visuals.md b/docs/agora/tasks/06-economy-visuals.mdindex d6467360e..0faf60eed 100644--- a/docs/agora/tasks/06-economy-visuals.md+++ b/docs/agora/tasks/06-economy-visuals.md@@ -1,5 +1,21 @@# Task 06 — Living economy visuals+> **Status: shipped** (`src/agora/job-board.js`, `economy-fx.js`, `ticker.js`,+> wired by `economy-layer.js`). Three behaviours differ from the scope below.+> The **$THREE coin arc rides the `earned` activity** (`EconomyFx.onPayout`),+> not `completed_task`: the labour engine splits the moment in two and only the+> payout carries the amount, so a completion flows coins itself only when it+> names a reward (an Arena purse), and a `taskPda` dedupe keeps that purse from+> paying twice. The **board is bounded** (`board-rank.js`): on-chain bounties+> first, then reward order, with the roster ending in an honest+> `+N more open jobs in the bazaar` line because the x402 lane returns hundreds+> of services. And the plinth guards back-to-back completions with a load+> generation, so an overlapped GLB load is disposed on arrival instead of+> orphaned; off-production the deliverable is fetched through the dev `/r2-proxy`+> route so the plinth is not silently empty on localhost. Every layer honours a+> live `prefers-reduced-motion` toggle through `setReducedMotion(on)`. Kept as+> the build record.+**Goal:** Make the economy *legible at a glance* in the Commons. A job boardbuilding with glowing open tasks; citizens walking to claim; a busy state whilethey work; on completion the **deliverable materializes** (a Sculptor's GLB popsdiff --git a/docs/agora/tasks/07-verify-and-passport.md b/docs/agora/tasks/07-verify-and-passport.mdindex 91f999259..a8b59e7da 100644--- a/docs/agora/tasks/07-verify-and-passport.md+++ b/docs/agora/tasks/07-verify-and-passport.md@@ -1,5 +1,15 @@# Task 07 — Verify the work + the living passport+> **Status: shipped** (`src/agora/job-detail.js`, `verify.js`,+> `passport-panel.js`, `handshake.js`, composed by `trust-surface.js`). Since+> this was written: a deep link (`/agora?task=<pda>`) carries only the PDA, so+> the job panel falls back to the `deliverableUrl` and `proofHash` the lifecycle+> itself reports before it says "no proofHash recorded"; and the passport lists+> the citizen's **primary craft first** (`primaryProfessionKey`,+> `citizenProfessionLabel` from `citizen-avatar.js`) ahead of the rest of its+> decoded capability bitmap, which always opens with the baseline Fetcher bit.+> Kept as the build record.+**Goal:** Ship the **trust surface** — the thing that proves Agora isn't theater.Click a job → its on-chain lifecycle timeline + a **Verify deliverable** buttonthat re-downloads the artifact, re-hashes it in the browser, and shows it matchesdiff --git a/docs/agora/tasks/08-humans-first-class.md b/docs/agora/tasks/08-humans-first-class.mdindex c233b55d3..3ddc171d9 100644--- a/docs/agora/tasks/08-humans-first-class.md+++ b/docs/agora/tasks/08-humans-first-class.md@@ -1,5 +1,23 @@# Task 08 — Humans as first-class citizens+> **Status: shipped** (`api/agora/act.js` with actions `join`, `post-task`,+> `hire`, `claim`, `complete`, `vouch`; `api/_lib/agora-human.js`,+> `agora-policy.js`; UI in `src/agora/me-hud.js`, `post-form.js`, `actions.js`).+> Idempotency is the `Idempotency-Key` header backed by the durable+> `agora_idempotency` table. Hardening that landed after this was written:+> the rolling 24h spend cap is **held before the escrow** (`reservePostSpend`,+> `agora_spend_reservations`, one statement under a per-citizen lock) so two+> posts fired together cannot both clear headroom only one fits under; a dry+> wallet answers `409 insufficient_funds` with the fundable address, which the+> post form renders with a Copy button; a non-uuid citizen id answers 404 and a+> non-base58 task PDA answers 400 before any wallet work; a Solana RPC outage+> answers a retryable `503 rpc_unavailable`; and a confirm timeout is resolved+> from the ledger (a landed claim or completion is projected, a landed bounty+> answers `409 escrow_pending` instead of escrowing twice). The HUD shows a+> designed "Your bounty" state for a posting you made instead of a Claim button+> the chain can only reject, and publishes its live height as `--agora-dock-h`+> so the mobile layout stacks above it. Kept as the build record.+**Goal:** Let real, signed-in humans *live in* Agora alongside the agents: join asa citizen with their own avatar, **post a bounty** (escrow $THREE), **hire** acitizen, **complete** a task themselves, **verify** another's work, and **vouch**diff --git a/docs/agora/tasks/11-production-hardening.md b/docs/agora/tasks/11-production-hardening.mdindex ee929d0c9..7e66a81d3 100644--- a/docs/agora/tasks/11-production-hardening.md+++ b/docs/agora/tasks/11-production-hardening.md@@ -1,5 +1,11 @@# Task 11 — Production hardening + launch+> **Status: shipped, except the fleet-render performance box**, which is carved+> out as [task 12](12-fleet-render-performance.md). `/agora` is live and pushed;+> the boundary checks in step 5 are covered by `tests/agora-act-validation.test.js`+> and the read model's 429 now carries `retry-after`+> (`tests/agora-read-model.test.js`).+**Goal:** Take Agora from "works on my machine" to **100% production-ready** andlaunch it: tests across every new surface, all UI states audited, accessibility +performance verified, security/spend review, real deploy verification, the@@ -19,7 +25,7 @@ until every box here is true.- The `completionist` agent and `/code-review` — use them.## Build (scope)-1. **Tests.** `node --test` coverage for: the economy API shapes + empty/error+1. **Tests.** Vitest coverage (`npm test` is `vitest run && playwright test`) for: the economy API shapes + empty/errorpaths (mock the DB/bazaar at the boundary only — never ship mocks in app code);the engine's loop transitions, idempotency (no double-projection), and failureisolation; each profession module's proof derivation; `agora-mcp` tools;@@ -48,8 +54,9 @@ until every box here is true.7. **Docs + changelog + index.** Update `docs/agora.md` roadmap checkboxes toreflect 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). Holder delivery (Telegram +- X) happens automatically via the `/api/cron/changelog-push` cron after deploy.+ `npm run build:pages` (it validates the entry). Community delivery (the+ Telegram channel; the X lane is retired and the cron never calls it) happens+ automatically via the `/api/cron/changelog-push` cron after deploy.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.diff --git a/docs/agora/tasks/12-fleet-render-performance.md b/docs/agora/tasks/12-fleet-render-performance.mdindex 67587a5a6..e4737dc08 100644--- a/docs/agora/tasks/12-fleet-render-performance.md+++ b/docs/agora/tasks/12-fleet-render-performance.md@@ -20,6 +20,21 @@ world requests 200 citizens (`src/agora/agora-world.js`, `loadCitizens`) and`CitizenPopulation` streams them in `MAX_CONCURRENT_LOADS = 4` at a time(`src/agora/citizen-avatar.js`). Steady-state frame cost is **~900-1400ms**.+## What changed since the measurement++The load path the numbers above describe no longer exists, so the ~50s cliff+timing has to be re-measured before anything is concluded from it. Since+2026-08-16 every citizen stands up on the shared default rig first (one small+GLB for the whole crowd) and only the most recently active `MAX_PERSONAL_AVATARS`+(24 on desktop, 8 on a coarse pointer) upgrade to their own model+(`src/agora/citizen-avatar.js`, `_wearOwnAvatar`); the crowd is placed ten+citizens per frame and the citizens request is prefetched in parallel with the+map (`src/agora/agora-world.js`). The full 200 are therefore standing in+seconds rather than minutes, which moves the cliff earlier, and the per-frame+cost this task is about is unchanged: `CitizenPopulation.update` still runs+`mixer.update(dt)` for every instance every frame, so the suspected per-object+cost below applies to 200 skinned meshes exactly as before.+## What was ruled out| Hypothesis | Evidence against |diff --git a/docs/ar-studio.md b/docs/ar-studio.mdindex ea371a067..3fa6034d3 100644--- a/docs/ar-studio.md+++ b/docs/ar-studio.md@@ -20,20 +20,23 @@ The page ([`pages/ar-studio.html`](../pages/ar-studio.html)) only imports [`src/`addModel({ src, title })` normalizes the URL (https or site-relative only), enforces a 20-model cap, clones the loaded template (using SkeletonUtils for skinned rigs), and drops it on the floor in front of the camera. The "Add models" tray has five tabs:- **Recent forges**: read from local storage (`twx_ar_forge_recent`), shared with `/ar` so one forge history opens in two doors.-- **Yours**: `GET /api/forge-gallery?limit=24` with an `x-forge-client` header (your anonymous browser id).+- **Yours**: `GET /api/forge-gallery?limit=24` with an `x-forge-client` header (your anonymous browser id). Forge cards are titled with the first clause of the prompt they were generated from (`cardTitleFromPrompt`), with the whole prompt as the tooltip; a poster that fails to load falls back to the cube mark a poster-less item uses.- **Community**: `GET /api/forge-gallery?scope=community&limit=24`.- **Objects**: `GET /api/objects/library`, the CC0 prop library behind [/objects](https://three.ws/objects). The whole manifest is fetched once, so the tab's search box filters name and category client-side with no further requests, and renders matches 60 at a time.++Both gallery reads and the objects manifest answer with `Access-Control-Allow-Origin: *`: they are public, keyless, read-only feeds, and the standalone studio (npm `3d-ar-studio`) offers them as its Community and Objects tabs from whatever origin a developer embedded it on. Rate limiting, not origin, is the control.- **GLB link**: paste any https `.glb`: a forge result, a viewer share link's `src`, or your own hosting.A sixth source is the **in-view forge**: the dock form calls `POST /api/forge` with `{ prompt, backend: 'nvidia' }` (the free NVIDIA NIM / TRELLIS lane), polls `GET /api/forge?job=<id>` until the GLB is ready, remembers it, and drops it into the scene. A seventh is deep links: repeatable `?src=` (paired with `?title=`) and `?forge=<prompt>` boot content on open.### Device-capability ladder-Best available mode wins:+Best available mode wins. The dock's AR button (`#ars-xr-btn`) resolves one of three AR modes on load (`resolveArMode()`) and stays hidden when none applies:-1. **WebXR immersive AR**: offered only when `navigator.xr.isSessionSupported('immersive-ar')` resolves true. The session requests `hit-test` (required) plus `anchors`, `local-floor`, `depth-sensing`, and `light-estimation`, with a DOM-overlay HUD. Each placed model gets an `XRAnchor`, and an always-armed reticle does tap-to-place.-2. **Camera passthrough**: `getUserMedia({ video: { facingMode: { ideal: 'environment' } } })` becomes the background layer, with gyroscope world-lock look (DeviceOrientation, iOS permission-gated) and live light matching. Offered when `getUserMedia` exists.-3. **Desktop 3D preview**: always available: a grid floor, drag-look, and a "Phone" QR handoff on non-touch devices.+1. **WebXR immersive AR**: offered only when `navigator.xr.isSessionSupported('immersive-ar')` resolves true. The button reads **Immersive**. The session requests `hit-test` (required) plus `anchors`, `local-floor`, `depth-sensing`, and `light-estimation`, with a DOM-overlay HUD. Each placed model gets an `XRAnchor`, and an always-armed reticle does tap-to-place. This is the only mode that keeps the whole multi-model scene in the page.+2. **The device's own AR viewer**, one model at a time, when there is no immersive session. The button reads **Place in AR** and hands the selected model (or the last one placed) to the platform viewer: on iPhone and iPad, AR Quick Look ([`src/ar/quick-look.js`](../src/ar/quick-look.js)), after the GLB is fetched and converted to USDZ on the device through three's `USDZExporter` ([`src/usdz-pipeline.js`](../src/usdz-pipeline.js), the same pipeline `/avatars/:id/ar` uses), with each stage reported in the status line ("Fetching the model…", "Preparing it for AR…", "Opening AR…"); on Android, Scene Viewer ([`src/ar/scene-viewer.js`](../src/ar/scene-viewer.js)) with the GLB URL directly. A device with neither is told to open the scene on a phone and offered the QR code. Before this existed, an iPhone was only ever offered the camera composite below, which looks right in a screenshot and not at all in the hand (no plane detection, no real scale, nothing occluding).+3. **Camera passthrough**: `getUserMedia({ video: { facingMode: { ideal: 'environment' } } })` becomes the background layer, with gyroscope world-lock look (DeviceOrientation, iOS permission-gated) and live light matching. Offered when `getUserMedia` exists, and available alongside mode 2.+4. **Desktop 3D preview**: always available: a grid floor with distance fog (removed the moment the camera becomes the backdrop), drag-look, and a "Phone" QR handoff on non-touch devices. Until you aim the camera yourself, the preview re-frames on the models you add so a model dropped on the floor never lands out of view.If WebGL is missing, the page never loads the module and shows a fallback linking to `/ar` and `/viewer`.@@ -86,7 +89,7 @@ You can also hand-build a share link: append `?src=<https glb url>&title=<name>`- **No auth, fully free.** Identity is an anonymous per-browser id (`forge:cid`), shared with `/forge` and `/creations`; it scopes the Yours tab, attributes in-studio forges, and keys room ownership. No sign-in, no wallet, no payment.- **Placement caps.** 20 models per local scene; the shared room enforces its own per-room and per-owner caps and a per-client rate limit.- **Camera and motion.** Camera denial (`NotAllowedError`) shows "Camera permission is blocked... then try again"; no `getUserMedia` disables the camera button but keeps the 3D preview. Denied motion falls back to drag-look.-- **XR unsupported.** The Immersive button simply never appears; a failed XR start shows "Camera mode still works." Lost tracking prompts you to move to a brighter, more textured spot.+- **XR unsupported.** With no immersive session the button becomes Place in AR (Quick Look or Scene Viewer) or stays hidden; a failed XR start shows "Camera mode still works." A failed native handoff shows "Could not open AR for this model" with a Try again action. Lost tracking prompts you to move to a brighter, more textured spot.- **Rooms offline.** If the multiplayer server is unreachable or refuses the handshake, the studio drops back to single-player with "Shared rooms are offline right now, you can still build solo." and the room modal stays on its create/join panel. Departing authors' models remain until the room empties.- **Persistence.** Your own placed models are saved to local storage (`twx_ar_studio_scene_v1`); `#s=` links replace the working scene. Photo capture composites the camera and WebGL layers to a PNG.- **Forge failures.** `503`/unconfigured shows "The generator is offline"; `429` shows a busy message with a retry hint.diff --git a/docs/architecture.md b/docs/architecture.mdindex 1b713d505..49682429a 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -60,7 +60,7 @@ The top layer is what lets an agent live somewhere other than the canonical app.- **`widget-types.js`**: ten widget variants (Turntable Showcase, Animation Gallery, Talking Agent, ERC-8004 Passport, Hotspot Tour, Pump.fun Live Feed, Smart Money Feed, Live Trades Canvas, Bonding Curve, Walking Avatar) that share the underlying element but ship as separate ergonomic wrappers.- **`lib.js`** — the CDN entry. Imports the element, registers it, and re-exports the public surface.- **`app.js`** — the main SPA. URL routing happens here using hash params (`#model=`, `#agent=`, `#kiosk=`, `#brain=`, `#preset=`) and query params (`?agent=` for authenticated edit mode, `?pending=1` for post-login round-trips). The hash form stays in embed mode; the query form moves into edit mode.-- **`vercel.json`** — the server's route and cron table. Maps clean URLs (`/agent/<id>`, `/agent/<id>/edit`, `/agent/<id>/embed`, `/a/<chainId>/<agentId>`) to the right HTML entry and mounts the `api/*` handlers. In production the single Cloud Run container ([`server/index.mjs`](../server/index.mjs)) reads this table at runtime — it's a live config file, not a Vercel-only artifact.+- **`vercel.json`**: the server's route and cron table. Maps clean URLs (`/agents/<id>`, `/agents/<id>/edit`, `/agents/<id>/embed`, `/a/<chainId>/<agentId>`; the singular `/agent/<id>` forms are kept as permanent redirects to the plural canonical route) to the right HTML entry and mounts the `api/*` handlers. In production the single Cloud Run container ([`server/index.mjs`](../server/index.mjs)) reads this table at runtime: it is a live config file, not a Vercel-only artifact.---@@ -219,7 +219,7 @@ The flow:5. **Reputation.** Users can call `ReputationRegistry.submitFeedback(agentId, score, comment)` to attach reviews. The element exposes a small UI for this.6. **Validation attestations.** When the glTF validator runs, the report can be hashed and answered onto the agent's open request via `ValidationRegistry.validationResponse(requestHash, score, uri, hash, tag)` so anyone can verify the body has been spec-checked.-Per-chain registry addresses, ABIs, and helpers live in `src/erc8004/`. RPC endpoints fall back to public defaults but can be overridden with `?rpcURL=...`.+Per-chain registry addresses, ABIs, and helpers live in `src/erc8004/`. Every chain in `chains.js` carries an ordered `rpcUrls` list of keyless public hosts, and `src/shared/evm-rpc-fallback.js` prepends the same-origin `/api/evm-rpc?chainId=N` proxy (which inherits the server's own failover chain) whenever the page is served from a three.ws origin, so one dead public host never reads as "chain unsupported". A caller-pinned URL (`loadManifest(source, { rpcURL })`, or the `rpc-url` attribute on `<agent-3d>`) is tried ahead of the public tail.---@@ -241,7 +241,7 @@ To run the whole stack yourself, the minimum is:- **A Node.js host** for the SPA and the `api/*` handlers. Production runs a single container ([`server/index.mjs`](../server/index.mjs)) on Google Cloud Run that reads the `vercel.json` route table at runtime; any Node host works the same way, or reproduce the same path → handler map in your reverse proxy.- **Neon DB (PostgreSQL)** for agents, widgets, sessions, and the action log.- **Upstash Redis** for rate limiting, nonce storage, and short-lived caches.-- **An S3-compatible object store** for hosted GLB and texture assets. The client in [api/_lib/r2.js](../api/_lib/r2.js) speaks the S3 API, so Cloudflare R2, AWS S3, and Backblaze B2 all work (configure `S3_ENDPOINT`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`).+- **An S3-compatible object store** for hosted GLB and texture assets. The client in [api/_lib/r2.js](../api/_lib/r2.js) speaks the S3 API, so Cloudflare R2, AWS S3, and Backblaze B2 all work (configure `S3_ENDPOINT`, `S3_BUCKET`, `S3_PUBLIC_DOMAIN`, `S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`; `objectStorageConfigured()` is true only when all five are set, and the storage-dependent crons skip their tick rather than fail every item when it is not).- **Anthropic API key** for the default LLM provider. The runtime can also point at a self-hosted proxy (`#proxyURL=`) for billing, logging, or a non-Anthropic backend.- **Optional:** ElevenLabs for higher-quality TTS, Pinata or Filebase for IPFS pinning, Privy for non-wallet onboarding, an RPC endpoint for ERC-8004 reads.diff --git a/docs/authentication.md b/docs/authentication.mdindex 6f1add8a7..a0dda97a5 100644--- a/docs/authentication.md+++ b/docs/authentication.md@@ -283,6 +283,8 @@ When CAPTCHA is enabled for the Privy app (Privy dashboard, Security tab), PrivyIf the app config declares a `custom_api_url` (three.ws uses `https://privy.three.ws`), every auth call above goes to that domain instead of `auth.privy.io`.+The discovery step is factored into [src/auth/privy-captcha.js](../src/auth/privy-captcha.js), and the login page treats "CAPTCHA required" and "could not find out" as different answers: when the app config probe fails, the page refuses to send a code without a token Privy might require, and tells the user to reload rather than surfacing Privy's opaque `401 invalid_credentials`. The same distinction applies to `/api/config` itself: if that probe fails (it is bounded to six seconds), the email and wallet controls are hidden with an explanation and the password form still signs the visitor in, instead of the whole block silently vanishing as it does when the deployment genuinely has no Privy app.+### Configuration```env@@ -484,6 +486,7 @@ const res = await fetch('/api/agents', {| `memory:read` | Read agent memory || `memory:write` | Write agent memory || `profile` | Read/write profile data; required to manage API keys themselves |+| `herald:announce` | Post announcements through the [Herald](herald.md) (`POST /api/herald/announce`); the scope the `herald-mcp` package's `THREE_WS_API_KEY` needs |Scopes are space-separated in the `scope` field. Default when unspecified: `avatars:read avatars:write`.diff --git a/docs/avatar-inspector.md b/docs/avatar-inspector.mdindex dfc19c648..d86e8b5aa 100644--- a/docs/avatar-inspector.md+++ b/docs/avatar-inspector.md@@ -27,7 +27,7 @@ All data is real and server-authoritative, the same public endpoints everyother surface reads, so a number never disagrees across the platform:- **Identity**, display name, the three.ws agent the avatar pilots (with a- link to `/agent/<id>`), its bio, skills, creator, and ERC-8004 registration.+ link to `/agents/<id>`), its bio, skills, creator, and ERC-8004 registration.From `GET /api/agents/:id`.- **Reputation**, the 0, 100 trust score with its full pillar breakdown(tenure, settled volume, tips, reliability, conduct, …) and verifiable@@ -37,7 +37,10 @@ other surface reads, so a number never disagrees across the platform:USD net worth, SOL balance, $THREE holding, top tokens, and tips received.From `GET /api/agents/:id/solana/networth`. A player who signed in with awallet but pilots no agent gets bare balances from- `POST /api/wallet/balances`.+ `POST /api/wallet/balances`, which validates the address shape first (base58+ Solana or 0x-prefixed EVM) and answers `400 validation_error` with a+ field-level `issues` array instead of reporting a malformed address as an+ empty wallet.- **World facts**, which world you met them in, an NPC's role and service,your live street location in `/city`.diff --git a/docs/avatar-thumbnails.md b/docs/avatar-thumbnails.mdindex a4ce1a0f3..ed0d84b14 100644--- a/docs/avatar-thumbnails.md+++ b/docs/avatar-thumbnails.md@@ -90,12 +90,21 @@ via `adoptForgePreviews()` in the backfill.The browser captures the live viewer's canvas and uploads a PNG. Stored at`thumb/<avatarId>.png` with `Content-Type: image/png`. Owner or admin only.-### 3. Server render (headless chromium)--Everything else — studio avatars, uploads, forge rows older than preview capture —-is rendered server-side: the GLB is presigned, loaded into a headless chromium-running a three.js viewer, and screenshotted to a 768×768 PNG, which is uploaded to-`thumb/<avatarId>.png`. Costs ~3–6s per model, so it always runs in bounded batches.+### 3. Server render (CPU rasterizer, chromium failover)++Everything else (studio avatars, uploads, forge rows older than preview capture)+is rendered server-side through `renderGlbToPng()` in+[`api/_lib/render-glb.js`](../api/_lib/render-glb.js): the GLB is presigned and+rendered to a 768x768 PNG, which is uploaded to `thumb/<avatarId>.png`. The+renderer tries the in-process software rasterizer first+([`api/_lib/render-cpu.js`](../api/_lib/render-cpu.js), the `@three-ws/render`+package, roughly 200-900 ms and no subprocess) and falls back to headless chromium+running a three.js viewer only for the models the CPU lane cannot decode on its+own (Draco-compressed geometry, KTX2/Basis textures). A CPU miss is logged as+`[render] cpu lane fell back to chromium` and costs latency, never a failed+thumbnail. Set `RENDER_CPU_LANE=off` on the service to pin every render back onto+chromium without a deploy. A chromium render costs 3-15 s per model, so rendering+always runs in bounded batches.All of this lives in [`api/_lib/avatar-thumbs.js`](../api/_lib/avatar-thumbs.js),the single owner of the invariant above.@@ -156,15 +165,28 @@ So the runner distinguishes the two:- **Model failure** (`glb fetch failed: …`, `render failed: …`) — charge theattempt, record `last_error`, keep going.- **Infrastructure failure** (`Connection closed.`, `Target closed`, `Protocol- error`, …) — the model is blameless. Roll the attempt back, roll back every+ error`, a `spawn EFAULT` / `ENOMEM` / `EAGAIN` launch refusal, or object storage+ answering `Missing required env var: S3_…`, `InvalidAccessKeyId`, `NoSuchBucket`,+ `ECONNREFUSED`, …): the model is blameless. Roll the attempt back, roll back everyclaim the aborted batch never reached, and **stop the batch**. `renderBatch()`returns `aborted: "<reason>"`; the cron logs `backfill_browser_died` and the nexttick retries the same avatars on a fresh container.-`isBrowserInfrastructureError()` in-[`api/_lib/render-glb.js`](../api/_lib/render-glb.js) is the classifier, and the-cached browser now evicts itself on `disconnected` so the next render relaunches-instead of reusing a corpse.+Two classifiers decide which side a failure lands on. `isBrowserInfrastructureError()`+in [`api/_lib/render-glb.js`](../api/_lib/render-glb.js) covers the browser (its+`INFRA_ERROR_PATTERN`), and `isStorageInfrastructureError()` in+[`api/_lib/r2.js`](../api/_lib/r2.js) covers object storage (`STORAGE_ERROR_PATTERN`).+Both are exported as pattern strings so the ledger repair below asks the same+question in SQL with `~*` instead of maintaining a drifting copy, and+[`tests/avatar-thumbs.test.js`](../tests/avatar-thumbs.test.js) imports the real+classifiers rather than a stand-in for the same reason. The cached browser evicts+itself on `disconnected` so the next render relaunches instead of reusing a corpse.++Storage is also checked before any claim is made: both thumbnail crons return+`{ ok: false, reason: "object_storage_unconfigured" }` and touch nothing when+`objectStorageConfigured()` in `r2.js` reports the `S3_*` set incomplete, because+three ticks of identical `S3_BUCKET` failures at `*/5` would otherwise retire every+remaining avatar in under fifteen minutes.This is not hypothetical: before the classifier existed, one OOM-killed chromiumretired **1,283 perfectly renderable avatars** in a single run. If you ever suspect@@ -174,9 +196,12 @@ that happened again:node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --reset-infra```-It deletes every ledger row whose `last_error` is an infrastructure error, returning-those avatars to the candidate set. Rows recording a model-attributable error are-left retired. Safe to run at any time.+It deletes every ledger row whose `last_error` matches either infrastructure+pattern (browser or storage), returning those avatars to the candidate set. Rows+recording a model-attributable error are left retired. Safe to run at any time.+Add `--repair-only` to run the repair (and any `--restyle`) and stop before anything+touches R2: that mode needs only `DATABASE_URL`, so the undo stays reachable while+object storage is exactly the thing that is broken.Running more than one bulk backfill at once is what causes the OOM in the firstplace. The claim ledger makes it *correct*, but not *free* — one runner at@@ -209,10 +234,11 @@ node --env-file=.env.local scripts/backfill-avatar-thumbnails.mjs --restyle=200```Requires `DATABASE_URL` plus the `S3_*` credentials (`S3_BUCKET`,-`S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ENDPOINT`, `S3_PUBLIC_DOMAIN`).-Only `DATABASE_URL` is in `.env.local`; the authoritative copy of the `S3_*` set-lives on the Cloud Run service, so `--env-file=.env.local` alone exits with-`S3_BUCKET is unset`. Export them into the shell first:+`S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ENDPOINT`, `S3_PUBLIC_DOMAIN`);+`--status` and `--repair-only` need `DATABASE_URL` alone. Only `DATABASE_URL` is in+`.env.local`; the authoritative copy of the `S3_*` set lives on the Cloud Run+service, so `--env-file=.env.local` alone exits with `S3_BUCKET is unset` for any+mode that renders or adopts. Export them into the shell first:```basheval "$(gcloud run services describe three-ws-api --region us-central1 \diff --git a/docs/avatar-wardrobe.md b/docs/avatar-wardrobe.mdindex 5773bcbb2..a789c2037 100644--- a/docs/avatar-wardrobe.md+++ b/docs/avatar-wardrobe.md@@ -65,7 +65,7 @@ A garment with no skin at all (hat, glasses) is parented to a single joint|---|---|---|| Attachment engine | [`src/avatar-garment.js`](../src/avatar-garment.js) | Skin rebind, occlusion, slot occupancy — the runtime core || Shared taxonomy | [`src/garment-taxonomy.js`](../src/garment-taxonomy.js) | Slots, body regions, region→bone map, coverage gate |-| Catalog loader | [`src/garment-catalog.js`](../src/garment-catalog.js) | Fetch + validate manifests; drops anything malformed or unlicensed |+| Catalog loader | [`src/garment-catalog.js`](../src/garment-catalog.js) | Fetch (three bounded attempts, then the last copy this browser loaded) + validate manifests; drops anything malformed or unlicensed || Closet UI + controller | [`src/garment-closet.js`](../src/garment-closet.js) | Racks/tiles in the editor, attach/detach queue, appearance sync || Editor wiring | [`src/avatar-edit.js`](../src/avatar-edit.js) | Hydrate on load, persist `appearance.garments`, reset/save || Region mask (pixel-exact occlusion) | Baker [`scripts/build-body-region-mask.mjs`](../scripts/build-body-region-mask.mjs) → `public/avatars/parametric-base.regions.png`, sampler [`src/garment-region-mask.js`](../src/garment-region-mask.js) | On the parametric base, worn garments cut the skin via a baked UV mask (alphaMap) instead of triangle culling; any other body falls back to bone-cull |@@ -91,6 +91,15 @@ slot, unknown body region, malformed hash, or a licence outside the approvedcommercial set (CC0, CC-BY, MIT, Apache-2.0, BSD) drops the entry with aconsole warning. A broken manifest becomes a missing tile, not a broken avatar.+`loadCatalog()` fetches the file with a 10 s deadline and retries a 5xx or a+dropped connection twice more before giving up; a 4xx is final. When every+attempt fails it falls back to the copy the browser last loaded (kept in+`localStorage` under `three.ws:garment-catalog:<url>` for 24 hours) and logs a+warning, so a bucket blip no longer empties the closet. Only with no cached copy+does the load reject. The server-side baker reads the same URL through the shared+`fetchUpstream` helper (15 s deadline, two attempts) and caches it for five+minutes.+## Generating new garmentsThe catalog is fed by the Garment Forge@@ -105,6 +114,12 @@ GET /api/garment-forge?job=<id>→ { status, stage, glb_url, manifest_url, coverage, occludes }```+The proxy gives a submit one attempt with a 60 s deadline (it starts a GPU job,+so it is not safely repeatable) and a job read three attempts at 10 s each; both+share the `garment-forge-worker` circuit breaker, so a dead worker answers every+caller with `502 garment_forge_unavailable` at once instead of each paying the+full deadline.+`stage` walks `image → mesh → compose → rig → extract → validate → publish`.When the job reports `done`, the piece is already live in the catalog above;a closet refresh (`loadCatalog({ force: true })`) shows it immediately. Every@@ -147,8 +162,9 @@ bricking the avatar.- Garment can't reach the skeleton → refused with the measured coverage in thereason string; the slot keeps its previous occupant.-- Catalog unreachable → closet shows a retry state; the rest of the editor is- unaffected.+- Catalog unreachable → the closet serves the last catalog this browser loaded;+ with no cached copy it shows a retry state. The rest of the editor is+ unaffected either way.- Bake-time garment failure → logged and skipped; the bake always lands.- Non-humanoid model → the closet is withheld (`supportsWardrobe` gate), samepolicy as the animation library's humanoid gate.diff --git a/docs/aws-builder-center.md b/docs/aws-builder-center.mdindex 0f40af829..90aa0fe65 100644--- a/docs/aws-builder-center.md+++ b/docs/aws-builder-center.md@@ -20,6 +20,7 @@ The full AWS Marketplace SaaS usage-based integration, end to end: `ResolveCusto- **Source draft in this repo:** [aws-builder-center-marketplace-x402.md](./aws-builder-center-marketplace-x402.md)- **Code it documents:** [`api/aws-marketplace/`](https://github.com/nirholas/three.ws/tree/main/api/aws-marketplace), [`api/_lib/aws-marketplace.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/aws-marketplace.js), [`api/_lib/aws-marketplace-bridge.js`](https://github.com/nirholas/three.ws/blob/main/api/_lib/aws-marketplace-bridge.js)+- **Since publication:** on 2026-08-17 the integration moved to the updated SaaS integration AWS made mandatory for new products. `ResolveCustomer` now returns `CustomerAWSAccountId` + `LicenseArn` rather than a `CustomerIdentifier`, so the store keys buyers by license ARN (`api/_lib/aws-marketplace-store.js`) and the x402 bridge joins on the customer row id, with `CustomerIdentifier` kept only as a legacy lookup. Lifecycle notifications arrive as EventBridge agreement and license events; the SNS webhook path the article describes is still accepted and still signature-verified. [aws-marketplace.md](./aws-marketplace.md) is the current reference; the article stays accurate for the SDK calls it walks through.- **Announcement:** [three.ws Publishes on the AWS Builder Center Blog](https://three.ws/news/aws-builder-center-blog)### 2. Build Autonomous AI Agents with 3D Bodies and On-Chain Payments | three.ws on AWSdiff --git a/docs/btn-pill-migration.md b/docs/btn-pill-migration.mdindex 085a8b681..a2e5f12db 100644--- a/docs/btn-pill-migration.md+++ b/docs/btn-pill-migration.md@@ -1,7 +1,7 @@# Button + Pill Migration Map (B04)**Canonical system:** the `.btn` base + BEM modifiers live in `public/buttons.css` (B03, a portable partial that `public/style.css` `@import`s; any surface can also `<link>` it directly). The `.pill` base + semantic modifiers live in `public/style.css` (B04).-**Tokens:** B01 primitives in `public/tokens.css`; `--btn-*` and `--focus-ring-*` component tokens in `public/buttons.css`, `--badge-*` in `public/style.css`, `--disabled-*` in `public/tokens.css`.+**Tokens:** B01 primitives in `public/tokens.css`, which also carries the `--focus-ring-*` and `--disabled-*` component tokens; `--btn-*` component tokens in `public/buttons.css`, `--badge-*` in `public/style.css`.---@@ -16,6 +16,7 @@| `.btn.btn--secondary` | Explicit secondary (same as base, for readability) || `.btn.btn--ghost` | Transparent, text-only || `.btn.btn--danger` | Red-tinted |+| `.btn.btn--forge` | Gradient-bordered forge CTA with a live pulse dot (`.btn-forge-dot`); dark surfaces only || `.btn.btn--sm` | Small size || `.btn.btn--lg` | Large size || `.btn.btn--block` | Full-width |@@ -48,7 +49,7 @@ Linked pills: use `<a class="pill pill--onchain">` — gets hover/focus states a| `/deploy` (register-ui.js) | `erc8004-btn`, `erc8004-btn--primary`, `erc8004-btn--ghost`, `erc8004-btn--close`, `erc8004-btn--wallet`, `erc8004-btn--x` | Added `btn btn--primary/--ghost/--secondary/--icon` alongside || Pump launch modal (launch-token-modal.js) | `ltm-btn`, `ltm-btn-primary` | Added `btn btn--secondary/--primary` alongside || Homepage pump launcher (homepage-launcher.js) | `ltm-btn`, `ltm-btn-primary` | Added `btn btn--secondary/--primary` alongside |-| Nav drawer (nav.html) | `btn primary` | Added `btn--primary` BEM modifier |+| Nav drawer (public/nav.js renders it into the empty `nav-drawer` element in nav.html) | `btn primary` | Added `btn--primary` BEM modifier || On-chain badge (onchain-badge.js) | `tws-ocb`, `tws-ocb--md`, `tws-ocb--devnet` | Added `pill pill--onchain/--devnet pill--md` |---diff --git a/docs/ca2x402.md b/docs/ca2x402.mdindex bbb477627..1b70d0374 100644--- a/docs/ca2x402.md+++ b/docs/ca2x402.md@@ -31,8 +31,9 @@ Three steps, all real:shape-checked in the browser before a request is made(`/^[1-9A-HJ-NP-Za-km-z]{32,44}$/` or `/^0x[a-fA-F0-9]{40}$/`).2. **Resolve.** `GET /api/ca2x402/resolve` pulls the token's live market from- DexScreener and returns both the token preview and the generated service- descriptor. This read is free and unauthenticated.+ DexScreener (backed by a last-known-good copy, see below) and returns both+ the token preview and the generated service descriptor. This read is free+ and unauthenticated.3. **Ship.** The page renders the endpoint URL, its price and networks, threecopy-paste snippets, and a button that fetches the real `402 Payment Required`challenge from the live endpoint so you can see exactly what a buyer settles@@ -59,16 +60,26 @@ What happens, in order:1. **Validate.** A missing `mint` is `400 missing_mint`. An address that isneither a valid Solana mint nor a valid EVM address is `422 invalid_mint`.2. **Fetch the market.** `fetchTokenMarket()` calls the public DexScreener token- endpoint (no key) with a 6 second timeout, then picks the pair with the- deepest USD liquidity across every chain and DEX DexScreener knows for that- address. The address may sit on either side of the pair; the reader selects- whichever side matches what you passed.+ endpoint (no key) through the shared upstream fetcher (6 second timeout, two+ attempts, circuit breaker) and remembers the last payload it got for each+ address for 15 minutes, so a throttled indexer serves a few-minutes-old+ market rather than nothing. It then picks the pair with the deepest USD+ liquidity across every chain and DEX DexScreener knows for that address. The+ address may sit on either side of the pair; the reader selects whichever+ side matches what you passed.3. **No market found.** A well-formed address with no live pair (unlaunched, dead- liquidity, wrong chain, or an upstream hiccup) returns+ liquidity, or wrong chain) returns`404 { ok: false, error: 'token_not_found' }` with `cache-control: no-store`.The page renders that as a designed empty state. Nothing is fabricated to fillthe gap.-4. **Success.** `200 { ok: true, token, service }` with+4. **Indexer unreachable.** The resolver asks `fetchTokenMarketResult()`, which+ tells "no market exists" apart from "the indexer could not be reached". When+ DexScreener is down and this instance holds no remembered payload for the+ address, the answer is `503 { ok: false, error: 'market_unavailable',+ retry_after: 15 }` with a `Retry-After: 15` header and `cache-control:+ no-store`, never a `404` that would tell someone their real token does not+ exist. The page shows the error description with its retry button.+5. **Success.** `200 { ok: true, token, service }` with`cache-control: public, max-age=20, stale-while-revalidate=60`.### The `token` block@@ -202,8 +213,8 @@ Two failure modes are deliberately thrown **before** settlement, so a buyer isnever charged for a bad or missing answer:- `422 invalid_mint` when `mint` is absent or not a resolvable address.-- `503 data_unavailable` when DexScreener has no live market or no 24 hour change- for the token.+- `503 data_unavailable` when the market reader (DexScreener plus its 15-minute+ last-known-good copy) has no live market or no 24 hour change for the token.Access control uses the shared bypass hook with the `x402:bypass` scope([`api/_lib/x402/access-control.js`](../api/_lib/x402/access-control.js)), which isdiff --git a/docs/character-library.md b/docs/character-library.mdindex fc3d46142..66a7bf624 100644--- a/docs/character-library.md+++ b/docs/character-library.md@@ -1,4 +1,4 @@-# Character Library: 106 rigged characters, ready to animate+# Character Library: rigged characters, ready to animateThe Character Library is a free, curated gallery of professionally rigged humanoid 3D characters. Every character ships as a web-ready GLB with a full skeleton, skin weights, and textures, so it drives the entire three.ws animation library (idle, walk, run, wave, dance, and the rest of the canonical clip set) out of the box via animation retargeting. No account, no payment, no upload step: browse, preview live, and send any character into a studio in one click.@@ -11,13 +11,13 @@ Source: [`pages/character-library.html`](../pages/character-library.html) · [`s## What is in the library-106 professionally rigged Mixamo humanoid characters (Y Bot, X Bot, Warrok, Remy, Vanguard, zombies, knights, and more), staged as optimized GLBs on the R2 CDN. The manifest can also merge additional CC0 characters from other sources (for example Quaternius), so the API's `total` field is the authoritative count and can exceed 106.+A hundred-plus professionally rigged Mixamo humanoid characters (Y Bot, X Bot, Warrok, Remy, Vanguard, zombies, knights, and more), staged as optimized GLBs on the R2 CDN. The manifest can also merge additional CC0 characters from other sources (for example Quaternius), so the API's `total` field is the authoritative count. Nothing on the page hard-codes a number: the hero headline and the results counter render `total` from the manifest.Every entry is animation-ready: the GLB carries a skinned mesh, and the three.ws runtime retargets the canonical clip library onto it automatically (see [Animations](./animations.md) for how retargeting and the clip registry work). There is no per-character allowlist; any character in the library plays any clip.## Using the gallery-Each card renders the character live in an auto-rotating `<model-viewer>` (with the pre-rendered thumbnail as the poster) and offers three one-click routes:+Each card renders the character live in an auto-rotating `<model-viewer>` (with the pre-rendered thumbnail slotted in as a lazy-loaded poster image that fades once the model loads), shows the entry's `source` and file size, and offers three one-click routes. The viewer is control-free (no orbit, no extra tab stop); the whole thumbnail is a link to the preview. A manifest row with no `url` renders as a plain, unlinked tile with no actions.| Button | Destination | What you get ||---|---|---|@@ -29,7 +29,7 @@ Gallery controls:- **Search** filters by name; press `/` anywhere on the page to focus the search box.- **Sort** by name (A to Z, Z to A) or by file size (largest or smallest first). File size is shown on every card.-- The library is small enough that the page fetches the whole manifest once and filters client-side, so search and sort are instant.+- The library is small enough that the page fetches the whole manifest once and filters client-side, so search and sort are instant. Search, sort, card copy, and the deep links are pure functions of the manifest in [`src/shared/character-library-view.js`](../src/shared/character-library-view.js), covered by `tests/character-library-view.test.js`.- Loading shows a skeleton grid; an empty library, an empty search result, and a fetch error each have their own designed state with a recovery action.## API: `GET /api/avatars/library`diff --git a/docs/character-studio.md b/docs/character-studio.mdindex 99e695109..ce8905d81 100644--- a/docs/character-studio.md+++ b/docs/character-studio.md@@ -12,7 +12,7 @@ It is a rebranded fork of the open-source (MIT license) [M3-org/CharacterStudio]Where you meet it in the product:-1. Open an agent's edit page (`https://three.ws/agent/<agent-id>/edit`)+1. Open an agent's edit page (`https://three.ws/agents/<agent-id>/edit`)2. Click the avatar tile and choose **three.ws Studio** ("In-browser builder: hair, clothing, body") from the create menu3. The builder opens in a modal iframe; customize using the sections in the left panel4. Click **Save Avatar**; the finished GLB is handed back to the agent editor automatically@@ -102,7 +102,7 @@ RightUpperLeg → RightLowerLeg → RightFootThis means:- **Mixamo animations work**: the fork retargets Mixamo FBX clips onto the VRM rig (`loadMixamoAnimation.js`, `VRMRigMapMixamo.js`)-- **The three.ws animation library is fully compatible**: the platform's bone-name canonicalizer (`src/glb-canonicalize.js`) maps VRM rigs to the canonical set, so all built-in clips (idle, wave, walk, and the rest) work out of the box+- **The three.ws animation library is fully compatible**: the platform's bone-name canonicalizer (`src/glb-canonicalize.js`) maps VRM rigs (and every other humanoid convention it knows, MikuMikuDance's Japanese bone names included) to the canonical set, so all built-in clips (idle, wave, walk, and the rest) work out of the box- **Retargeting** is handled automatically by the animation manager (`src/animation-retarget.js`)---@@ -177,8 +177,9 @@ offers three real paths, each ending in a GLB the world adopts immediately:editor mode, which loads the Avaturn selfie→3D SDK (`@avaturn/sdk`). No sign-in required;the exported GLB is staged locally and used as your avatar instantly, then uploaded in thebackground so peers can load it too (`play-handoff.js`).-2. **Upload a .glb** — bring a model from Blender, Mixamo, VRoid, or any tool. Validated- client-side (`avatar-upload.js` `validateGlb`) before it becomes your avatar.+2. **Upload a model**: bring a `.glb` or `.vrm` from Blender, Mixamo, VRoid, or any tool.+ Validated client-side (`avatar-upload.js` `validateGlb`, which accepts both extensions+ since a VRM file is a glTF binary) before it becomes your avatar.3. **Advanced studio**: opens the native Avatar Studio at `/create/studio` in a newtab for deep body/face/hair/clothing sculpting, then saves to your account(see [Avatar Studio (native)](/docs/avatar-studio)).diff --git a/docs/chatgpt-ar.md b/docs/chatgpt-ar.mdindex c84a27fc8..8fc21e8a6 100644--- a/docs/chatgpt-ar.md+++ b/docs/chatgpt-ar.md@@ -31,7 +31,7 @@ The same free lane ships into ChatGPT twice, because ChatGPT has two integration### 1. The ChatGPT app (Apps SDK / MCP connector)-The MCP connector at `https://three.ws/api/mcp-studio` (no authentication) exposes ten free tools: six generation tools (`forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`), the `check_job` collector that picks up a generation which outran the tool call, and three persona/embodiment tools (`create_agent_persona`, `get_agent_persona`, `persona_say`). Full server documentation: [3D Studio MCP](./mcp-studio.md).+The MCP connector at `https://three.ws/api/mcp-studio` (no authentication) exposes eleven free tools: six generation tools (`forge_free`, `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`, `refine_model`), the `check_job` collector that picks up a generation which outran the tool call (a pending result now names its `stage`, `mesh` or `rig`, so the collector knows which leg it is waiting on), the read-only `look_at_model` tool that renders any public GLB from several angles and returns the frames as images plus a plain reading of its geometry, so the assistant can judge its own output before printing a link, and three persona/embodiment tools (`create_agent_persona`, `get_agent_persona`, `persona_say`, in [api/_mcp-studio/persona-tools.js](../api/_mcp-studio/persona-tools.js)). Full server documentation: [3D Studio MCP](./mcp-studio.md).Every successful tool result carries `arUrl` in its `structuredContent`, and the inline 3D widget renders it as a **View in your space** button next to the rotatable model. When the result is a rigged avatar the response additionally carries `irlUrl` and the button becomes **Bring it to life**. Refined versions (`refine_model`) each carry their own `arUrl`, so any point in the version lineage can be placed in the room.@@ -45,10 +45,10 @@ curl -s -X POST https://three.ws/api/3d/studio \-d '{"prompt":"a small ceramic robot figurine"}'```-Submit returns either the finished model or a job to poll:+Submit returns either the finished model or a job to poll (the response shaping lives in [api/_mcp-studio/studio-shape.js](../api/_mcp-studio/studio-shape.js), shared with the tests):```json-{ "status": "pending", "job": "…", "poll": "/api/3d/studio?job=…&title=a%20small%20ceramic%20robot%20figurine", "format": "glb" }+{ "status": "pending", "job": "…", "poll": "/api/3d/studio?job=…&title=a%20small%20ceramic%20robot%20figurine", "watchUrl": "https://three.ws/watch?job=…&title=…", "etaSeconds": 45, "format": "glb" }``````json@@ -68,6 +68,7 @@ Design decisions on this endpoint, all deliberate:- **The title-carrying poll.** ChatGPT Actions never resend context, so the submit response embeds the prompt in the poll URL as `&title=`. When the poll finally returns `done`, the `arUrl` and `viewerUrl` are labeled with the original prompt without the GPT doing anything except calling the poll path verbatim.- **Timeout honesty.** Actions calls time out around 45 seconds; generation takes 20 to 60. The endpoint holds the request as long as it safely can and falls back to `pending` + poll rather than dying mid-request.- **Safety before GPU.** Every prompt passes an age-13+ appropriateness gate ([api/_mcp-studio/safety.js](../api/_mcp-studio/safety.js)) before any provider work; refusals return `400 prompt_rejected` with a clear message.+- **An outage is an answer, not a 5xx.** When the poll finds the generation lane unconfigured upstream (`503`/`501` with `unconfigured` or `backend_unconfigured`), it answers `200 { "status": "error", "job": "…", "error": "3D generation is temporarily unavailable…" }`, so the GPT can tell the user plainly instead of surfacing a transport failure.The GPT's instructions tell it to present three links on every finished model, in this order: **See it in your space** (`arUrl`), **Preview in your browser** (`viewerUrl`), **Download** (`glbUrl`), and to never fabricate a URL an action did not return. The OpenAPI schema the GPT imports is served at [`https://three.ws/.well-known/3d-studio-openapi.yaml`](../public/.well-known/3d-studio-openapi.yaml) and describes `/api/ar` alongside the generation action, so the AR launch is part of the app's published contract rather than an undocumented link. The full GPT build sheet lives at [prompts/store-submissions/_generated/](../prompts/store-submissions/_generated/) (`openai-gpt-config.md`, plus `openai-actions.yaml`, which is regenerated from the served schema by `npm run sync:studio-openapi`).@@ -79,13 +80,13 @@ The GPT's instructions tell it to present three links on every finished model, i| Device | What the user gets ||---|---|-| **iPhone / iPad** | A launch page whose View in AR button opens Apple **Quick Look**. The USDZ Apple requires is generated from the GLB on the fly, in the page, by model-viewer's three.js `USDZExporter`. No server-side USD tooling exists or is needed. |+| **iPhone / iPad** | A tiny interstitial carrying the model's real `og:image`/`og:title` (so a pasted link still unfurls; crawlers do not follow a bare redirect's JS) that refreshes straight into **`/ar/view?src=…&title=…`** ([pages/ar-view.html](../pages/ar-view.html), [src/ar-view.js](../src/ar-view.js)). That Vite-bundled page generates a real USDZ from the GLB on the device with three's `USDZExporter` and then offers Apple **Quick Look** with a genuine `ios-src`. No server-side USD tooling exists or is needed; `<model-viewer>` alone does not do the conversion, which is why the AR page is a bundled page rather than HTML the handler writes inline. || **Android** (static model) | An HTTP `302` straight into Google **Scene Viewer** via an ARCore `intent://` URL, with a `browser_fallback_url` back to the WebGL viewer for devices without ARCore. |-| **Desktop** | The launch page falls back to the interactive WebGL viewer. There is no dead end: the link is safe to open anywhere. |+| **Desktop** | The same interstitial into `/ar/view`, which falls back to the interactive WebGL viewer. There is no dead end: the link is safe to open anywhere. |Responses set `vary: user-agent` so CDN caching stays correct per device class. Bad input (non-https, non-GLB, missing `src`) returns a designed error page, never a crash.-The pure routing logic (`detectArTarget`, `buildSceneViewerUrl`, `planArLaunch`) lives dependency-free in [api/_lib/ar-launch.js](../api/_lib/ar-launch.js) and is covered by [tests/ar-export.test.js](../tests/ar-export.test.js). The deeper AR reference (WebXR sessions, USDZ pipeline details, optimization limits) is [docs/ar.md](./ar.md).+The pure routing logic (`detectArTarget`, `buildSceneViewerUrl`, `buildArViewUrl`, `planArLaunch`) lives dependency-free in [api/_lib/ar-launch.js](../api/_lib/ar-launch.js) and is covered by [tests/ar-export.test.js](../tests/ar-export.test.js). `planArLaunch` now resolves every branch to a redirect target: Scene Viewer for a static model on Android, `/ar/view` for everything else, with `viewerUrl` and `sceneViewerUrl` still returned for callers such as the `export_ar` tool that want the raw URLs alongside the launch link. The deeper AR reference (WebXR sessions, USDZ pipeline details, optimization limits) is [docs/ar.md](./ar.md).---@@ -93,8 +94,8 @@ The pure routing logic (`detectArTarget`, `buildSceneViewerUrl`, `planArLaunch`)AR on three.ws is not a prop viewer; it is how agents cross into physical space. When the generated model is a rigged avatar (an agent's body), the pipeline appends `kind=avatar` to the `arUrl`, and the launcher changes behavior:-- The launch page leads with a **Bring it to life** handoff into [`/irl?avatar=<glbUrl>`](/irl), where the avatar walks, animates, and talks with the user through the camera, standing in their real room. See [IRL](./irl.md).-- Android is NOT blind-redirected into Scene Viewer, because that would hide the living path. It gets the launch page too, with static placement still one tap away.+- `/ar/view` receives the handoff as `&irl=<irlUrl>` and leads with a **Bring it to life** button into [`/irl?avatar=<glbUrl>`](/irl), where the avatar walks, animates, and talks with the user through the camera, standing in their real room. See [IRL](./irl.md).+- Android is NOT blind-redirected into Scene Viewer, because that would hide the living path. It lands on `/ar/view` too, with static placement still one tap away.In ChatGPT this happens automatically: the avatar-producing tools (`text_to_avatar`, `rig_mesh`, `forge_avatar`) set the flag and return `irlUrl` alongside `arUrl`, and the inline widget swaps its button label accordingly.@@ -107,7 +108,7 @@ A place-in-your-room link is built to be forwarded. When it is pasted into a cha- `og:title`: "Place `<title>` in your room"- `og:image`: `https://three.ws/api/render/glb?glbUrl=<encoded GLB>&width=1200&height=630`-`GET /api/render/glb` ([api/render/glb.js](../api/render/glb.js)) is a public, URL-addressable GLB-to-PNG renderer: point any image tag at it with a public GLB URL and get a PNG back (headless Chromium + model-viewer under the hood, the same pipeline as the platform's OG cards). It clamps dimensions to 64-2048, HEAD-checks the GLB at 10 MB max, is SSRF-guarded and per-IP rate-limited, and is CDN-cached for a day. The launch page itself ends with a "Create your own" link, so a shared model converts its recipient into a creator.+`GET /api/render/glb` ([api/render/glb.js](../api/render/glb.js)) is a public, URL-addressable GLB-to-PNG renderer: point any image tag at it with a public GLB URL and get a PNG back (the shared `renderGlbToPng` in `api/_lib/render-glb.js`: an in-process software rasterizer first, headless Chromium as the failover for Draco/KTX2 models, the same pipeline as the platform's OG cards). It clamps dimensions to 64-2048, HEAD-checks the GLB at 10 MB max, accepts a `background` of `transparent` or any CSS color (markup or anything else that is not a color is rejected with `400 bad_request`), is SSRF-guarded and per-IP rate-limited, and is CDN-cached for a day. The launch page itself ends with a "Create your own" link, so a shared model converts its recipient into a creator.---@@ -132,6 +133,8 @@ The generation lane is operator-funded (NVIDIA NIM running Microsoft TRELLIS for| AR launcher (`/api/ar`) + unfurl tags | [api/ar.js](../api/ar.js) || AR routing core (`buildArLaunchUrl`, device branch, IRL handoff) | [api/_lib/ar-launch.js](../api/_lib/ar-launch.js) || MCP studio tools + response envelope | [api/_mcp-studio/tools.js](../api/_mcp-studio/tools.js) |+| Studio Actions response shaping (`shapeSubmit`, `shapePoll`) | [api/_mcp-studio/studio-shape.js](../api/_mcp-studio/studio-shape.js) |+| The on-device AR page (`/ar/view`) | [pages/ar-view.html](../pages/ar-view.html), [src/ar-view.js](../src/ar-view.js) || Inline widget (View in your space / Bring it to life) | [api/_mcp-studio/component.js](../api/_mcp-studio/component.js) || GLB-to-PNG renderer (og:image) | [api/render/glb.js](../api/render/glb.js) || GPT OpenAPI schema (served, source of truth) | [public/.well-known/3d-studio-openapi.yaml](../public/.well-known/3d-studio-openapi.yaml) |diff --git a/docs/clash.md b/docs/clash.mdindex 8d2df6429..03f526303 100644--- a/docs/clash.md+++ b/docs/clash.md@@ -67,7 +67,7 @@ The Coin Clash state and leaderboard are also exposed read-only over MCP through- **Auth.** Viewing needs no login. Enlisting requires a connected Solana wallet and a message signature; rallying requires a valid war pass.- **Rate limits.** Enlist and enlist-verify are limited to 20 per 5 minutes per IP; rally is 40 per minute per wallet; state and leaderboard are 120 per minute per IP.- **Pass expiry.** A war pass lives 30 minutes; after that rally returns `401 pass_invalid` and the client transparently re-enlists if the wallet is still connected. Switching wallets drops the enlistment and prompts a re-enlist.-- **Empty and degraded states.** Fewer than 2 active communities shows "No battles live right now" with a link to `/communities`; a bye faction is labeled. An unconfigured community source shows a temporarily-unavailable state and stops polling. A Redis outage degrades silently to per-instance tallies and still serves 200s.+- **Empty and degraded states.** Fewer than 2 active communities shows "No battles live right now" with a link to `/communities`; a bye faction is labeled. An unconfigured community source shows a temporarily-unavailable state and stops polling. A request that never reaches the server (offline, blocked fetch) surfaces as a named connection error, "Couldn't reach the battle server", instead of the browser's raw "Failed to fetch". A Redis outage degrades silently to per-instance tallies and still serves 200s.- **Validation.** Taps must be a positive integer and are clamped to 50 per call. The ambient particle field is skipped under `prefers-reduced-motion`.## Relateddiff --git a/docs/coin-pages.md b/docs/coin-pages.mdindex 7dffe6da0..a71bae425 100644--- a/docs/coin-pages.md+++ b/docs/coin-pages.md@@ -55,6 +55,16 @@ Grotesk display face).The picked source is remembered across coins and visits (localStorage`tws_coin_chart_source`), and the embeds follow the site's light/dark theme.++ A third-party terminal that never renders is caught, not left as an empty+ box: [`src/shared/embed-guard.js`](../src/shared/embed-guard.js) gives each+ embed a 12 s deadline (started when it first scrolls into view, since a lazy+ iframe below the fold has not begun loading), and a TradingView script that+ is blocked outright or loads without ever injecting its chart trips the same+ path. The panel that replaces it says the provider did not load (an ad+ blocker, an extension or the network usually ate it), links to the same+ chart on the provider's own site, and offers a "Try again" that remounts the+ embed.- **Price performance matrix** — colored 1h / 24h / 7d / 14d / 30d / 60d /200d / 1y change cells, so the whole return curve is legible at a glance.- **Market stats** — market cap, 24h volume, circulating/total supply,@@ -112,6 +122,9 @@ through the shared [`failover-fetch`](../src/shared/failover-fetch.js) primitiveEach is normalized to the same shape in[`api/_lib/market-fallbacks.js`](../api/_lib/market-fallbacks.js); a fallbackthat only carries BTC dominance (CoinPaprika) simply shows one dominance chip.+ The Fear & Greed reading is fetched with one retry and keeps its last good+ value for a day (the index updates once daily), so an alternative.me blip+ never blanks the gauge.- **Market table** (`/api/coin/markets`) — CoinGecko → CoinLore. CoinLore backsup the ranked top-N list (7d sparklines and category scoping stayCoinGecko-only and degrade to an empty chart / CoinGecko-only when it's down).@@ -153,7 +166,10 @@ through the shared [`failover-fetch`](../src/shared/failover-fetch.js) primitive- **Derivatives table** (`/api/coin/derivatives`) — CoinGecko's cross-venue perpfeed, falling back to Hyperliquid's keyless info API([`api/_lib/hyperliquid.js`](../api/_lib/hyperliquid.js)): one venue instead of- dozens, but live price/funding/OI/volume for ~200 perps beats a 502. The+ dozens, but live price/funding/OI/volume for ~200 perps beats a 502. Because+ no other venue reports the same contracts, each Hyperliquid info query is+ retried once and keeps its last good answer for ten minutes (keyed by the+ query body), so a throw there never empties the derivatives view. Theresponse carries a `source` marker. Riding alongside whichever source answeredis a `deribit` block ([`api/_lib/deribit.js`](../api/_lib/deribit.js)): indexprices, funding-carrying perp tickers, and per-asset options aggregates from@@ -543,6 +559,19 @@ All data is real and fetched at runtime — nothing is hardcoded or sampled:| `/api/news/archive` | `gs://three-ws-news-archive` (662k-article JSONL corpus + indexes on GCS) | 300 s / 3600 s || `/api/coin/liquidations`| `services/liquidation-collector` (Binance/Bybit/OKX public liquidation WebSocket streams) | 15 s, `503` no-fallback offline |+The `/api/defi/*` handlers have DeFiLlama as their only upstream, so a TTL+cache alone would still 502 the moment it expired during an outage. Every+DeFiLlama read goes through the shared+[`upstream-fetch`](../api/_lib/upstream-fetch.js) helper (one retry on a+transient failure, `attempts: 2`) and each handler keeps its last good payload+past the TTL: `/api/defi/chain`, `/api/defi/protocol`, `/api/defi/yields` and+`/api/defi/hacks` hold theirs for six hours, the rest for the 30 minutes that+[`mem-cache`](../api/_lib/mem-cache.js)'s `cached()` mirrors every value into+its last-known-good tier. A response served from that copy carries an+`x-three-stale: 1` header so the page can say the numbers are not live rather+than pass them off as current; the header disappears the moment the loader+succeeds again.+Full request/response shapes: [api-reference.md → Coin Market Data API](api-reference.md#coin-market-data-api).The proxies live in [`api/coin/`](../api/coin) over the shareddiff --git a/docs/coin-wars.md b/docs/coin-wars.mdindex 6669079a5..99bb39754 100644--- a/docs/coin-wars.md+++ b/docs/coin-wars.md@@ -29,6 +29,9 @@ the UI.While a war involving your coin is live, anyone standing at the portal sees thescore, the round clock and a kill feed on the board without joining the fight.+A battle still in its lobby reads "waiting on both sides" until both communities+have fielded a fighter, and a battle that has already ended is never flown as+live: the portal skips it when it picks the running war to banner.---diff --git a/docs/configuration.md b/docs/configuration.mdindex 99121b4e3..686426346 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -106,6 +106,9 @@ OPENROUTER_API_KEY=sk-or-xxxxx#### `NVIDIA_API_KEY`**Optional.** NVIDIA NIM free tier, a third independent free lane.+#### `SAMBANOVA_API_KEY`, `MISTRAL_API_KEY`, `ZAI_API_KEY`+**Optional.** Three more free lanes, tried after NVIDIA in that order: SambaNova Cloud, Mistral's Experiment tier, and Z.AI's GLM Flash lane. Each joins the ladder only when its key is present, so `/api/chat` degrades across providers without a code change. The server-side completion chain in [api/_lib/llm.js](../api/_lib/llm.js) also accepts optional Cerebras, Gemini AI Studio, Cloudflare Workers AI (`CLOUDFLARE_ACCOUNT_ID` + `CLOUDFLARE_AI_API_TOKEN`), and SiliconFlow lanes on the same free-first rule.+#### `ANTHROPIC_API_KEY`**Optional (paid backstop).** Anthropic key, tried after the free lanes. Also accepted as a user-supplied BYOK key.@@ -231,7 +234,7 @@ VITE_CHARACTER_STUDIO_URL=http://localhost:5173The three.ws avatar builder is an open-source 3D avatar editor (full body customisation — hair, clothing, accessories, skin tone, proportions). It runs as a separate Vite/React app under `character-studio/` in this monorepo and posts the exported GLB back to the parent via `postMessage`. It is fully compatible with the three.ws avatar runtime — same humanoid skeleton naming, ARKit `viseme_*` blendshapes, and Mixamo animation support.#### `AVATURN_API_KEY`-**Optional.** API key for the photo-to-avatar pipeline. Used server-side by `/api/onboarding/avaturn-session` to exchange selfie photos for a session URL.+**Optional.** API key for the photo-to-avatar pipeline. Used server-side by `/api/onboarding/avaturn-session` (`api/onboarding/[action].js`) to exchange selfie photos for a session URL.```AVATURN_API_KEY=xxxxx@@ -261,10 +264,10 @@ VITE_AVATURN_DEVELOPER_ID=xxxxx```#### `AVATAR_REGEN_PROVIDER`-**Optional.** Provider for avatar regeneration. Set to `stub` for testing. Defaults to `none` (API returns `501 regen_unconfigured`).+**Optional.** Platform provider for avatar regeneration and reconstruction: `replicate`, `huggingface`, or `gcp` (`api/_lib/regen-provider.js`). When unset the provider is inferred from credentials, paid first: `REPLICATE_API_TOKEN` selects Replicate, then `GCP_RECONSTRUCTION_URL` the self-hosted Cloud Run worker, then `HF_TOKEN` the HF Spaces queue; with none of those the platform provider is `none` and the reconstruct endpoint falls back to a user's stored BYOK key (Meshy, Tripo) before answering `501`.```-AVATAR_REGEN_PROVIDER=none+AVATAR_REGEN_PROVIDER=replicate```---@@ -383,6 +386,8 @@ A **live configuration file** consumed at runtime by the Cloud Run server ([`ser**Key route patterns:**```json+{ "src": "/agents/([^/.]+)/edit", "dest": "/agent-edit.html" }+{ "src": "/agents/([^/.]+)/embed", "dest": "/agent-embed.html" }{ "src": "/agent/([^/]+)/edit", "dest": "/agent-edit.html" }{ "src": "/agent/([^/]+)/embed", "dest": "/agent-embed.html" }{ "src": "/agent/([^/]+)", "status": 301, "headers": { "Location": "/agents/$1" } }@@ -391,7 +396,7 @@ A **live configuration file** consumed at runtime by the Cloud Run server ([`ser{ "src": "/studio", "dest": "/studio/index.html" }```-**Embed routes** include security headers that allow cross-origin iframe embedding:+**Embed routes** (both the `/agents/:id/embed` and legacy `/agent/:id/embed` spellings) include security headers that allow cross-origin iframe embedding:```json{@@ -459,7 +464,7 @@ dist-lib/agent-3d.umd.cjs # UMD (CommonJS-compatible)Three.js and ethers are bundled (not externalized) so the web component works as a zero-install drop-in embed via `<script type="module">`.-**VitePWA** generates a service worker for the app build. Only `**/*.{ico,woff2}` are precached; HTML, JS, and CSS are deliberately excluded so deploys take effect immediately. Google Fonts are cached with a `CacheFirst` strategy and a 1-year TTL, and `/api/*` is never intercepted by the service worker.+**VitePWA** generates a service worker for the app build. Only `**/*.{ico,woff2}`, `offline.html` and `pwa-icon.svg` (the offline shell) are precached; HTML pages, JS, and CSS are deliberately excluded so deploys take effect immediately. Google Fonts are cached with a `CacheFirst` strategy and a 1-year TTL, and `/api/*` is never intercepted by the service worker.The dev server includes a rewrite middleware that mirrors the `vercel.json` route patterns, so `http://localhost:3000/agent/my-agent/edit` works the same as in production.diff --git a/docs/creator-portfolio.md b/docs/creator-portfolio.mdindex 817705bec..885897c8e 100644--- a/docs/creator-portfolio.md+++ b/docs/creator-portfolio.md@@ -14,7 +14,7 @@ feed/follow/rankings graph is covered in|---|---|| `/u/:username` | The public portfolio. No auth required; anyone can view it. || `/profile` | Self-view resolver for the signed-in user (see below). |-| `/u/0x<40 hex>` | Legacy wallet-address profile: the on-chain agent list for that address ([src/erc8004/user-profile.js](../src/erc8004/user-profile.js)). |+| `/u/0x<40 hex>` | Legacy wallet-address profile: the on-chain agent list for that address ([src/erc8004/user-profile.js](../src/erc8004/user-profile.js)). Each chain is read through `readProvider()` from [src/erc8004/chain-meta.js](../src/erc8004/chain-meta.js), which fails over across keyless public RPC nodes so one rate-limited endpoint cannot blank the list. |All three are served by [pages/profile.html](../pages/profile.html); the pageinspects the path segment and mounts the right view.@@ -55,8 +55,9 @@ instead.**Walking-avatar hero.** The owner's primary avatar walks live in an embedded`/walk-embed` iframe with two real CTAs: "Say hi" opens the avatar's live-chat surface, "Walk with me" opens the full walk experience alongside the-owner ([src/profile-walk-hero.js](../src/profile-walk-hero.js)).+chat surface (`/avatars/:id?view=chat` for an avatar, `/agents/:id#chat` for an+agent), "Walk with me" opens the full walk experience alongside the owner+([src/profile-walk-hero.js](../src/profile-walk-hero.js)).**Stats strip.** Followers and Following lead and are clickable (they openthe follow-list modal). After them, one tile per non-zero count: Creations,@@ -75,7 +76,7 @@ is active by default, and the bar hides when fewer than two tabs survive:|---|---|---|| Creations | Forged 3D models, saved worlds, and restyled models, merged by recency. Each card is a live rotating 3D thumbnail with the type badge (Model / World / Restyle), a remix tag where applicable, and a copy-the-prompt button. | `/viewer?src=<glb>` or `/diorama?id=<id>` || Avatars | Public avatars with tags, file size, fork count, and a Fork button. | `/avatars/:id` |-| Agents | Public agents with on-chain identity metadata (ERC-8004 id, wallet, `.sol` domain, X / Farcaster) and, when published, a Fork button. | `/agent/:id` |+| Agents | Public agents with on-chain identity metadata (ERC-8004 id, wallet, `.sol` domain, X / Farcaster) and, when published, a Fork button. | `/agents/:id` || Widgets | Public widgets with type and view count. | `/w/:id` || Skills | Published marketplace skills with category, per-call price, and installs. | `/marketplace#<slug>` || Plugins | Published plugins with installs and rating. | rendered in place |@@ -175,7 +176,11 @@ The header's share button opens a small menu: the native share sheet wherethe browser supports it, share to X, and copy link. Page title, description,and the OG/Twitter card (rendered live by[api/u-og.js](../api/u-og.js)) are rewritten per profile, so a shared link-unfurls with the creator's actual name and stats.+unfurls with the creator's actual name and stats. Because that image URL is+what a crawler resolves for `og:image`, a database blip while rendering it+degrades to a real card of the handle already known, sent `Cache-Control:+no-store`, rather than a JSON error body that a crawler would cache as the+unfurl; an unknown handle is still a cached 404 card.---diff --git a/docs/crypto-api.md b/docs/crypto-api.mdindex cb8630aef..35496f501 100644--- a/docs/crypto-api.md+++ b/docs/crypto-api.md@@ -474,7 +474,11 @@ array.- **No symbols** → `400 missing_symbols` with the cap and an `example`.- **More than 20 symbols** → `400 too_many_symbols` with the cap.- **Registry source down** → `200` with `degraded: true`; affected symbols get- `available: null` + a `note`. Never `500`.+ `available: null` + a `note`. Never `500`. Each lookup is retried once and+ keeps its last good DexScreener answer for 10 minutes, so through a throttle+ the result still lists the last known `exactCollisions` / `fuzzyCollisions`+ with `stale: true` (and `available: null`, because availability could not be+ verified live); a fresh answer carries `stale: false`.- **Rate-limited** → `429 rate_limited` with `RateLimit-*` + `Retry-After` headers.### Examples@@ -825,8 +829,11 @@ surfaces can never contradict each other.`concentration: "unknown"`, and a note — a valid empty, not an error.- **Missing/EVM/invalid `address`** → `400` with a clear message + example.- **Valid address that isn't an on-chain mint** → `400 token_not_found`.-- **Holder sources unreachable or throttled** → `503` + `Retry-After`. A throttled- RPC is never reported as "no holders". Never `500`.+- **Holder sources unreachable or throttled** → the last good answer for that+ `address` + `limit`, held for 24 hours, served as `200` with `stale: true`,+ `as_of` (when it was computed), and an `x-holders-stale: 1` header; with no+ last good copy, `503` + `Retry-After`. A throttled RPC is never reported as+ "no holders". Never `500`.- **Rate-limited** → `429` with `RateLimit-*` + `Retry-After` headers.### Examples@@ -906,6 +913,10 @@ that layer, computed once server-side so every client renders the same numbers.- **`slot`** - a palette slot per top asset, so the same wallet colors the sameway across reloads and across surfaces.- **`stale: true`** - present only when the balance source served a cached read.+ The 24h-change column has its own continuity: each DexScreener batch is+ retried once and keeps its last good pair list for 10 minutes, so a throttle+ no longer blanks every `change24h` in the batch in a way indistinguishable+ from a token that genuinely has none.### Sourcesdiff --git a/docs/daily-match.md b/docs/daily-match.mdindex 40c713a46..20747ddfa 100644--- a/docs/daily-match.md+++ b/docs/daily-match.md@@ -69,7 +69,8 @@ the client clock is always in sync with the server's window.`GET /api/leaderboard/daily-match?limit=N`- `limit`: 1 to 50, default 20 (the page requests 25).-- GET only, CORS-enabled, rate limited per client IP.+- GET only, CORS-enabled for any origin (it is a public, anonymous board, so a+ cross-origin fetch passes its preflight), rate limited per client IP.- Cached `public, max-age=15, s-maxage=30, stale-while-revalidate=60`.- Computed live per request over the daily window, the same pattern as[`api/leaderboard/unified.js`](../api/leaderboard/unified.js).diff --git a/docs/demo-routes.md b/docs/demo-routes.mdindex 9feddb262..9e0836d9f 100644--- a/docs/demo-routes.md+++ b/docs/demo-routes.md@@ -93,7 +93,7 @@ that canonical `.html` form.| Route | Page file | What it does ||---|---|---|-| `/demos/agents` | `public/demos/agents/index.html` | Hub for the lab below, linked from the `/demos/` index. `/demos/agents/` reaches it too, via the sitewide trailing-slash 301. |+| `/demos/agents` | `public/demos/agents/index.html` | Hub for the lab below, linked from the `/demos/` index. `/demos/agents/` reaches it too: `vercel.json` carries an explicit rewrite for both forms. || `/demos/agents/auto-rig.html` | `public/demos/agents/auto-rig.html` | Auto-rigging an imported mesh. || `/demos/agents/builds-button.html` | `public/demos/agents/builds-button.html` | Agent assembles a CTA button. || `/demos/agents/climb-title.html` | `public/demos/agents/climb-title.html` | Agent climbs the page title. |@@ -187,8 +187,8 @@ Re-verified against production (`https://three.ws`) with `curl -sIL`:resolve, so the `/demos/` index linked a URL that could not be served.It stayed invisible because the dev server has explicit `fileMap`entries for both forms in `vite.config.js`. `vercel.json` now carries- a `/demos/agents` rewrite to `/demos/agents/index.html`, placed above- the generic slug rule so it wins. It ships with the next deploy.+ a `/demos/agents` rewrite to `/demos/agents/index.html` (and one for+ `/demos/agents/`), placed above the generic slug rule so it wins.- Directory URLs with a trailing slash (`/demos/`, `/demo/`,`/demo/avatar-os/`) return **301** to the slashless form, which servesthe index with 200.diff --git a/docs/deployment.md b/docs/deployment.mdindex fb7dd80c4..41bba0872 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -331,7 +331,7 @@ TARGET=lib npm run build# Output: dist-lib/```-The Vite config handles multi-page routing, asset hashing, and the PWA manifest. Every JS file in `dist/assets/` is content-hashed, so you can serve them with long cache headers safely — the `vercel.json` route headers set `max-age=604800` on `/assets/*`, and the container (and any CDN in front of it) honors them.+The Vite config handles multi-page routing, asset hashing, and the PWA manifest. Every JS file in `dist/assets/` is content-hashed, so you can serve them with long cache headers safely: the `vercel.json` route headers set `public, max-age=31536000, immutable` on `/assets/*`, and the container (and any CDN in front of it) honors them.---@@ -342,8 +342,10 @@ The Vite config handles multi-page routing, asset hashing, and the PWA manifest.### Key rewrites```-/agent/:id/edit → /agent-edit.html-/agent/:id/embed → /agent-embed.html (frame-ancestors: * header)+/agents/:id/edit → /agent-edit.html+/agents/:id/embed → /agent-embed.html (frame-ancestors: * header)+/agent/:id/edit → /agent-edit.html (legacy spelling, still served)+/agent/:id/embed → /agent-embed.html (legacy spelling, same headers)/agent/:id → 301 → /agents/:id/agents/:id → /agent-detail.html (bot user-agents get the OG render)/dashboard → /dashboard-next/index.html@@ -369,7 +371,7 @@ The container does **not** schedule these itself — you need an external schedu### Static asset caching-Assets under `/assets/*` are served with a 7-day cache header. Versioned CDN bundles under `/agent-3d/x.y.z/*` are served with a 1-year immutable cache. Both are configured in `vercel.json` route headers.+Assets under `/assets/*` are content-hashed and served with a 1-year immutable cache header. Versioned CDN bundles under `/agent-3d/x.y.z/*` are served with a 1-year immutable cache. Both are configured in `vercel.json` route headers.---@@ -460,7 +462,7 @@ server {}location /assets/ {- expires 7d;+ expires 1y;add_header Cache-Control "public, immutable";}@@ -538,7 +540,7 @@ After deploying, run through these checks to verify the instance is healthy:| Wallet sign-in | Connect MetaMask — SIWE challenge + verify || Avatar creation | Navigate to `/create` — avatar builder iframe loads || Agent page | Visit `/agents/:id`: 3D viewer with chat overlay (`/agent/:id` 301-redirects here) |-| Embed | Check `/agent/:id/embed` loads without auth, can be iframed |+| Embed | Check `/agents/:id/embed` loads without auth, can be iframed || Dashboard | Navigate to `/dashboard` — shows your agents || API health | `GET /api/agents` returns JSON (may be empty array) || Auth metadata | `GET /.well-known/oauth-authorization-server` returns valid JSON |diff --git a/docs/docs-world.md b/docs/docs-world.mdindex 6aaed9ab8..9254cd9aa 100644--- a/docs/docs-world.md+++ b/docs/docs-world.md@@ -27,6 +27,8 @@ Both render the same files. The world fetches the same `/docs/nav.json` manifestThe **Index** chip (top left) lists every section; picking one teleports you to its pavilion and opens its page list. That list is fully keyboard-reachable, so nothing in the world requires mouse-precision walking.+The **Search docs** chip (or `/`, or `Ctrl`+`K`) opens a palette over every page. `Enter` on a result opens the page at once; `Shift`+`Enter` hands you to the wayfinder, which walks your avatar to the right pavilion with a live route readout, a **Read now** shortcut that skips the walk, and a cancel button. The **?** chip holds the controls table and a **Replay the welcome tour** button.+## Your avatarBy default you walk as the platform's default rigged body, the same one [/walk](/walk) uses, animated by the shared canonical clip library. Pass any rigged GLB with `?avatar=`:@@ -39,7 +41,7 @@ Any humanoid rig works; bone names are mapped automatically, exactly as describe## Devices and accessibility-- **No WebGL?** The page detects it and offers the classic docs instead; nothing is lost, because the content is identical.+- **No WebGL?** The page detects it and offers the classic docs instead; nothing is lost, because the content is identical. A failure a reload can fix (a dropped `/docs/nav.json` fetch, an exhausted WebGL context budget, an unexpected boot error) shows the same fallback with a **Try again** button, focused once it is visible; a device with no GPU never gets that button, because reloading cannot help it.- **`prefers-reduced-motion`** stills the ambient animation (floating labels, portal shimmer, drifting stars).- The reader panel is real DOM, not a texture: text is selectable, zoomable, and visible to screen readers.- Frame rate is governed like every three.ws 3D surface: 60fps focused, 30fps in the background or with the shared Power-saver preference on.@@ -73,7 +75,7 @@ Every link carries a `label` plus exactly one of:Three rules the test suite enforces in [`tests/docs-world.test.js`](https://github.com/nirholas/three.ws/blob/main/tests/docs-world.test.js), so a bad entry fails CI rather than shipping a dead link:-1. Every `path` must resolve to a markdown file that actually exists.+1. Every `path` must resolve to a markdown file that actually exists, in `docs/` (copied into the build) or `public/docs/` (served verbatim); either one reaches `/docs/<slug>.md`.2. A link is a `path` **or** an `href`, never both and never neither.3. No `path` may point into `docs/internal/`, `docs/ops/`, or `docs/security/`. Those directories are written for operators and are deliberately excluded from the published site, so a nav entry into one would 404 in production.diff --git a/docs/draft-agent-mint.md b/docs/draft-agent-mint.mdindex 69e8014d7..870e2110a 100644--- a/docs/draft-agent-mint.md+++ b/docs/draft-agent-mint.md@@ -134,7 +134,9 @@ The authority needs about 0.02 devnet SOL to cover the collection account, themint, and the registry enrolment on a first run. Fund it at<https://faucet.solana.com>. The script writes an evidence JSON (asset,signature, explorer link, storage checksum, chain read-back, EVM calldata) to-`DRAFT_MINT_E2E_OUT`, defaulting to your temp directory.+`DRAFT_MINT_E2E_OUT`, defaulting to your temp directory. At the end it deletes+the user, avatar, and agent rows it created (the chain artifacts are permanent+by nature); set `DRAFT_MINT_E2E_KEEP=1` to keep them.### Running it without cloud credentials@@ -215,6 +217,9 @@ explorer link, so the evidence file never overstates what was proven.| Agent already minted on this network | `already`, with the existing asset address, no chain write || Agent Registry enrolment fails | The mint still stands; the back-fill retries the enrolment later || No EVM treasury key | EVM leg returns `dry_run` with real calldata and a real gas estimate |+| `DRAFT_AGENT_MINT_EVM_CHAIN_ID` is not a chain in the table | EVM leg returns `skipped` / `unsupported_chain` |+| Treasury cannot cover the agent wallet's gas top-up | EVM leg returns `skipped` / `treasury_low:<balance>`; nothing is broadcast |+| Agent has no custodial EVM key to sign with | EVM leg returns `skipped` / `no_evm_key` || Database write fails after a mint | The avatar stamp is skipped with a warning; the on-chain asset and the agent meta are already written |## Relateddiff --git a/docs/economy-heartbeat.md b/docs/economy-heartbeat.mdindex 5f85acc09..f69fd4cb4 100644--- a/docs/economy-heartbeat.md+++ b/docs/economy-heartbeat.md@@ -8,7 +8,8 @@ every minute. When nothing hits them, the economy flat-lines while the site keepserving traffic.In production these endpoints are driven by **Google Cloud Scheduler** — one-job per `vercel.json` cron entry (~76 jobs), each firing `GET /api/cron/<name>`+job per `vercel.json` cron entry (the `crons` array there is the count; 110 at+the 2026-08-28 sync), each firing `GET /api/cron/<name>`with the `Authorization: Bearer $CRON_SECRET` header. (We do **not** use GitHubActions for any scheduling.)@@ -33,16 +34,20 @@ that makes the economy move:| --- | --- | --- || Payments & x402 | `x402-ring-tick`, `x402-seed-cron`, `x402-autonomous-loop`, `x402-ring-leak-scan`, `wallets-leak-scan`, `run-distribute-payments`, `payment-session-sweep` | ring settlements, micropayment feed, catalog spend, leak scans, payout distribution || Money Pulse, Labor & delegation | `pulse-tick`, `/api/labor/tick`, `index-delegations` | live wallet-activity feed, bounty bids/awards/settlements, agent hiring/delegation |-| Coin launches (pump.fun) | `launcher-tick`, `launcher-claimer`, `coin-intel-observe`, `pumpfun-monitor`, `pumpfun-graduations-sync`, `run-coin-cycle`, `run-coin-payouts` | autonomous minting, fee claims, launch intel, graduation sync, coin lifecycle + payouts |+| Coin launches (pump.fun) | `launcher-tick`, `launcher-claimer`, `pumpfun-monitor`, `pumpfun-graduations-sync`, `run-coin-cycle`, `run-coin-payouts` | autonomous minting, fee claims, graduation sync, coin lifecycle + payouts || Autonomous / copy / strategy trading | `copy-fanout`, `mirror-fanout`, `signal-fanout`, `strategy-fanout`, `run-dca` | copy trading, signal/strategy execution, DCA || Tips, payouts, subscriptions, royalties | `club-payouts`, `run-subscriptions`, `process-subscriptions`, `settle-royalties`, `cosmetic-splits-sweep` | tipping payouts, subscription billing, royalty + cosmetic-split settlement |-| $THREE buyback | `run-buyback`, `run-three-buyback` | revenue → buy → treasury (internally gated hourly/daily) |-| Funding, treasury & reconcile | `treasury-topup`, `treasury-autopilot`, `treasury-sweepback`, `economy-reconcile`, `reflect-sweep` | master-wallet funding root, treasury autopilot, tamper reconciliation |+| $THREE buyback | `run-buyback`, `run-three-buyback`, `three-buy-loop` | revenue → buy → treasury (internally gated hourly/daily), plus the x402-settled micro-buy loop |+| Funding, treasury & reconcile | `treasury-topup`, `economy-rebalance`, `treasury-autopilot`, `treasury-sweepback`, `economy-reconcile`, `reflect-sweep` | master-wallet funding root, economy rebalance, treasury autopilot, tamper reconciliation || $THREE market & holders | `three-market-refresh`, `three-holders-snapshot` | live coin market + holder snapshots |The snipers / autonomous trading experiment run as a **standalone always-on CloudRun worker** ([workers/agent-sniper/](../workers/agent-sniper)), not a scheduledcron, so they are continuous and not part of this dispatch list.+`coin-intel-observe` is also deliberately absent: it watches PumpPortal for 85s+inside its own 120s budget and runs on its own `*/2 * * * *` cron, so firing it+from the dispatcher aborted it at the 60s call timeout every minute and pinned+the heartbeat to `failed: 1`.Every target engine is internally idempotent — per-tick spend caps, per-endpointcooldowns, and daily ceilings absorb over-calling — so it is safe to fire@@ -148,6 +153,12 @@ CRON_SECRET=… DURATION_MINUTES=10 node scripts/economy-heartbeat.mjsno-ops the extra calls.- **Undeployed endpoints are tolerated.** A target missing from the deployedbuild reports `status: 404` and never stops the others.+- **A non-production process never drives production.** `APP_ORIGIN` falls+ back to `https://three.ws` wherever `PUBLIC_APP_ORIGIN` is unset (a laptop,+ CI, an audit session), so a process that is not a Cloud Run revision (no+ `K_SERVICE`) and would fan out to a non-loopback origin answers+ `200 { ok: true, skipped: "not_deployed" }` and fires nothing. Point+ `PUBLIC_APP_ORIGIN` at a local server to exercise the fan-out for real.Related: [circulation engine](circulation-engine.md) ·[x402 ring economy](x402-ring-economy.md) ·diff --git a/docs/erc8004.md b/docs/erc8004.mdindex 52478925a..789a03b51 100644--- a/docs/erc8004.md+++ b/docs/erc8004.md@@ -177,7 +177,7 @@ The registration wizard auto-generates the agent card JSON from your editor stat### Step 3: Upload to IPFS-The agent card and GLB are pinned to IPFS to create stable, content-addressed URLs. The platform pins files automatically via its backend storage. If you prefer to pin yourself, you can provide a Pinata JWT token — the system will upload directly to Pinata and return `ipfs://` URLs.+The agent card and GLB are pinned to IPFS to create stable, content-addressed URLs. The platform pins files automatically via its backend storage. If you prefer to pin yourself, you can provide a Pinata JWT token: the system will upload directly to Pinata and return `ipfs://` URLs. That direct upload is bounded to 60 seconds, and a Pinata failure or timeout falls through to the platform's own pinning route (`/api/erc8004/pin`) rather than failing the registration mid-flow, so the token is a preference, not a requirement.The GLB auto-thumbnail feature renders a PNG from your 3D model server-side so that NFT marketplaces and social cards display a 2D preview. You can supply your own image instead.@@ -365,11 +365,9 @@ The `<agent-3d>` element boots the full agent runtime — 3D rendering, memory,### IPFS fallbacks-The resolver tries multiple IPFS gateways in sequence when fetching metadata:-1. `ipfs.io`-2. `dweb.link`-3. `flk-ipfs.xyz`-4. `gateway.pinata.cloud`+`resolveUrl(uri)` turns an `ipfs://` URI into a single URL on the primary gateway (`ipfs.io`). `resolveUrlCandidates(uri)` returns the full ordered chain for the same content, and it no longer keeps a gateway list of its own: it delegates to `uriCandidates()` in [src/ipfs.js](../src/ipfs.js), which owns the one live, dead-host-free list for the whole platform. Today that chain is `ipfs.io` (the primary, kept at the head), then `dweb.link`, `flk-ipfs.xyz`, `w3s.link`, and `nftstorage.link`. `uriCandidates()` also re-extracts the CID from a URL whose gateway was already baked in upstream, so a card that hardcodes one gateway is still rotatable.++The manifest `toManifest(resolved)` builds keeps `image` and `body.uri` as single URLs (nothing that consumes them changes), and alongside them carries `_gatewayCandidates.body` and `_gatewayCandidates.image`: the ordered chain for each, starting with that same single URL. A consumer that can retry (an `<img>` fallback chain, a GLB loader) walks those instead of giving up on one dead gateway.Arweave (`ar://`) URIs are resolved through `arweave.net`.diff --git a/docs/erc8004/validation-attestation.md b/docs/erc8004/validation-attestation.mdindex c66f1204d..2c7634fa8 100644--- a/docs/erc8004/validation-attestation.md+++ b/docs/erc8004/validation-attestation.md@@ -78,6 +78,15 @@ maps to the same request, and a new model always gets its own.- **Verifying a proof.** `hashReport()` keccaks the report's compact JSON. Fetchthe pinned file, `JSON.stringify(JSON.parse(bytes))`, keccak it, and compareagainst the chain's `responseHash`.+- **One dead RPC never blocks an attestation.** The attestor signs against+ `evmFallbackProvider(chainId)` from `api/_lib/evm/rpc.js`, a quorum-1+ fallback over the chain's endpoint list in priority order, so both the reads+ in step 4 and the broadcast in step 6 go through whichever endpoint answers.+ On BSC Testnet that list leads with PublicNode, because the bnbchain data-seed+ nodes refuse every `eth_getLogs` call outright.+- **The `/validation` dashboard resolves `ipfs://` report links through the+ shared gateway list** in `src/ipfs.js` (`resolveURI`), the same rotation the+ rest of the platform uses, rather than one hardcoded gateway.## Badge statesdiff --git a/docs/event-readiness/04-play-multiplayer-net.md b/docs/event-readiness/04-play-multiplayer-net.mdindex b84497d2e..25b91d448 100644--- a/docs/event-readiness/04-play-multiplayer-net.md+++ b/docs/event-readiness/04-play-multiplayer-net.md@@ -14,11 +14,11 @@ The event means many strangers in one world at once. Connection handling has to## What to audit1. **Join path.** Time from page load to seeing other players. Any handshake failure must surface a designed, actionable error (what happened + retry button), never an empty world that looks single-player when it silently failed.-2. **Reconnect.** Kill the socket mid-session (devtools offline toggle, 10s, then online). The client must reconnect automatically, resync player positions, and show a subtle "reconnecting" indicator while it does. State after resync must match the server (no ghost players, no duplicated self).+2. **Reconnect.** Kill the socket mid-session (devtools offline toggle, 10s, then online). The client must reconnect automatically, resync player positions, and show a subtle "reconnecting" indicator while it does. State after resync must match the server (no ghost players, no duplicated self). Note `community-net.js` already reconnects with backoff: the attempt counter resets on every successful join, so `MAX_RECONNECT_ATTEMPTS` (14, about 11 minutes with the once-a-minute tail) bounds one outage and rides out a server redeploy before parking on `offline` with the manual `retry()`; a holder-gate refusal from `onAuth` is terminal and routes back to the gate instead of looping. A failed connect logs at info through the gated logger, not as a console warning. The boot watchdog in `pages/play.html` deliberately ignores a WebSocket-shaped rejection, so a flaky reconnect never trips the "could not load the world" card.3. **Backgrounding.** Switch tabs for 2 minutes and come back. Mobile Safari will have frozen the socket: same reconnect path must handle it.4. **Two-client consistency.** Open two browser contexts in the same coin world. Movement, chat, and emotes must appear on the other client within a human-imperceptible delay. Check name labels, avatar appearance, and cosmetics sync both ways.5. **Chat hygiene.** Long messages wrap, links do not inject HTML (verify escaping), spam has some throttle, and the log does not grow unbounded in memory.-6. **Voice.** If `voice-chat.js` is surfaced in the UI, test the full path: permission prompt, mute state visible to others, teardown on leave. If it is broken and unfixable today, hide the entry point rather than shipping a dead button.+6. **Voice.** `voice-chat.js` is surfaced (lazy-imported by `coincommunities.js` behind the HUD voice button), so test the full path: permission prompt, mute state visible to others, teardown on leave. Two hardening points to keep intact: a denied mic closes the `AudioContext` it just opened (browsers cap concurrent contexts, so leaking one per refusal made voice permanently unopenable), and an already-connected peer holds two ranks of hysteresis past `MAX_VOICE_PEERS` before it is dropped, so a crowd cannot churn WebRTC handshakes frame to frame. If it is broken and unfixable today, hide the entry point rather than shipping a dead button.7. **Scale behavior.** Simulate a crowded room (multiple headless Playwright contexts, or whatever the net layer allows). Watch for O(n^2) update patterns and per-player DOM label churn.8. **Mobile memory.** A phone that runs out of memory does not throw a JS error: the browser kills the tab, the socket dies mid-session, and the page reloads. In the server log that reads as a join followed by a leave a few seconds later, over and over, which looks like a networking bug and is not one. Watch the bytes, not the console. `scripts/play-mobile-repro.mjs` drives a phone-emulated /play session and prints every download attributed to the code that asked for it (`ENGINE=chromium node scripts/play-mobile-repro.mjs https://three.ws/play 120000`). Anything that loads community-uploaded models must work to a budget: the gallery is uncapped and single avatars there reach 24 MB. `src/game/ambient-crowd.js` holds the reference implementation (per-model cap, per-visit download cap, load-once-and-clone, release on leave).diff --git a/docs/event-readiness/05-play-economy-loops.md b/docs/event-readiness/05-play-economy-loops.mdindex bd220066c..5f57afd90 100644--- a/docs/event-readiness/05-play-economy-loops.md+++ b/docs/event-readiness/05-play-economy-loops.md@@ -11,13 +11,13 @@ The world's stickiness is its loops: gather, fight, trade, spin, buy cosmetics.- Quests: `src/game/quests-ui.js`- Cosmetics: `src/game/cosmetics-shop.js`, `cosmetics-purchase.js`, `cosmetics-loadout.js`, `cosmetics-wardrobe.js`, `cosmetics-flex.js`- Items and persistence: `src/game/items.js`, `src/game/world-persist.js`-- Published economy pages (must agree with the game): `/play/economy` and `/play/solver` (routes in `vercel.json`; both read from the same tables the game server prices with, so a mismatch means one side drifted)+- Published economy pages (must agree with the game): `/play/economy` and `/play/solver` (routes in `vercel.json`; `api/play/economy.js` imports every number from the same modules WalkRoom prices with, `multiplayer/src/{shop,items,cosmetics-catalog,spin-wheel,economy}.js`, so nothing is transcribed and a mismatch means one side drifted)## What to audit1. **Every loop end to end, with a real signed-in session.** Gather from a tree/rock/pond, sell at the store, bank cash, die and confirm the bank protected it, spin the wheel, complete a quest, buy and equip a cosmetic. Each step: correct payout, correct balance update in the HUD without a refresh, correct persistence across a reload.2. **Price truth.** Cross-check a sample of prices shown in-game against `/play/economy`. Any disagreement is a bug; find which side is stale.-3. **The $THREE boutique.** The cosmetics boutique charges $THREE: verify the full purchase path including insufficient-balance handling (clear message + how to get $THREE, never a silent failure or a raw error toast).+3. **The $THREE boutique.** The cosmetics boutique charges $THREE: verify the full purchase path including insufficient-balance handling (clear message + how to get $THREE, never a silent failure or a raw error toast). `boutique-purchase.js` already maps a short balance to "Not enough $THREE (or SOL for network fees) for this purchase. Get $THREE at three.ws/three-token, then try again.", times out a quote that never arrives, and only unlocks the item after the server's settle notice, never on the client's own "it worked"; verify that path holds rather than rebuilding it.4. **Race and double-spend.** Double-click every buy/spin/sell button fast. Balances must never go negative or double-charge; buttons must disable while a request is in flight.5. **Edge cases.** 0 inventory, full inventory, extremely long item names, network failure mid-purchase (the UI must reconcile with server state on reconnect, not trust its optimistic update).6. **Progression feel.** XP and skill levels visible, level-ups celebrated (even minimally), next-unlock always discoverable. If a loop pays out but gives no feedback (no sound/flash/toast), add the feedback; silent success reads as broken.diff --git a/docs/event-readiness/06-play-auth-errors.md b/docs/event-readiness/06-play-auth-errors.mdindex 62c827452..19583868f 100644--- a/docs/event-readiness/06-play-auth-errors.md+++ b/docs/event-readiness/06-play-auth-errors.md@@ -6,17 +6,17 @@ Event visitors will arrive signed out, with ad blockers, on flaky wifi, with wal- Auth flow: `src/game/play-auth.js`, `src/game/play-gate.js`, `src/game/play-handoff.js`- World boot (error surfaces): `src/game/coincommunities.js`, `src/game/boot-avatar.js`-- QA credentials for authed testing: `AUDIT_EMAIL` / `AUDIT_PASSWORD` in `.env` (a real production QA account); sweeps via `npm run audit:web` (anon) and `npm run audit:web:login` (authed)+- QA credentials for authed testing: `AUDIT_EMAIL` / `AUDIT_PASSWORD` in `.env` (a real production QA account); sweeps via `npm run audit:web` (anon) and `npm run audit:web:login` (authed). Both take route paths as arguments to scope the sweep (`npm run audit:web -- /play`) and `--engine webkit` or `--engine firefox` to run it in Safari's or Firefox's engine instead of Chromium (`npx playwright install webkit` once)## What to audit1. **Signed-out experience.** Load the canonical $THREE URL (see `docs/event-readiness/README.md`) with no session. How much of the world is explorable before a gate appears? The gate itself: is it an invitation (clear value, one-tap sign-in) or a wall? Fix toward invitation.2. **Sign-in mid-session.** Complete wallet sign-in from inside the world. The session must hand off without losing position or reloading the page if the flow supports it; if it must reload, state must restore.-3. **Session expiry.** Expire the session (clear the cookie/token) while playing, then perform an authed action (buy, bank). The user gets a re-auth prompt that resumes the action afterward, not a generic failure.+3. **Session expiry.** Expire the session (clear the cookie/token) while playing, then perform an authed action (buy, bank). The user gets a re-auth prompt that resumes the action afterward, not a generic failure. Note `play-gate.js` now reads the cached play pass first on boot, and reading is how it is reaped: `loadStoredPass()` drops an expired or corrupt entry before either early exit (config probe failing open, gate off for this world), so a dead token no longer outlives the boot and gets handed to a room join the server can only refuse.4. **Every fetch boundary.** Grep the play modules for `fetch(`/net calls and check each one handles rejection and non-2xx with a user-visible, actionable state. Internal code trusts itself; boundaries do not.-5. **Asset failures.** Block the IPFS coin image and one GLB in devtools. The world must render with fallbacks (placeholder texture, default rig per the `AnimationManager.supportsCanonicalClips()` gate), never a T-pose or an invisible avatar.+5. **Asset failures.** Block the IPFS coin image and one GLB in devtools. The world must render with fallbacks (placeholder texture, default rig per the `AnimationManager.supportsCanonicalClips()` gate), never a T-pose or an invisible avatar. A blocked or missing avatar GLB is a designed path in `boot-avatar.js`: it releases the loader, styles the card for the no-avatar case, and logs at info through the gated logger, so it costs a decoration, never the boot and never a console warning.6. **Bad query strings.** /play with no params, a garbage `coin=`, an XSS attempt in `name=`/`symbol=` (must render escaped, never execute), and an oversized `image=` URL. Each gets a sane default world or a designed error, and never script execution.-7. **Console zero.** `npm run audit:console` scoped to /play, plus a manual pass. Zero errors, zero warnings from our code, on both anon and authed runs.+7. **Console zero.** `npm run audit:console -- /play` (route paths passed as arguments scope the sweep; `--desktop` or `--mobile` picks one viewport), plus a manual pass. Zero errors, zero warnings from our code, on both anon and authed runs.## Verifydiff --git a/docs/event-readiness/07-platform-smoke-sweep.md b/docs/event-readiness/07-platform-smoke-sweep.mdindex f21a35f94..555724771 100644--- a/docs/event-readiness/07-platform-smoke-sweep.md+++ b/docs/event-readiness/07-platform-smoke-sweep.md@@ -7,7 +7,7 @@ Event visitors will not stay on /play; they will click around. Every page declarRun these against production first to find real user-facing breakage, then against `npm run dev` to fix:- `npm run smoke:prod`: sweeps every page in `data/pages.json` against the live site.-- `npm run audit:web`: unauthenticated browser sweep. `npm run audit:web:login`: authed sweep using the QA account (`AUDIT_EMAIL`/`AUDIT_PASSWORD` in `.env`).+- `npm run audit:web`: unauthenticated browser sweep. `npm run audit:web:login`: authed sweep using the QA account (`AUDIT_EMAIL`/`AUDIT_PASSWORD` in `.env`). Both accept route paths as arguments to narrow the sweep and `--engine webkit` or `--engine firefox` to run it outside Chromium (`npx playwright install webkit` once); a WebKit run counts one failed resource as one finding, not three. `npm run ui:review` is the visual sweep over the same route list.- `npm run audit:links`: dead links. `npm run audit:pages` and `npm run check:pages`: pages.json integrity.- `npm run audit:console`: console errors per page. `npm run audit:overlays`, `npm run audit:inline-handlers`, `npm run audit:routes`, `npm run audit:route-shadowing`: overlay/handler/route health.- `npm run audit:docs`: dead doc links and commands naming scripts that no longer exist.diff --git a/docs/event-readiness/11-event-live-ops.md b/docs/event-readiness/11-event-live-ops.mdindex 8def2b5b6..8e011de5a 100644--- a/docs/event-readiness/11-event-live-ops.md+++ b/docs/event-readiness/11-event-live-ops.md@@ -1,27 +1,27 @@# Feature 11: live event ops (broadcast, stage moments, event config)-Tomorrow the $THREE world hosts a live event. The countdown already exists (`src/game/event-countdown.js` reads `public/event.json` and mounts a lobby banner + in-world pill). What is missing is the live layer: a way for the operator to speak to everyone in the world at once, and for the world to visibly react when the event goes live. Build it end to end.+Tomorrow the $THREE world hosts a live event. The countdown already exists (`src/game/event-countdown.js` reads `public/event.json` through the shared `src/shared/event-config.js` reader and mounts a lobby banner + in-world pill). The live layer has since shipped in two of its three parts: the operator can speak to everyone in the world at once (`/internal/announce` + `scripts/announce-play.mjs`), and the world reacts when the event goes live (`src/game/meetup-event.js` agenda beats, go-live banner, and `src/game/fireworks.js`; the walkthrough is [docs/play-live-events.md](../play-live-events.md)). What is still missing is item 3, changing the event config without a redeploy. The list below records what exists so a rerun builds only the gap.## Where the code lives-- Event config + countdown: `public/event.json`, `src/game/event-countdown.js` (self-attaching, zero edits to the core modules; keep that pattern)-- Multiplayer server (in-repo): `multiplayer/src/rooms/WalkRoom.js`, `multiplayer/src/social-hub.js`; client socket + event bus: `src/game/community-net.js`+- Event config + countdown: `public/event.json`, `src/game/event-countdown.js` (self-attaching, zero edits to the core modules; keep that pattern). The same file is read by the home strip (`src/home-event-banner.js`), the API (`api/_lib/event-config.js`, from disk, cached a minute) and the game server (`multiplayer/src/event-window.js`, polled over HTTP every minute). Between events it holds an explicit no-event state (`id: null`) so `/event.json` still answers 200; edit it only through `npm run event:schedule -- --start <ISO> --duration <minutes> --apply` (`--rehearse 10` for a local dry run, `--clear` to reset) and gate the deploy on `npm run check:event`+- Multiplayer server (in-repo): `multiplayer/src/rooms/WalkRoom.js`, `multiplayer/src/social-hub.js`, the announce webhook in `multiplayer/src/index.js`; client socket + event bus: `src/game/community-net.js`- In-world screens for takeover moments: `src/game/x402-jumbotron.js`, `src/game/chart-screen.js`- Celebration FX precedent: the reaction-bar confetti in `src/game/coincommunities-ui.js`- Admin/API patterns: look at existing authed admin endpoints under `api/` before inventing a new auth scheme## What to build-1. **Operator broadcast.** An authed API endpoint (follow the repo's existing admin-auth pattern; never an open endpoint) that pushes an announcement through the Colyseus room to every connected player in a given coin world (or all worlds). Client side: a distinct, high-visibility announcement banner in the HUD, auto-dismissing, queued if several arrive. Server-side rate limit so a bad script cannot spam every player.-2. **Go-live moment.** When `event.json` flips to live (the countdown module already computes the state), the world marks it: jumbotron takeover with the event name, a one-shot celebration burst, and the countdown pill switching to its pulsing LIVE state. All of it must degrade to nothing when there is no event.-3. **Event config hardening.** `event.json` is baked into the image at build time, which means a config change mid-event needs a redeploy. Add a small authed read path (for example an `app_settings`-backed override checked after the static file) so the operator can extend, rename, or end the event live without a deploy. Document the exact curl in the runbook (`10-event-day-runbook.md`).-4. **Broadcast script.** A `scripts/` helper the operator runs from this workspace: takes a message, calls the endpoint, prints how many players received it.+1. **Operator broadcast.** Shipped as `POST /internal/announce` on the multiplayer server (`multiplayer/src/index.js`): HMAC-signed with `MULTIPLAYER_SHARED_SECRET` (falling back to `HOLDER_PASS_SECRET`) and timestamp-bound, so an unsigned or stale call is rejected before it reaches a room; there is no separate rate limit, the signature is the gate. It broadcasts on the existing `notice` channel (`kind: 'event'`, text capped at 300 characters, optional `title` 80 and `detail` 200, `durationMs` capped at 120 s) to every live `walk_world` room or one coin's world, so older clients get a toast and newer ones the centre-screen banner. Verify the banner queues, dismisses, and never overlaps chat or the joystick.+2. **Go-live moment.** Shipped in `src/game/meetup-event.js` (agenda, go-live banner) and `src/game/fireworks.js`, on the countdown pill's pulsing LIVE state. Everything reads the one config and mounts nothing when there is no event; keep it that way.+3. **Event config hardening.** Still open. `event.json` is baked into the image at build time, which means a config change mid-event needs a redeploy (today: `npm run event:schedule -- ... --apply`, `npm run check:event`, then the deploy runbook). Add a small authed read path (for example an `app_settings`-backed override checked after the static file, in `api/_lib/event-config.js` and `multiplayer/src/event-window.js` alike, since both read the file independently) so the operator can extend, rename, or end the event live without a deploy. Document the exact curl in the runbook (`10-event-day-runbook.md`).+4. **Broadcast script.** Shipped as `scripts/announce-play.mjs` (`node scripts/announce-play.mjs --title "Wheel hour" --detail "..." --coin <mint> --duration-ms 30000 "message"`; `--server http://localhost:2567` for a local test). It prints how many rooms and players it reached; the operator copy is in [LIVE-OPS.md](LIVE-OPS.md).## Verify- Two browser windows on `npm run dev` joined to the same coin world: a broadcast reaches both within a second; the banner queues, dismisses, and never overlaps the chat panel or mobile joystick.- `event.json` state transitions (upcoming, live, over) exercised by editing the local file; nothing mounts when it is absent.-- `npm test` green; add tests for the broadcast endpoint's auth and rate limit.+- `npm test` green; the broadcast endpoint's unsigned-call refusal is covered in `tests/multiplayer-server-boot.test.js`; add tests for the config override's auth.## Report formatdiff --git a/docs/event-readiness/14-welcome-concierge.md b/docs/event-readiness/14-welcome-concierge.mdindex 99c2ea90a..6c50d2469 100644--- a/docs/event-readiness/14-welcome-concierge.md+++ b/docs/event-readiness/14-welcome-concierge.md@@ -4,8 +4,8 @@ Most event visitors will be first-timers landing from one shared link. The onboa## Where the code lives-- NPC layer: `src/game/npc/npc.js`, `npc-catalog.js`, `npc-chat.js` (already talks to `/api/brain/chat`), `nav-graph.js` (pathing), `economy-npcs.js` for placement precedent-- Onboarding today: `src/game/play-onboard.js` (3-step overlay); intro card: `src/game/play-intro.js`+- NPC layer: `src/game/npc/npc.js`, `npc-catalog.js`, `npc-chat.js` (already talks to `/api/brain/chat`), `nav-graph.js` (pathing), `economy-npcs.js` for placement precedent, and `citizens.js` / `world-life.js` (every ambient walker is now a real citizen you can open and talk to; the closest precedent for a greeter that approaches once). Mind the chat gate: `/api/brain/chat` clamps a signed-out caller to the free providers under an anonymous rate limit and answers 401 for the paid first-party models, so the concierge persona must pin a free provider or first-timers get a sign-in wall instead of a welcome+- Onboarding today: `src/game/play-onboard.js` (3-step overlay; its control list is data with an `essential` flag, so a tour stop that teaches a key should reference that list rather than restate it); intro card: `src/game/play-intro.js`- Landmarks worth touring: the stations from `src/game/play-activities.js`, the chart jumbotron (`chart-screen.js`), the cosmetics boutique, the intel kiosk- First-visit detection: the same localStorage signals `play-onboard.js` usesdiff --git a/docs/event-readiness/15-live-hype-feed.md b/docs/event-readiness/15-live-hype-feed.mdindex 0edfaa36a..2e8d3623f 100644--- a/docs/event-readiness/15-live-hype-feed.md+++ b/docs/event-readiness/15-live-hype-feed.md@@ -4,9 +4,9 @@ A live world should feel alive even when you just stand there. The market alread## Where the code lives-- Market-to-world FX: `src/game/market-reactor.js`; trade feeds: `src/game/chart-screen.js` (`/api/pump/coin-trades`, `/api/robinhood/coin-trades` for hoodchain worlds)+- Market-to-world FX: `src/game/market-reactor.js` (it already detonates a beam over the totem on a whale-sized trade, so the hype moment extends that hook rather than adding a second one); trade feeds: `src/game/chart-screen.js` (`/api/pump/coin-trades`, `/api/robinhood/coin-trades` for hoodchain worlds). The chart badge now has a `stale` state after three consecutive failed polls, with the tape's age drawn under it: the ticker must go quiet on a stale tape, never celebrate from it. `api/robinhood/coin-trades.js` drops a malformed firehose event instead of 500ing the poll, so a quiet ticker means a quiet market, not a dead feed- Player joins/leaves: the Colyseus room state in `src/game/community-net.js` (the HUD online count already consumes it)-- In-world purchases worth celebrating: cosmetics buys, wheel wins, x402 payments (`agent-commerce.js`, `x402-jumbotron.js`)+- In-world purchases worth celebrating: cosmetics buys, wheel wins, x402 payments (`agent-commerce.js`, `x402-jumbotron.js`); war results already reach the platform feed as `war-result` events (`multiplayer/src/feed.js`) and the war portal holds a 9 s win takeover on its board (`HYPE_MS` in `src/game/war-portal.js`), the nearest precedent for a hype moment with a cooldown- HUD layer + toast precedent: `src/game/coincommunities-ui.js`, styles in `src/game/coincommunities.css`## What to builddiff --git a/docs/event-readiness/16-invite-flow.md b/docs/event-readiness/16-invite-flow.mdindex dfdd880ab..10416e998 100644--- a/docs/event-readiness/16-invite-flow.md+++ b/docs/event-readiness/16-invite-flow.md@@ -4,10 +4,10 @@ Everyone at the event arrives through one link, and everyone who has fun should## Where the code lives-- Deep-link contract: `coinWorldUrl()` (tested in `tests/fits-lib.test.js`); canonical URL emission in `src/game/coincommunities.js` (`history.replaceState` on entry)-- OG image for /play links: `api/play-og.js`; house OG patterns: `api/page-og.js`, `api/og-leaderboard.js`-- HUD mount + share precedent: `src/game/coincommunities-ui.js` and the build-share sheet-- QR: check `package.json` for an existing QR dependency first (open-source-first rule); a tiny well-maintained encoder is fine if none exists, no heavyweight additions+- Deep-link contract: `coinWorldUrl()` in `src/fits-lib.js` (tested in `tests/fits-lib.test.js`); canonical URL emission in `src/game/coincommunities.js` (`history.replaceState` in `enter()`, which keeps exactly `coin`, `name`, `symbol`, `image`, `tier` for a holders world, and `ui`; a bare `coin` link now resolves its name, symbol and image through `_fetchCoinIdentity` before the rewrite, so the canonical link is always complete)+- OG image for /play links: `api/play-og.js` (GET-only since the fleet hardening pass; any other verb is refused before the satori render); house OG patterns: `api/page-og.js`, `api/og-leaderboard.js`+- HUD mount + share precedent: `src/game/coincommunities-ui.js` and the build-share sheet. Do not confuse this with the friend invites in `src/game/friends-panel.js`, which are a social-graph request, not a world link+- QR: `qrcode` is already a dependency (`src/wallet-deposit.js` and `src/marketplace.js` render with it); use it, no new encoder## What to builddiff --git a/docs/event-readiness/17-plaza-live-show.md b/docs/event-readiness/17-plaza-live-show.mdindex b3ef957f7..f444d1d36 100644--- a/docs/event-readiness/17-plaza-live-show.md+++ b/docs/event-readiness/17-plaza-live-show.md@@ -1,19 +1,19 @@# Feature 17: live hosted show on a plaza stage inside /play-The platform already has Living Stages: an embodied AI host runs a real-time show with spatial voice, lip-sync, synced captions, an audience question queue, and a verified on-chain $THREE tip leaderboard where a tip pre-empts the host's next line in about a second. All of it works, and none of it is reachable from the world: `grep -r stage src/game/` finds zero references. Put a stage in the $THREE plaza and let the event crowd attend a show without leaving /play.+The platform already has Living Stages: an embodied AI host runs a real-time show with spatial voice, lip-sync, synced captions, an audience question queue, and a verified on-chain $THREE tip leaderboard where a tip pre-empts the host's next line in about a second. All of it works, and none of it is reachable from the world yet. Half of this build has landed: `src/game/plaza-stage.js` is the landmark (platform, canvas marquee via `screen-texture.js`, a proximity gate, a 45 s show-state poll while a player is near), `multiplayer/src/plaza-stage.js` derives the stage id, `PLAZA_STAGE` in `multiplayer/src/world-features.js` is the server-validated footprint, and `api/stage/index.js` answers `GET /api/stage?coin=<mint>` and claims a plaza with `POST /api/stage { action: 'plaza', agentId, coinMint }`. But nothing imports `plaza-stage.js` (`coincommunities.js` never mounts it), and the show client it dynamically imports on first proximity, `src/game/plaza-stage-show.js`, does not exist. Finish it: mount the landmark and write the show client so the event crowd can attend a show without leaving /play.## Where the code lives- Show engine (server): `multiplayer/src/rooms/StageRoom.js`, `multiplayer/src/stage-show.js` (the pure `ShowDirector` with beats OPENER, TIP_SHOUTOUT, ANSWER, BANTER, GAME), `multiplayer/src/stage-schemas.js`, `multiplayer/src/stage-registry.js`. Room registered as `stage_world` with `filterBy(['stageId'])` in `multiplayer/src/index.js`- Show client (page-level, reuse it): `src/stage.js`, `src/stage-net.js`, `src/stage-element.js`, served at `pages/stage.html`-- Show API: `api/stage/index.js` (directory, create, golive, endshow, `nextShowAt` scheduling), `api/stage/host.js` (the host's words), `api/stage/tip.js` (on-chain verified, idempotent per signature); host voice via `api/tts/speak`+- Show API: `api/stage/index.js` (directory, create, golive, endshow, `nextShowAt` scheduling, plus the `?coin=` read and the `plaza` claim; one `stageDetail()` serves the `?id=` and `?coin=` reads so /stage and the plaza never see two shapes of the same show), `api/stage/host.js` (the host's words; the prompt names $THREE as the only coin the host may mention, and `sanitizeLine` strips control characters and dashes from every spoken line before it becomes a caption), `api/stage/tip.js` (on-chain verified, idempotent per signature); host voice via `api/tts/speak`- The world to mount into: `src/game/coincommunities.js` (main scene), landmark placement precedent in `src/game/wheel-station.js` and `src/game/home-town.js`; server-validated landmark coordinates in `multiplayer/src/world-features.js`- Multiplayer client for the world room: `src/game/community-net.js` (Colyseus `walk_world`); the stage join is a second, concurrent room connection## What to build-1. **The stage landmark.** A real stage structure in the $THREE world plaza: platform, backdrop, marquee screen. The marquee shows the show state from `api/stage/index.js`: live now, next show time (`nextShowAt`), or a designed idle state. Register its footprint in `world-features.js` so the server can validate proximity.-2. **Proximity attendance.** Walking near the stage joins the coin's `stage_world` room alongside the existing `walk_world` connection (derive `stageId` from the mint deterministically). Reuse `stage-net.js` and the utterance rendering from the stage client rather than rewriting: the host avatar on stage speaks with TTS voice, lip-sync, and captions, synced across every attendee. Walking away leaves the stage room cleanly.+1. **The stage landmark.** Built in `src/game/plaza-stage.js` but not mounted: construct it from `coincommunities.js` next to the wheel station and the war portal. The marquee already reads the show state from `GET /api/stage?coin=`: live now, next show time (`nextShowAt`), or a designed idle state. The footprint is `PLAZA_STAGE` at (18, 26) with a 5 m radius in `world-features.js`, sized to contain the golden-angle seat ring StageRoom deals out (6.0/7.6/9.2 m from the stage origin).+2. **Proximity attendance.** Walking near the stage joins the coin's `stage_world` room alongside the existing `walk_world` connection. `stageId` is already derived: `plazaStageId(mint)` in `multiplayer/src/plaza-stage.js` is uuidv5 of the mint, which is both the `stage_world` `filterBy` key and the `stages.id` a plaza claim writes, so client and server agree offline. Write `src/game/plaza-stage-show.js` (the module `plaza-stage.js` lazy-imports on first proximity) around `stage-net.js` and the utterance rendering from the stage client rather than rewriting: the host avatar on stage speaks with TTS voice, lip-sync, and captions, synced across every attendee. Walking away (past `LEAVE_HYSTERESIS_M`, 3 m beyond the edge) leaves the stage room cleanly.3. **Audience presence.** Attendees get the server-assigned ring seats StageRoom already deals out, rendered as marked spots in front of the stage; the question queue is reachable from the in-world chat bar while attending.4. **Tips in-world.** A tip action at the stage that runs the existing `api/stage/tip.js` flow (this is an on-chain $THREE spend: render recipient, amount, and token and get the user's explicit confirmation before signing, every time). The tip leaderboard renders on the marquee, and a landed tip pre-empts the host beat exactly as it does on /stage.5. **Cost discipline.** Everything here mounts lazily on first proximity and fully unmounts when the show is over and the player leaves. No stage room connection, no TTS fetches, no per-frame work for players who never approach. When no show exists and none is scheduled, the stage is a quiet decorated landmark, not an error.diff --git a/docs/event-readiness/18-coin-wars-portal.md b/docs/event-readiness/18-coin-wars-portal.mdindex e36aeafe1..490353bf4 100644--- a/docs/event-readiness/18-coin-wars-portal.md+++ b/docs/event-readiness/18-coin-wars-portal.md@@ -1,22 +1,23 @@# Feature 18: Coin Wars portal inside the world-Coin Wars is finished and invisible. `ClashRoom` runs full community-vs-community battles (lobby, countdown, live, sudden death, kill cap, round clock) with an Elo league behind it, but the only door is the standalone page at /play/arena. Nobody standing in the $THREE world knows wars exist. Build the portal: see the standings, queue for a war, and come back with the result, all from inside /play.+Coin Wars is finished and, since the portal landed, visible. `ClashRoom` runs full community-vs-community battles (lobby, countdown, live, sudden death, kill cap, round clock) with an Elo league behind it, the arena is a real page at /play/war, and every coin world's plaza has a war portal (`src/game/war-portal.js`, constructed by `coincommunities.js`) to see the standings, queue for a war, and come back with the result without leaving /play. The player-facing walkthrough is [docs/coin-wars.md](../coin-wars.md). This prompt is now the spec to verify against and extend, not a blank build.## Where the code lives-- Server: `multiplayer/src/rooms/ClashRoom.js` (registered as `clash_arena` with `filterBy(['matchKey'])` in `multiplayer/src/index.js`), match logic in `multiplayer/src/clash.js`, league in `multiplayer/src/war-standings.js`, summaries in `multiplayer/src/war-report.js`, schemas in `multiplayer/src/clash-schemas.js`-- Arena client to hand off to: `pages/play/arena.html`, `src/play/arena.js`, `src/play/arena-world.js` (read how it resolves `matchKey` and gates entry before inventing anything)+- Server: `multiplayer/src/rooms/ClashRoom.js` (registered as `clash_arena` with `filterBy(['matchKey'])` in `multiplayer/src/index.js`), match logic in `multiplayer/src/clash.js`, league in `multiplayer/src/war-standings.js`, summaries in `multiplayer/src/war-report.js`, schemas in `multiplayer/src/clash-schemas.js`, pairing in `multiplayer/src/war-matchmaking.js` and live-war state in `multiplayer/src/war-live.js`+- Public API: `api/wars.js` (`GET /api/wars?coin=` for the board, `?action=live` for the spectator poll, `POST ?action=queue` and `?action=leave` for the queue, `POST ?action=report` for the game server's HMAC-signed result), backed by `api/_lib/wars-store.js` and the signed war ticket in `api/_lib/war-ticket.js`. Standings are folded from the battle ledger by `war-standings.js`, the same module the arena uses, never recomputed+- Arena client the portal hands off to: `pages/play/war.html`, `src/play/war.js`, `src/play/war-world.js` (ClashRoom is authoritative; the client renders and sends intent). `/play/arena` (`src/play/arena.js`, `arena-world.js`) is the Sniper Arena, the AI-agent trading floor, not Coin Wars; do not route war traffic there- Gating: the same holder pass as the Holders world (`multiplayer/src/holder-pass.js`, `api/community/holder-pass.js`)-- World mount: landmark precedent in `src/game/wheel-station.js`; jumbotron precedent in `src/game/chart-screen.js`; live feed producer `multiplayer/src/feed.js`-- Deep-link return path: the canonical URL emission in `src/game/coincommunities.js` (`history.replaceState` on entry)+- World mount: the portal in `src/game/war-portal.js` follows the landmark precedent in `src/game/wheel-station.js` and the canvas-board precedent in `src/game/chart-screen.js`; live feed producer `multiplayer/src/feed.js` (`war-result` is an allowed event type)+- Deep-link return path: the canonical URL emission in `src/game/coincommunities.js` (`history.replaceState` in `enter()`)## What to build-1. **The portal landmark.** A war portal structure in the plaza with a board showing real league state: this coin's Elo standing, recent war results (`war-report.js` output), and any war currently live. If the standings surface has no public API yet, expose one thin read endpoint under `api/` that serves exactly what the arena client already trusts; do not fork the math.-2. **Queue from the world.** An "enter the war" interaction that runs the same gate the arena page runs (holder pass where required), resolves the `matchKey` the same way, and hands off to `/play/arena` with a return link that carries the full coin identity (`coin`, `name`, `symbol`, `image`) so coming back lands in the same world with no lobby detour.-3. **Spectate without leaving.** While a war involving this coin is live, the portal's board becomes a spectator screen: live score, kill feed, round clock, sourced from the clash room state or a cheap polling read. Text and numbers, not a second 3D render.-4. **Results echo.** When a war ends, the result lands in the world: a feed event through `multiplayer/src/feed.js` and a short jumbotron moment for a win. If Feature 15's ticker landed, the result appears there too.-5. **Honest empty states.** No wars yet, standings empty, matchmaking quiet: each state says what it is and what a player can do about it, in the designed style of the lobby's retry cards.+1. **The portal landmark.** Shipped: the board in `war-portal.js` paints this coin's league row, recent battles, and any live war from `GET /api/wars`. Idle cost is zero by design: nothing is fetched until a player is inside the board's legibility ring (`WAR_PORTAL_BOARD_REACH`), the slow poll runs while someone idles near it, and the fast poll only while a war involving this coin is live, the panel is open, or the community is queued. Verify those cadences hold; do not add a second fetch path.+2. **Queue from the world.** Shipped: E at the portal runs the holder gate, `POST /api/wars?action=queue` pairs the community with a waiting one and returns the `matchKey` plus a signed war ticket (ClashRoom takes both competing communities from the ticket, never from a joining client), and the handoff goes to `/play/war` with a return link carrying `coin`, `name`, `symbol`, `image` so coming back lands in the same world with no lobby detour. Verify the round trip both ways.+3. **Spectate without leaving.** Shipped: while a war involving this coin is live the board becomes a scoreboard (score, round clock, kill feed) off the `?action=live` poll, text and numbers only, with the same numbers in the panel's spectator card.+4. **Results echo.** Partly shipped: the game server reports the result through `POST /api/wars?action=report`, `war-result` events go out through `multiplayer/src/feed.js`, and a win holds a 9 s takeover on the board (`HYPE_MS`). Still open: a jumbotron moment on the chart screen, and a ticker row if Feature 15 lands.+5. **Honest empty states.** Shipped for the unranked community, the empty battle log, the unreachable ledger, and the empty kill feed (each says what it is and what to do, e.g. "No wars fought yet. Press E to queue this community, the arena opens as soon as a second one does."). Verify each still renders in the designed style of the lobby's retry cards.## Verifydiff --git a/docs/event-readiness/19-forge-props-live.md b/docs/event-readiness/19-forge-props-live.mdindex 44157545a..d350c6f04 100644--- a/docs/event-readiness/19-forge-props-live.md+++ b/docs/event-readiness/19-forge-props-live.md@@ -1,22 +1,22 @@# Feature 19: forge 3D props live inside build mode-The platform's headline capability is text to 3D, and the world's build mode cannot use it. The prop palette pulls only the public avatar gallery, so building means placing other people's uploads. Wire the Forge lane into build mode: type a prompt, watch the object appear where you pointed, and everyone in the world sees it. At a live event this is the demo moment.+The platform's headline capability is text to 3D, and the world's build mode can now use it: the prop palette has a Forge form (and chat takes `/forge <prompt>`), `src/game/forge-prop.js` drives the free draft lane, and the finished GLB rides the uploaded-prop pipeline so everyone in the world sees it and the room persists it ([docs/play-forge-in-world.md](../play-forge-in-world.md)). What shipped is the pipeline; what is still open is the placement-first hologram, the size ceiling, and the server-side abuse limits below. At a live event this is the demo moment, and the size ceiling is what keeps it from becoming the iOS crash.## Where the code lives-- Forge lane: `api/forge.js` and siblings (`api/forge-gameready.js`, `api/forge-remesh.js`, `api/forge-rig.js`); client precedents in `src/forge.js` / `src/forge-studio/`. Use the platform's free text-to-3D lane and its existing rate limits; do not add a new paid dependency+- Forge lane: `api/forge.js` (`POST /api/forge` submits, `GET /api/forge?job=` polls, `POST /api/forge?action=rig` auto-rigs; there is no separate rig handler) and siblings (`api/forge-gameready.js`, which now also accepts a settled forge purchase and echoes only its own payment error codes, and `api/forge-remesh.js`); in-world client `src/game/forge-prop.js` (submit, poll every 2.5 s, up to 6 minutes for a cold GPU start, reference photos via `/api/forge-upload` capped at 8 MB, keyed to the same `forge:cid` handle the /forge page uses so in-world forges land in the same history); page precedents in `src/forge.js` / `src/forge-studio/`. Use the platform's free text-to-3D lane and its existing rate limits; do not add a new paid dependency- Prop plumbing (already networked and persistent): `src/game/world-objects.js` (`registerUploadedProp`, mirrors the server `objects` MapSchema), `src/game/avatar-upload.js` (`uploadPropModel`, presigned upload), the `_uploadProp` flow in `src/game/coincommunities.js`, persistence via `src/game/world-persist.js`-- Prop palette UI: the props panel in `src/game/coincommunities-ui.js` (currently fetching `/api/avatars/public`), styles in `src/game/coincommunities.css`+- Prop palette UI: the props panel in `src/game/coincommunities-ui.js` (the gallery tab still fetches `/api/avatars/public`; the Forge form is `forgeBtn` / `toggleForge()` reporting through the shared status strip, and the game side is `_forgeProp` in `src/game/coincommunities.js`), styles in `src/game/coincommunities.css`- The mobile lesson: `src/game/ambient-crowd.js` documents how uncapped user models killed iOS tabs, and its `CROWD_BUDGET` tiers are the sizing precedent- Generation ground truth when debugging: the `forge_creations` table carries per-generation backend, status, error, and prompt## What to build-1. **A Forge tab in the prop palette.** Prompt field, generate button, and a short history of this session's generations. Guidance text sets expectations honestly (real generation takes real time; say roughly how long from observed lane behavior, not a made-up number).-2. **Placement-first flow.** The player aims and places a hologram placeholder immediately (ghost shell in the build style, clearly "generating", using the real async state, never a fake progress bar). When the GLB lands, it swaps in place with a brief materialize effect. On failure the hologram becomes a designed error marker with retry and dismiss.-3. **The full prop pipeline, not a side door.** The finished GLB goes through `uploadPropModel` and `registerUploadedProp` so it is networked to every player, persists through `world-persist.js`, respects the per-player build budget, and is undoable with the existing Ctrl+Z stack.-4. **Size discipline.** Run generations through the gameready/remesh path so what enters the world is capped: enforce a hard triangle and file-size ceiling in the spirit of `CROWD_BUDGET` before a model is ever registered. An oversized result is decimated or rejected with a clear message, never placed raw. This is the difference between a demo moment and a repeat of the iOS crash.-5. **Abuse limits.** Per-player generation cooldown and a per-world concurrent-generation cap, enforced server-side on the endpoint, with the client showing queue position honestly.+1. **A Forge tab in the prop palette.** Shipped as the Forge form in the props panel (prompt or reference photo, one forge at a time, progress in the status strip) plus the `/forge <prompt>` chat command, which opens build mode with the result armed. Still open: a short history of this session's generations, and guidance text that sets expectations honestly (the lane comment says draft-tier generations land in about 30 to 60 s; quote observed behavior, not a made-up number).+2. **Placement-first flow.** Still open. Today the prop is armed as a ghost only after the GLB lands and the next click places it. Build the other order: the player aims and places a hologram placeholder immediately (ghost shell in the build style, clearly "generating", using the real async state, never a fake progress bar). When the GLB lands, it swaps in place with a brief materialize effect. On failure the hologram becomes a designed error marker with retry and dismiss.+3. **The full prop pipeline, not a side door.** Shipped: `_forgeProp` hands the finished GLB to `registerUploadedProp` and the normal `obj:spawn` placement, so it is networked to every player, persists like any other build, respects the per-player build budget, and is undoable with the existing Ctrl+Z stack. Verify a result that comes back with `durable: false` (temporary storage the server's asset allow-list may refuse) surfaces its warning and never leaves a phantom in the palette.+4. **Size discipline.** Still open, and the one that matters most. `forge-prop.js` enforces no triangle or file-size ceiling and never routes through the gameready/remesh path. Run generations through it so what enters the world is capped: enforce a hard triangle and file-size ceiling in the spirit of `CROWD_BUDGET` before a model is ever registered. An oversized result is decimated or rejected with a clear message, never placed raw. This is the difference between a demo moment and a repeat of the iOS crash.+5. **Abuse limits.** Still open beyond the lane's own rate limits and the client's one-forge-at-a-time guard. Per-player generation cooldown and a per-world concurrent-generation cap, enforced server-side on the endpoint, with the client showing queue position honestly.## Verifydiff --git a/docs/event-readiness/20-world-chat-scrollback.md b/docs/event-readiness/20-world-chat-scrollback.mdindex 8af8901ff..c9bc1e76d 100644--- a/docs/event-readiness/20-world-chat-scrollback.md+++ b/docs/event-readiness/20-world-chat-scrollback.md@@ -5,10 +5,10 @@ In-world chat is a pure relay: the server broadcasts and forgets, so everyone wh## Where the code lives- The relay today: the chat handler in `multiplayer/src/rooms/WalkRoom.js` (700ms cooldown and slur gate already enforced there; keep both)-- Persisted community chat (separate system): `api/community/messages.js`-- Chat UI: the chat bar and message list in `src/game/coincommunities-ui.js`, styles in `src/game/coincommunities.css`-- Name safety: `multiplayer/src/display-name-safety.js`-- Storage precedents: Upstash Redis usage in `api/play/builds.js` and `multiplayer/src/social-hub.js`+- Persisted community chat (separate system): `api/community/messages.js` (public GET; POST as the signed-in user now refreshes the 1 h access token off the refresh cookie first via `withAuthRefresh`, and a genuinely dead session answers `401 auth_required` rather than the `posting_locked` the composer renders as "this world does not take posts"; a bridge that writes in-world chat into this stream inherits that contract)+- Chat UI: the chat bar and message list in `src/game/coincommunities-ui.js` (it already sticks to the bottom only when the reader is near it, so a history tail must not fight that), styles in `src/game/coincommunities.css`+- Name safety: `multiplayer/src/display-name-safety.js` (`containsHateSlur`, applied to names on join and to every chat line in the relay)+- Storage precedents: Upstash Redis usage behind `api/play/builds.js` (`api/_lib/builds-store.js`) and in `multiplayer/src/social-hub.js`## What to builddiff --git a/docs/event-readiness/22-venue-projector-mode.md b/docs/event-readiness/22-venue-projector-mode.mdindex 316a3f5ae..c7fcfe79a 100644--- a/docs/event-readiness/22-venue-projector-mode.md+++ b/docs/event-readiness/22-venue-projector-mode.md@@ -4,11 +4,11 @@ Tomorrow there is a physical room with a big screen. The best thing that screen## Where the code lives-- URL params: parsing in `src/game/coincommunities.js` and the canonicalisation allowlist where entry rewrites the URL via `history.replaceState`. Any new param MUST be added to that allowlist or it is dropped on entry: this is the known trap-- Cameras: `src/game/camera-modes.js` (cinematic mode exists) and `src/game/hud/camera-rig.js`+- URL params: parsing in `src/game/coincommunities.js` and the canonicalisation in `enter()`, where the `history.replaceState` rewrite rebuilds the query from scratch with exactly `coin`, `name`, `symbol`, `image`, `tier` (holders worlds) and `ui`. Any new param MUST be added there or it is dropped on entry: this is the known trap+- Cameras: `src/game/camera-modes.js` (cinematic mode exists) and `src/game/hud/camera-rig.js` (it now honors `prefers-reduced-motion`, suppressing shake and the speed FOV kick; the director rotation must respect the same switch, since a venue machine may have it set)- Zen and embed precedents: `ui=hidden` and `bg=transparent` handling in `src/game/coincommunities.js`-- Server join: `multiplayer/src/rooms/WalkRoom.js` join options; the client sends them from `src/game/community-net.js`-- Event state: `public/event.json` via `src/game/event-countdown.js`; live activity if Feature 15 landed; invite QR if Feature 16 landed+- Server join: `multiplayer/src/rooms/WalkRoom.js` join options (there is no `spectator` option yet; every join spawns a visible player); the client sends them from `src/game/community-net.js`+- Event state: `public/event.json` via `src/game/event-countdown.js` and the shared `src/shared/event-config.js` reader (between events the file holds an explicit no-event state, `id: null`, which must render as the no-event overlay, not as an error); the go-live moments in `src/game/meetup-event.js` and `fireworks.js` are the shots worth cutting to; live activity if Feature 15 lands; invite QR if Feature 16 lands (`qrcode` is already a dependency)## What to builddiff --git a/docs/event-readiness/23-signature-wall.md b/docs/event-readiness/23-signature-wall.mdindex 06e20763f..6915dbc9f 100644--- a/docs/event-readiness/23-signature-wall.md+++ b/docs/event-readiness/23-signature-wall.md@@ -4,8 +4,8 @@ Events end; walls remember. Give the $THREE world a signature wall near spawn wh## Where the code lives-- Persistence precedents: `src/game/world-persist.js` (Postgres index plus blob store for builds), Upstash Redis in `api/play/builds.js`; pick the store that fits an append-only list of small records and state why-- Canvas-rendered world screens: `src/game/screen-texture.js` (shared quality pattern), `src/game/chart-screen.js` and `src/game/x402-jumbotron.js` as CanvasTexture precedents+- Persistence precedents: the per-world build doc behind `src/game/world-persist.js` (`api/world/[action].js` over `api/_lib/world-store.js`: a Postgres `world_docs` index row is always the source of truth, large docs offload to an R2 blob, and writes carry an etag with 409 on conflict; the browser only writes when no `walk_world` room is authoritative), Upstash Redis behind `api/play/builds.js` (`api/_lib/builds-store.js`); pick the store that fits an append-only list of small records and state why+- Canvas-rendered world screens: `src/game/screen-texture.js` (shared quality pattern), `src/game/chart-screen.js`, `src/game/x402-jumbotron.js` and the marquee in `src/game/plaza-stage.js` as CanvasTexture precedents; the war portal's board in `src/game/war-portal.js` is the precedent for a screen that fetches nothing until a player is within reading range- Interaction and placement: landmark precedent in `src/game/wheel-station.js`; the contextual F interaction chain in `src/game/coincommunities.js`- Safety: the slur gate in `multiplayer/src/rooms/WalkRoom.js` and `multiplayer/src/display-name-safety.js` (reuse the same filters server-side on the write path)- Identity: the play pass from `src/game/play-auth.js` distinguishes signed-in wallets from guestsdiff --git a/docs/farcaster-memory-seeding.md b/docs/farcaster-memory-seeding.mdindex a357309d8..f499baad9 100644--- a/docs/farcaster-memory-seeding.md+++ b/docs/farcaster-memory-seeding.md@@ -98,10 +98,16 @@ Two rungs, tried in order:1. **Neynar** (`@neynar/nodejs-sdk`, MIT) when `NEYNAR_API_KEY` is set. Indexeddata, so casts carry reaction counts and profiles carry follower counts. Thatis what makes engagement ranking possible.-2. **A public Farcaster hub over its HTTP API, keyless.** Default- `https://hub.pinata.cloud`, override with `FARCASTER_HUB_URL`. Serves raw- protocol messages, so there are no reaction counts, but it needs no vendor- key and does not go dark when a billing plan lapses.+2. **Public Farcaster hubs over their HTTP API, keyless.** Every hub serves+ the same replicated set, so the lane walks a list rather than pinning one+ host: `FARCASTER_HUB_URL` (if set) first, then any comma-separated+ `FARCASTER_HUB_URLS`, then the built-in defaults (`https://hub.pinata.cloud`,+ `https://hub.farcaster.standardcrypto.vc:2281`,+ `https://nemes.farcaster.xyz:2281`). An unreachable hub or a non-2xx answer+ moves to the next rung; a "no such user" answer ends the walk immediately,+ because that is the network's verdict, not one hub's. Hubs serve raw+ protocol messages, so there are no reaction counts, but they need no vendor+ key and do not go dark when a billing plan lapses.Neither key is required for the feature to work. The SDK is imported lazily andonly when a key is configured, so the keyless lane carries no dependency on thediff --git a/docs/first-contribution.md b/docs/first-contribution.mdindex fad0eb286..a77451720 100644--- a/docs/first-contribution.md+++ b/docs/first-contribution.md@@ -18,7 +18,7 @@ npm run devOpen http://localhost:3000. You should see a 3D avatar you can orbit with the mouse.-`npm run setup` is not optional and not the same as `npm install`. It builds the local `solana-agent-sdk` (linked as a `file:` dependency with no prebuilt `dist/`) and generates the gitignored `data/_generated/*` artifacts that the app, the sitemap, and the test suite read. It is idempotent, so re-running it is always safe.+`npm run setup` is not optional and not the same as `npm install`. It builds the local `solana-agent-sdk` (linked as a `file:` dependency with no prebuilt `dist/`), generates the gitignored `data/_generated/*` artifacts that the app, the sitemap, and the test suite read, and installs the repo's pre-push hook into `.git/hooks` (the same one `npm install` sets up through `scripts/setup-git-hooks.mjs`). That hook lints the commits you push against the rules in section 4, so a rejected push is the hook doing its job, not a broken setup. It is idempotent, so re-running it is always safe.You do **not** need any API keys, a wallet, or a database to work on the rendering, rigging, animation, or docs layers. Those layers are pure client-side JavaScript and their tests run offline.diff --git a/docs/forge-background-generation.md b/docs/forge-background-generation.mdindex ff4da317d..7c249f3fe 100644--- a/docs/forge-background-generation.md+++ b/docs/forge-background-generation.md@@ -45,22 +45,30 @@ Three cooperating pieces:past the attended polling window (13 minutes, so a live browser's ownfailover is never raced) is redispatched unattended to the next healthylane under the same hop cap as the attended path, and an expired NVCF- request is resubmitted from the inputs stored on the row. Only a job with- nothing left to try is marked failed. Anything non-terminal after 45- minutes is marked failed as timed out, so no row can be orphaned at- `generating` again.+ request is resubmitted from the inputs stored on the row. A redispatched+ attempt is linked to its successor row (`forge_creations.superseded_by`,+ migration `20260814200000_forge_failover_supersede.sql`), so the outcome+ ledger records a recovery rather than a loss. Only a job with nothing left+ to try is marked failed, and the finalizer logs that it declined the+ failover (every alternative lane already attempted or cooling) rather than+ failing silently. Anything non-terminal after 45 minutes is marked failed+ as timed out, so no row can be orphaned at `generating` again.3. **Notifications** ([api/_lib/forge-notify.js](../api/_lib/forge-notify.js)):the finalizer, and only the finalizer, notifies. `forge_complete` and`forge_failed` are standard notification types in the `creations`- preference category (defaults: in-app on, push on, email on for- completions). Email delivery uses the platform Resend pipeline and skips- undeliverable placeholder addresses.+ preference category (defaults: in-app, push, email and the on-page+ companion avatar on; Telegram off; email only for completions). The+ `avatar` channel is delivered client-side by the corner companion+ (`src/notification-herald.js`), which walks on and says it out loud while+ the user is on the site; it can be muted per browser from its bubble.+ Email delivery uses the platform Resend pipeline and skips undeliverable+ placeholder addresses.## Self-host poll recovery (the "task not found" grace)A self-host worker poll (`/tasks/:id` or `/jobs/:id`) can 404 when the durable-task record is not yet visible to the instance the poll load-balanced to — the+task record is not yet visible to the instance the poll load-balanced to: thebrief post-submit cross-instance window (workers run at high concurrency with nosession affinity), or a completion write racing the poll. The worker persistseach task's `queued` state to GCS before returning its 202 and re-reads GCS for@@ -73,33 +81,36 @@ recoverable signal): the GCP provider tags a 404 with `code: 'gcp_task_missing'`([api/_providers/gcp.js](../api/_providers/gcp.js)) and the poll handler runs apure decision ([api/_lib/forge-selfhost-recovery.js](../api/_lib/forge-selfhost-recovery.js)):-1. **Store re-check** — if the creation row already materialized (`done` + a+1. **Store re-check**: if the creation row already materialized (`done` + aglb), a racing poll or the completion write beat us; resolve as complete.-2. **Grace window** — a job younger than `GCP_TASK_MISSING_GRACE_MS` (90s)+2. **Grace window**: a job younger than `GCP_TASK_MISSING_GRACE_MS` (90s)reports `running` so the client keeps polling; the durable record resolveswithin seconds.-3. **Terminal** — past the window a still-missing task is genuinely orphaned;+3. **Terminal**: past the window a still-missing task is genuinely orphaned;the failure surfaces and the existing lane failover redispatches to a healthy- lane. Nothing here disables failover — it just stops firing it on transient+ lane. Nothing here disables failover, it just stops firing it on transient404s.## Generation success-rate healthLane liveness ("can a worker serve right now?") is not the same as outcomehealth ("are generations succeeding?"). A warm lane can still fail half its-jobs — the 404 burst above ran ~48% failure for days while every liveness probe+jobs: the 404 burst above ran ~48% failure for days while every liveness proberead healthy. The **Forge 3D generation** subsystem([api/_lib/ops/forge-health-sensor.js](../api/_lib/ops/forge-health-sensor.js))closes that: it reads `forge_creations` outcomes over a 6h window and reports the-success rate (`done / (done + failed)`; running/queued excluded), naming the+success rate (`done / (done + failed)`; running/queued excluded, and so are+attempts that were re-dispatched to another lane, `superseded_by` set, so the+failover machinery working is never counted as loss), naming theworst backend/path and top error class so a page is actionable. It rolls into`/api/healthz`, `/status`, and the uptime-cron escalation. States: `ok` ≥ 85%,-`degraded` 60–85%, `down` < 60%, `unknown` below 15 finished generations+`degraded` 60 to 85%, `down` < 60%, `unknown` below 15 finished generationsin-window. This is the forge twin of the x402 settlement-success sensor.## Operational notes-- The finalizer needs `CRON_SECRET` (standard cron auth), `DATABASE_URL`, the+- The finalizer needs `CRON_SECRET` (the shared fail-closed cron gate,+ `api/_lib/cron-auth.js`), `DATABASE_URL`, theR2 `S3_*` storage vars, and `GCP_RECONSTRUCTION_KEY` to poll workers. Withno worker key it still reaps timed-out rows.- Batch size is 25 per tick (`FORGE_FINALIZE_BATCH` overrides). Ticks arediff --git a/docs/forge-off.md b/docs/forge-off.mdindex 37c7ed179..4b477506d 100644--- a/docs/forge-off.md+++ b/docs/forge-off.md@@ -15,15 +15,15 @@ strip without an account.On the "Fresh from the Forge" section of [/forge](/forge):-- **Upvote** — each card has an upvote pill (chevron + count). Tap it to vote,+- **Upvote**: each card has an upvote pill (chevron + count). Tap it to vote,tap again to remove your vote. The count is the whole community's; the filledstate is only yours. The button is optimistic and reconciles against theserver tally, so a double-tap or a slow network never leaves it wrong.-- **Fresh / Top this week** — a toggle in the section header. *Fresh* is the+- **Fresh / Top this week**: a toggle in the section header. *Fresh* is thehistorical newest-first, visual-first strip. *Top this week* is the Forge-Offboard: the most-voted public models created during the current Forge-Off week(Monday→Monday UTC), highest first.-- **The weekly winner** — every Monday the top-voted model of the week just+- **The weekly winner**: every Monday the top-voted model of the week justended is crowned permanently. Later votes never rewrite a past week's winner.The same strip and voting appear on the signed-in [/forge-studio](/forge-studio)@@ -52,7 +52,7 @@ Response:never a drifting counter).- `voted` is *your* state after the call.- Voting is idempotent: a second upvote from the same browser is a no-op.-- A missing or shared (`anon`) client id is rejected `400 no_client_id` — a real+- A missing or shared (`anon`) client id is rejected `400 no_client_id`: a realvote needs a real, unique voter so the tally means something.- Votes are only accepted on public, finished, non-rejected creations. Anythingelse returns `404 not_votable`.@@ -65,14 +65,19 @@ already caps real influence; this just blunts carpet-voting).```GET /api/forge-gallery?scope=community&sort=top&window=week&limit=24-x-forge-client: <stable browser id> # optional — resolves your `voted` flags+x-forge-client: <stable browser id> # optional, resolves your `voted` flags```-- `sort=fresh` (default) — newest, visual-first.-- `sort=top` — ranked by `vote_count` desc, `created_at` desc.-- `window=week` — with `sort=top`, narrow to the current Forge-Off week.+- `sort=fresh` (default): newest, visual-first.+- `sort=top`: ranked by `vote_count` desc, `created_at` desc.+- `window=week`: with `sort=top`, narrow to the current Forge-Off week.- Each returned creation carries `vote_count` and, when a client id is sent,- `voted`. An anonymous read is CDN-cacheable; a voter-aware read is `private`.+ `voted`. An anonymous read is CDN-cacheable; a voter-aware read is `private`,+ and the response varies on `x-forge-client`, so the edge never hands the+ anonymous copy to a browser that sent a client id.+- The read is CORS-open to any origin: it is the same public catalogue the+ standalone AR studio (npm: `3d-ar-studio`) shows as its Community tab from+ whatever page embeds it. Rate limiting is the control, not the origin.## How it fits together@@ -99,12 +104,17 @@ that pipeline's strongest tier was starved; voting + the weekly crown feed it.| Piece | Where ||---|---|-| Vote / board store logic | [api/_lib/forge-store.js](../api/_lib/forge-store.js) — `castVote`, `removeVote`, `listShowcase` (sort/window/voter), `forgeOffWeekStart` |+| Vote / board store logic | [api/_lib/forge-store.js](../api/_lib/forge-store.js): `castVote`, `removeVote`, `listShowcase` (sort/window/voter), `forgeOffWeekStart` || Vote endpoint | [api/forge-vote.js](../api/forge-vote.js) || Board read | [api/forge-gallery.js](../api/forge-gallery.js) (`scope=community`) || Weekly crowning cron | [api/cron/forge-off-crown.js](../api/cron/forge-off-crown.js) (`7 0 * * 1`) || UI (vote button, Fresh/Top toggle) | [src/forge-showcase.js](../src/forge-showcase.js) and its `/forge-studio` twin [src/forge-studio/forge-showcase.js](../src/forge-studio/forge-showcase.js) |-| Schema | [migration 20260625120000_forge_board.sql](../api/_lib/migrations/20260625120000_forge_board.sql) — `forge_votes`, `forge_creations.vote_count`, `forge_board_winners` |+| Schema | [migration 20260625120000_forge_board.sql](../api/_lib/migrations/20260625120000_forge_board.sql): `forge_votes`, `forge_creations.vote_count`, `forge_board_winners` |++A creator deleting their own creation (`DELETE /api/forge-creation?id=`, the+two-tap delete on a "Your creations" card) takes its `forge_votes` rows with+it; a past week's `forge_board_winners` row survives with its creation+reference cleared, so the hall of fame never loses a week.Backfill a past week's winner (owner): `GET /api/cron/forge-off-crown?week=YYYY-MM-DD`(add `&dry_run=1` to preview). Authorized with `CRON_SECRET`.diff --git a/docs/forge-pipeline.md b/docs/forge-pipeline.mdindex be660982a..13c912a39 100644--- a/docs/forge-pipeline.md+++ b/docs/forge-pipeline.md@@ -59,7 +59,7 @@ Three properties define the design:| Flagship free API | `POST /api/v1/ai/text-to-3d` (`api/v1/ai/text-to-3d.js`) | NVIDIA NIM TRELLIS draft lane, 10 generations per IP per day, 429 + x402 upsell above quota. || Refinement | `POST /api/forge-iterate` (`api/forge-iterate.js`) | Conversational refinement with version lineage for the signed-in Studio. || MCP (paid stdio) | `mesh_forge`, `forge_avatar`, `forge_free`, `text_to_avatar`, `rig_mesh`, `refine_model`, `restyle_material` (`mcp-server/src/tools/`) | Shared cores in `mcp-server/src/tools/_studio-core.js`; thin clients over `/api/forge`. |-| ChatGPT clone | `POST /api/gpt-forge` (`api/gpt-forge.js`) | Clone of the orchestrator dedicated to the ChatGPT surfaces (the Apps SDK MCP connector `api/mcp-studio` and the custom-GPT Actions endpoint `api/3d/studio`, via `api/_mcp-studio/gpt-forge-client.js`), so the ChatGPT pipeline can evolve without touching `/api/forge`. Same lanes, tiers, job tokens, and `forge_creations` rows. First divergence: its poll responses also carry `prompt`, `preview_image_url` (the painted concept view), and `text_to_image_model`, so the ChatGPT surfaces can show the concept image while the mesh generates. |+| ChatGPT clone | `POST /api/gpt-forge` (`api/gpt-forge.js`) | Clone of the orchestrator dedicated to the ChatGPT surfaces (the Apps SDK MCP connector `api/mcp-studio` and the custom-GPT Actions endpoint `api/3d/studio`, via `api/_mcp-studio/gpt-forge-client.js`), so the ChatGPT pipeline can evolve without touching `/api/forge`. Same lanes, tiers, job tokens, and `forge_creations` rows. First divergence: its poll responses also carry `prompt`, `preview_image_url` (the painted concept view), and `text_to_image_model`, so the ChatGPT surfaces can show the concept image while the mesh generates. It also remembers a finished job's poll frame (`api/_lib/forge-done-cache.js`), so later polls of a done job answer in milliseconds without re-reading the provider. || MCP (hosted HTTP) | `text_to_3d`, `image_to_3d`, `auto_rig_model`, plus the wider studio toolset (`generation_status`, `preview_3d`, `remove_background`, `remesh_model`, `stylize_model`, `segment_model`, `retexture_model`, `pose_model`, `save_avatar`, persona tools; `api/mcp-3d.js`, tools in `api/_mcp3d/tools/studio.js`) | Streamable HTTP server registered as `io.github.nirholas/three-ws-3d-studio`. || DCC plugins | `integrations/blender/`, `integrations/comfyui/`, `integrations/_pyclient/` | First-party clients driving the same API. |@@ -133,6 +133,8 @@ Routing answers one question: given `(path, tier, userImages, prompt)`, which co**Submit-time failover.** If a lane rejects the submit outright (down, quota, cooldown), `startJob` walks the free-first chain to the next candidate in the same request. The client never sees the rejected lane.+**Reference-image budget.** On the text path the reference-image step (the Vertex lane in `api/_lib/forge-reference-image.js`, its QA score and corrective retry, and the `textToImage` fallthrough ladder, Livepeer included) runs under one shared budget, `TEXT_TO_IMAGE_BUDGET_MS` (default 60 s). A stalled paint provider can no longer hold a submit open for minutes before a job exists; once the budget is spent the caller gets a fast, retryable failure instead.+### The job handleAsync jobs get an opaque HMAC-signed token (`f1.<payload>.<sig>`, `api/_lib/forge-job-token.js`) that records provider, kind, and upstream task id, signed with `JWT_SECRET`. The legacy Replicate path keeps the bare prediction id. Tokens make the poll endpoint stateless: any instance can decode the handle and ask the right upstream.@@ -141,7 +143,7 @@ Async jobs get an opaque HMAC-signed token (`f1.<payload>.<sig>`, `api/_lib/forg`GET /api/forge?job=<id>` returns `status`: `queued`, `running`, `done` (with `glb_url`, `viewer_url`, and the `path`/`tier`/`backend` that actually produced it), or `failed`. Polling is free and unauthenticated. The in-flight job id is also written to `localStorage`, so an interrupted browser session resumes polling for up to 30 minutes; background completion persists the result to the user's gallery either way (see [Background generation](./forge-background-generation.md)).-**Poll-time failover** (`api/_lib/forge-failover.js`) closes the nastier gap: a self-host worker can accept a task and fail it minutes later, in a poll handled by a different instance that no longer holds the request. On a failed poll the module recovers the original inputs (prompt plus reference image) from the creation row, resubmits to the next configured lane, and binds old handle to new handle in Redis (2 hour TTL). The client keeps polling the same job id and simply sees `status: running` with a new `backend`. Hops are capped by `MAX_FAILOVER_HOPS = 3` (one primary plus up to three backups). The redispatch order is `trellis_selfhost`, `hunyuan3d`, `trellis`: HuggingFace is excluded because its provider blocks through the whole generation (cannot be ridden from a poll), and NVIDIA is excluded because poll-time redispatch always reconstructs from a stored reference image, which NIM rejects.+**Poll-time failover** (`api/_lib/forge-failover.js`) closes the nastier gap: a self-host worker can accept a task and fail it minutes later, in a poll handled by a different instance that no longer holds the request. On a failed poll the module recovers the original inputs (prompt plus reference image) from the creation row, resubmits to the next configured lane, and binds old handle to new handle in Redis (2 hour TTL). The client keeps polling the same job id and simply sees `status: running` with a new `backend`. Hops are capped by `MAX_FAILOVER_HOPS = 3` (one primary plus up to three backups). The redispatch order is `trellis_selfhost`, `hunyuan3d`, `trellis`: HuggingFace is excluded because its provider blocks through the whole generation (cannot be ridden from a poll), and NVIDIA is excluded because poll-time redispatch always reconstructs from a stored reference image, which NIM rejects. Both failover paths (this attended one and the unattended finalizer sweep) link the failed attempt to its successor row (`forge_creations.superseded_by`, migration `20260814200000_forge_failover_supersede.sql`), so the outcome ledger, the forge health sensor and `npm run forge:errors` count a recovered attempt as a recovery, not a loss.**Designed terminal failure.** When no successor is possible, the failed response carries `retryable: true` plus `retry_backends: [...]`, the ordered configured lanes a client can one-click resubmit to. A failure is never a bare string. The whole module is fail-open: no Redis disables automatic redispatch but keeps suggestions; no DB disables recovery but never turns a clean failure into a hang.@@ -149,7 +151,7 @@ Async jobs get an opaque HMAC-signed token (`f1.<payload>.<sig>`, `api/_lib/forg- **Quality gate + best-of retry.** `scoreQualityGate` flags degenerate results (near-empty geometry, texture failures); synchronous lanes retry once inline before returning.- **Result cache** (`api/_lib/forge-cache.js`). Identical text prompts on platform-keyed non-high lanes are served from cache with `cached: true`. The key covers path, tier, backend, the normalized prompt, and the output-affecting options (seed included), with a 7-day TTL that a read never refreshes. `force_regenerate: true` in the request body skips the cache READ while still writing the fresh result back. Any caller that must prove the pipeline is alive rather than that a mesh exists has to send it: the daily smoke cron (`api/cron/forge-smoke.js`) submits a constant prompt with no seed, so without the flag its key never changes and it verifies a replay. Automation that seeds the gallery takes the other route and varies the seed per submit (`api/cron/forge-seed-cron.js`), so a repeated prompt yields a genuinely new asset instead of a second catalog entry pointing at one GLB.-- **Scale controls** (`api/_lib/forge-scale.js`). In-flight coalescing, blocking-lane slots, and daily paid caps keep a traffic spike from stampeding the GPU fleet or the paid last resort.+- **Scale controls** (`api/_lib/forge-scale.js`). In-flight coalescing, blocking-lane slots, and daily paid caps keep a traffic spike from stampeding the GPU fleet or the paid last resort. Its circuit breaker (`circuitRecordFailure`) widens the open window linearly per consecutive failure but caps it at one hour (`CIRCUIT_MAX_OPEN_MS`), so a provider outage parks the seed cron for at most an hour before it re-probes the lane.## 6. Persistence and storage@@ -162,8 +164,9 @@ Async jobs get an opaque HMAC-signed token (`f1.<payload>.<sig>`, `api/_lib/forg- Feedback flywheel: `outcome` (`generated`, `accepted`, `rejected`), `rating`, `note`, `downloaded`, `feedback_at`. The outcome partial index feeds training-signal export.- Lineage and remix (migration `20260625000000_forge_refine_lineage.sql`): `parent_creation_id`, `refine_instruction`, `lineage_index`, `remixable`, `remix_royalty_bps` (0 to 2000, default 1000), `creator_wallet_solana`, `remix_settlement_ref`.- Forge-Off (migration `20260625120000_forge_board.sql`): `vote_count`, plus the `forge_votes` and `forge_board_winners` tables.+- Failover and cleanup: `superseded_by` (migration `20260814200000_forge_failover_supersede.sql`, the successor row's id when this attempt was re-dispatched; a plain uuid, not a foreign key, so retention pruning stays free) and `source_image_keys` (migration `20260813160000_forge_source_image_keys.sql`, the storage key of every uploaded reference photo, so a delete can erase them).-`api/_lib/forge-store.js` owns all writes: `createCreation` on submit (also records the funnel `start` event), `materializeCreation` on completion, `markFailed`, and verdict capture. It is fail-soft: without a DB or storage config it no-ops rather than blocking generation.+`api/_lib/forge-store.js` owns all writes: `createCreation` on submit (also records the funnel `start` event), `materializeCreation` on completion, `markFailed`, `markSupersededBy` when a failed attempt is re-dispatched, verdict capture, and `deleteCreation` (behind `DELETE /api/forge-creation?id=`), which removes the mesh, preview and source uploads from storage before the row and is scoped to the owning client key. It is fail-soft: without a DB or storage config it no-ops rather than blocking generation.**Storage is two-layer.** GPU workers write raw output to GCS (`gs://$GCS_BUCKET/raw-meshes/...`), and provider URLs generally expire within about an hour. `materializeCreation` therefore mirrors the mesh and reference image into Cloudflare R2 (`api/_lib/r2.js`) and stores the durable CDN URL in `glb_url`. Anything user-facing must reference the R2 URL, never the raw provider URL.@@ -186,7 +189,7 @@ Model weights are staged from `gs://three-ws-model-weights` via `workers/deploy/## 8. Post-processing- **Rigging.** `POST /api/forge?action=rig` prefers the self-host rig worker and falls back to Replicate; unconfigured deployments return a clean 501. Auto-rig-on-create (`api/_lib/auto-rig.js`) mints a sibling creation row rather than mutating the original (provenance and attestation depend on the original bytes staying put), gated by the humanoid prompt classifier (`mcp-server/src/tools/_humanoid.js`) and `rigInfoIsRigged()` (already-skinned GLBs are skipped).-- **Skeleton canonicalization.** `src/glb-canonicalize.js` maps any humanoid rig's bone names (Mixamo, Avaturn, Unreal, VRM/VRoid, Daz, MakeHuman, Blender `.L`, and more) onto the canonical bone set, repacking the GLB in place. There is no rig allowlist; a new convention means a new bone-name mapping plus a test case in `tests/glb-canonicalize.test.js`.+- **Skeleton canonicalization.** `src/glb-canonicalize.js` maps any humanoid rig's bone names (Mixamo, Avaturn, Unreal, VRM/VRoid, Daz, MakeHuman, MMD/MikuMikuDance with its Japanese bone names, Blender `.L`, and more) onto the canonical bone set, repacking the GLB in place. There is no rig allowlist; a new convention means a new bone-name mapping plus a test case in `tests/glb-canonicalize.test.js`.- **Animation retargeting.** `src/animation-retarget.js` applies the pre-baked canonical clip library (`public/animations/clips/*.json`) to arbitrary rigs: rewrites track names, drops missing bones, rescales hip translation, and requires 50% bone coverage. Pure JS, shared between the browser and the Node MCP tool.- **Refinement lineage.** `api/forge-iterate.js` and the MCP `refine_model` tool share one core (`mcp-server/src/tools/_lineage.js`) for composing refinements and maintaining the revertable, branchable version tree over `parent_creation_id` and `lineage_index`.- **Restyle.** `api/material-studio.js` re-skins a GLB without regenerating the mesh: an LLM proposes PBR factors from an instruction, applied server-side. The paid MCP `restyle_material` is a thin client over it.diff --git a/docs/forged.md b/docs/forged.mdindex 8fc738169..9837aab5c 100644--- a/docs/forged.md+++ b/docs/forged.md@@ -30,7 +30,8 @@ The page ([pages/forged.html](../pages/forged.html), rendered byhappen client-side over the loaded feed.- **Designed empty, no-match, and error states.** The empty state explains thatthe autonomous loop pays the Forge for a new prop every hour; the error state- has a retry button.+ names the reason the load failed (the API's own message) and has a retry+ button.## Where the assets come fromdiff --git a/docs/free-llm-providers.md b/docs/free-llm-providers.mdindex c2cfef970..5c57aa0fe 100644--- a/docs/free-llm-providers.md+++ b/docs/free-llm-providers.md@@ -10,10 +10,10 @@ Free rungs run first, 70B-class models before smaller ones. A keyed rung is skip| # | Rung | Model | Key | Free tier ||---|------|-------|-----|-----------|-| 1 | Groq | `llama-3.3-70b-versatile` | `GROQ_API_KEY` | Per-minute and per-day caps, no card. [console.groq.com](https://console.groq.com) |+| 1 | Groq | `qwen/qwen3.8-27b` | `GROQ_API_KEY` | Per-minute and per-day caps, no card. Llama 3.x left Groq's catalog in August 2026; Qwen 3.8 27B is the fastest non-reasoning model left there. [console.groq.com](https://console.groq.com) || 2 | Cerebras | `llama-3.3-70b` | `CEREBRAS_API_KEY` | About 1M tokens/day. [cloud.cerebras.ai](https://cloud.cerebras.ai) || 3 | OpenRouter | `openai/gpt-oss-20b:free` | `OPENROUTER_API_KEY` (+ fallback keys) | `:free` models only; the platform key is never billed. [openrouter.ai](https://openrouter.ai) |-| 4 | NVIDIA NIM | `meta/llama-3.3-70b-instruct` | `NVIDIA_API_KEY` | Free developer tier, about 40 req/min. [build.nvidia.com](https://build.nvidia.com) |+| 4 | NVIDIA NIM | `nvidia/nemotron-3-super-120b-a12b` | `NVIDIA_API_KEY` | Free developer tier, about 40 req/min. `meta/llama-3.x` on NIM reached end of life on 2026-08-26 (HTTP 410); Nemotron 3 is a reasoning family, so the rung sends `enable_thinking: false` to keep the answer in `content`. [build.nvidia.com](https://build.nvidia.com) || 5 | SambaNova | `Meta-Llama-3.3-70B-Instruct` | `SAMBANOVA_API_KEY` | About 20 req/min, 200K tokens/day per model, no card. [cloud.sambanova.ai](https://cloud.sambanova.ai) || 6 | Mistral | `mistral-small-latest` | `MISTRAL_API_KEY` | Experiment tier: about 1B tokens/month at 1 req/sec (account opts into data training). [console.mistral.ai](https://console.mistral.ai) || 7 | Z.AI | `glm-4.7-flash` | `ZAI_API_KEY` | Permanently free, rate-limited Flash models. [z.ai](https://z.ai), docs at [docs.z.ai](https://docs.z.ai) |@@ -24,15 +24,15 @@ Free rungs run first, 70B-class models before smaller ones. A keyed rung is skip| 12 | Pollinations | `openai-fast` | none (keyless) | Anonymous, always on. || 13 | LLM7.io | `gemini-3.1-flash-lite` | none (keyless) | Anonymous, about 30 req/min per IP. || 14 | SiliconFlow | `Qwen/Qwen3-8B` | `SILICONFLOW_API_KEY` | Free-tier small model, own quota pool. [siliconflow.com](https://siliconflow.com) |-| 15 | Groq instant | `llama-3.1-8b-instant` | `GROQ_API_KEY` | Separate per-model quota from rung 1. |+| 15 | Groq instant | `openai/gpt-oss-20b` | `GROQ_API_KEY` | Separate per-model quota from rung 1. |After rung 15 come the paid backstops (Vertex Claude, Anthropic, OpenAI, Grok), which never lead and which no flow depends on.-The interactive chat ladder (`/api/chat`) uses: groq → openrouter → nvidia → sambanova → mistral → zai → paid backstops, with the Vertex Gemini anchor always appended at the tail. SambaNova, Mistral, and Z.AI are also selectable as explicit `provider` values in the chat API, and anonymous callers may use them.+The interactive chat ladder (`/api/chat`) uses: groq → openrouter → nvidia → sambanova → mistral → zai → paid backstops, with the Vertex Gemini anchor always appended at the tail. SambaNova, Mistral, and Z.AI are also selectable as explicit `provider` values in the chat API, and anonymous callers may use them. When every anonymous-eligible free lane is throttled or in cooldown at once, `/api/chat` answers `503 rate_limited` ("The AI chat is at capacity right now") with a `Retry-After: 20` header and the `providers_tried` list, never a 401 asking a signed-out visitor to sign in for a throttle they cannot fix.## Why so many-Every rung is an independent quota pool on independent infrastructure. Free tiers throttle, retire models without notice (OpenRouter dropped its whole `:free` Llama roster in one day, GitHub Models was retired outright in 2026), and queue under load (NVIDIA NIM). One provider failing costs nothing; the chain moves on in under a second. The platform's baseline reliability is the product of how many independent free lanes stand between a request and an error.+Every rung is an independent quota pool on independent infrastructure. Free tiers throttle, retire models without notice (OpenRouter dropped its whole `:free` Llama roster in one day, Groq and NVIDIA NIM both removed Llama 3.x in August 2026, GitHub Models was retired outright in 2026), and queue under load (NVIDIA NIM). One provider failing costs nothing; the chain moves on in under a second. The platform's baseline reliability is the product of how many independent free lanes stand between a request and an error.Two providers were evaluated and deliberately excluded:diff --git a/docs/galaxy.md b/docs/galaxy.mdindex 39d1c2df3..621285824 100644--- a/docs/galaxy.md+++ b/docs/galaxy.md@@ -14,12 +14,12 @@ A flat directory of agents tells you what exists but nothing about how they relaThe page ([`pages/galaxy.html`](../pages/galaxy.html)) loads [`src/galaxy.js`](../src/galaxy.js), a Three.js scene. The map itself is assembled server-side and cached.1. **Collect agents.** `GET /api/galaxy` ([`api/galaxy.js`](../api/galaxy.js)) loads published agents from Postgres (`agent_identities` joined to `avatars`, filtered to published, described, named agents, ordered by chat count), default 600 and capped at 1200.-2. **Embed.** Each agent's text (name, description, tone tags) is embedded with IBM Granite through [`api/_lib/watsonx.js`](../api/_lib/watsonx.js). The default model is `ibm/granite-embedding-278m-multilingual`, called at `POST {WATSONX_URL}/ml/v1/text/embeddings` with an IAM bearer token minted from the watsonx API key. Vectors are cached durably per agent (`agent_embeddings`), so only changed agents re-embed.+2. **Embed.** Each agent's text (name, description, tone tags) is embedded with IBM Granite through [`api/_lib/watsonx.js`](../api/_lib/watsonx.js). The default model is `ibm/granite-embedding-278m-multilingual`, called at `POST {WATSONX_URL}/ml/v1/text/embeddings` with an IAM bearer token minted from the watsonx API key (the IAM exchange is idempotent and gets three attempts at 10 s; an inference call gets one attempt with a 45 s deadline). Vectors are cached durably per agent (`agent_embeddings`), so only changed agents re-embed.3. **Project to 3D.** [`api/_lib/embedding-math.js`](../api/_lib/embedding-math.js) mean-centers the vectors, takes the top 3 principal components via power iteration (PCA, seeded and deterministic, not UMAP or t-SNE), whitens per axis, and maps them into a cube of half-width 120 world units. Determinism means cached rebuilds are stable.4. **Cluster into constellations.** Seeded k-means (Lloyd's with k-means++ seeding) over L2-normalized vectors groups agents into `clamp(round(n/8), 2, 8)` clusters. Each cluster is labeled by Granite chat (`ibm/granite-3-8b-instruct`, with a same-family OpenRouter fallback).5. **Render.** The client draws agents as a single `THREE.Points` cloud with a custom additive shader. Point size grows with chat count; a wealth glow (from real wallet net worth via `/api/agents/networth`) biases funded stars toward a violet tint. `OrbitControls` gives drag-to-orbit, scroll-to-zoom, and gentle auto-rotate that pauses on interaction. A raycaster powers hover tooltips.-6. **Inspect.** Clicking a star opens an in-scene card with the agent's thumbnail, constellation, description, and meta chips (net worth, chat count, token), plus two actions: "View agent" (`/agents/:id`) and "Chat" (`/agent/:id`).-7. **Search.** The search box POSTs `{ query }` to `/api/galaxy`, which embeds the query with the same Granite model and ranks stored agent vectors by cosine similarity. The client highlights matches and flies the camera to the best one.+6. **Inspect.** Clicking a star opens an in-scene card with the agent's thumbnail, constellation, description, and meta chips (net worth, chat count, token), plus two actions: "View agent" and "Chat", both on the canonical `/agents/:id` route.+7. **Search.** The search box POSTs `{ query }` to `/api/galaxy`, which embeds the query with the same Granite model and ranks stored agent vectors by cosine similarity (`ranking: "semantic"`). The client highlights matches and flies the camera to the best one. When the embedder cannot answer (unreachable, or no vector returned) there is deliberately no other embedding lane to fall back to, because the stored vectors live in Granite's space and a vector from another model would be compared in a different geometry; instead the same corpus is ranked lexically ([`api/_lib/lexical-rank.js`](../api/_lib/lexical-rank.js)) and the response says so with `ranking: "lexical"` and `degraded: { reason: "embedder_unavailable", detail, retryable: true }`, so a search still returns useful matches rather than a `502`.Only projected coordinates and cluster centroids are sent to the browser; raw high-dimensional vectors never leave the server.@@ -54,8 +54,12 @@ curl -X POST 'https://three.ws/api/galaxy' \# "query": "an agent that trades solana memecoins",# "model": "ibm/granite-embedding-278m-multilingual",# "count": 12,-# "results": [ { "id": "…", "name": "…", "description": "…", "thumbnail": "…", "score": 0.742 } ]+# "results": [ { "id": "…", "name": "…", "description": "…", "thumbnail": "…", "score": 0.742 } ],+# "ranking": "semantic"# }+# When Granite cannot embed the query the same call answers 200 with+# "ranking": "lexical", a "lexicalScore" per result, and+# "degraded": { "reason": "embedder_unavailable", "detail": "…", "retryable": true }.````GET /api/galaxy` accepts `?refresh=1` to force a rebuild and `?limit=<n>` (default 600, max 1200). `POST /api/galaxy` takes `{ query, limit? }` (query trimmed to 200 chars, up to 30 results). Rankings apply a minimum similarity of 0.05.@@ -63,7 +67,7 @@ curl -X POST 'https://three.ws/api/galaxy' \## States and limits- **No auth.** Both endpoints are public and read-only, guarded by a per-IP rate limit. Embedding cost is bounded by design: agents embed once into the durable cache and map builds are snapshot-cached, so only a search query triggers a fresh Granite call.-- **watsonx required.** With no credentials the endpoint returns `503 watsonx_unavailable` and the page shows "IBM Granite isn't connected" (no retry). Configure `WATSONX_API_KEY` and `WATSONX_PROJECT_ID` to light it up.+- **watsonx required.** With no credentials the endpoint returns `503 watsonx_unavailable` and the page shows "IBM Granite isn't connected" (no retry). Configure `WATSONX_API_KEY` and `WATSONX_PROJECT_ID` to light it up. With credentials present but Granite failing on a search, the query degrades to lexical ranking as described above instead of erroring.- **Caching.** Three layers: a `galaxy_snapshots` server snapshot (6-hour TTL, with warm-instance rebuild coalescing), the durable per-agent `agent_embeddings` cache, and a 60-second cache on the published-agent query. Pass `?refresh=1` to bypass the snapshot.- **Population.** However many published agents exist, capped by the limit. There is no fixed count.- **Empty state.** With zero published agents the page shows "The galaxy is still forming" and a "Create an agent" CTA to `/create`.diff --git a/docs/genome.md b/docs/genome.mdindex 3e9814737..5a1ee5246 100644--- a/docs/genome.md+++ b/docs/genome.md@@ -35,6 +35,9 @@ parents and the same seed it always derives the identical child.mutate; pitch blends within a bounded range. The dominant `voice_id` comes fromwhichever parent carries a real cloned or ElevenLabs voice, and the child's blendedsettings are genuinely synthesized through `/api/tts/eleven`, not just labelled.+ There is no free platform TTS lane: a preview clip bills the listener's prepaid+ credit wallet, or their own ElevenLabs key when one is saved (see+ [Voice Lab](./voice-lab.md)).- **Body.** Morph targets and colors blend; accessories and hidden parts recombine assets. At breed time the dominant parent's GLB is copied into the child's namespaceand the inherited appearance is baked into a real composite child GLB.@@ -51,12 +54,17 @@ parents and the same seed it always derives the identical child.hash, generation, and pedigree tier. `verifyGenome` re-derives the child from therecorded seed plus the parent-genome snapshots captured at breed time and confirmsthe stored hash matches. Breeding is idempotent per `(parents, seed)` key: replaying- the same pairing returns the same child instead of minting twins.+ the same pairing returns the same child (HTTP 200 with `deduped: true`) instead of+ minting twins, and two concurrent commits of the same key race on the unique+ breeding key, with the loser's provisional child retired and the winner's returned.## Walkthrough1. **Open [/genome](https://three.ws/genome).** Your agents load from `/api/agents`;- public studs load from `/api/genome/stud`.+ public studs load from `/api/genome/stud`. The **Your stud listings** section at+ the bottom lists or unlists your own agents and sets their `$THREE` stud fee+ (`POST /api/genome/stud`, owner-only; it has PATCH semantics, so sending only a+ new fee keeps the listing open rather than silently unlisting the agent).2. **Pick two parents.** Choose two agents you own, or pair one of yours with apublic stud. An agent cannot breed with itself.3. **Preview the offspring.** `POST /api/genome/preview` derives the child@@ -112,11 +120,17 @@ curl -s "https://three.ws/api/genome/lineage?agentId=<child-uuid>&verify=1"- **Breeding cooldown.** A parent can breed at most once per 6-hour window(`BREED_COOLDOWN_MS`). Breeding a parent still on cooldown returns HTTP 409`breeding_cooldown` with the remaining minutes. Cooldowns keep deep pedigrees- scarce.+ scarce. The cooldown is checked before the stud fee gate, so a breeding that will+ be refused never takes a real payment first.- **Stud fee settlement.** When a stud fee applies and no valid payment signature is- attached, `/api/genome/breed` returns HTTP 402 with the required `$THREE` amount.- Presence of a signature is not proof of payment; the fee must actually land in the- stud's payout wallet, and a single payment cannot be reused across breedings.+ attached, `/api/genome/breed` returns HTTP 402 `stud_fee_required` with the+ required `$THREE` amount (`stud_fee_unverified` when a signature is present but the+ fee did not land). Presence of a signature is not proof of payment; the fee must+ actually land in the stud's payout wallet, and a single payment cannot be reused+ across breedings: a unique index on `stud_fee_signature` makes the replay check+ atomic, and a reused signature returns HTTP 409 `stud_fee_replayed`. Paid+ breedings record the settled amount as `stud_fee_atomics` on the `genome_breedings`+ row.- **Determinism.** Same parents plus same seed always yields the same child. Changethe seed and you get a different (still valid) draw.- **Graceful birth.** A copy or bake hiccup never blocks the birth; the child stilldiff --git a/docs/github-memory-seeding.md b/docs/github-memory-seeding.mdindex 974ff4c4f..f9747b7cd 100644--- a/docs/github-memory-seeding.md+++ b/docs/github-memory-seeding.md@@ -84,7 +84,7 @@ selection, so the promise and the code cannot drift apart.| Stored on the agent | Never stored ||---|---|-| Up to 20 short distilled facts (max 600 characters each) about what you build, your stack, and how you describe your work | Repository file contents beyond the README excerpt |+| Up to 20 short distilled facts (max 600 characters each) about what you build, your stack, and how you describe your work | Repository file contents beyond the README excerpt (the first 8,000 characters of a ticked README) || Your GitHub handle and the exact selection manifest (profile on/off, repo keys, README keys) on every seeded row | Any GitHub credential; the access token stays HKDF-encrypted in the connection record and is never copied into a memory |## What lands in memory@@ -231,8 +231,8 @@ curl -s https://three.ws/api/agents/$AGENT_ID/memory/seed/github --cookie "$JAR"### `POST /api/agents/:id/memory/seed/github`Seed from a selection. `repos` and `readmes` are `owner/name` keys from the-catalog; a README key must also appear in `repos`. An empty selection is-refused (`400 empty_selection`).+catalog, at most 12 in each list; a README key must also appear in `repos`. An+empty selection is refused (`400 empty_selection`).```bashcurl -s https://three.ws/api/agents/$AGENT_ID/memory/seed/github --cookie "$JAR" \@@ -279,6 +279,7 @@ because no API can delete a personal access token using that token.| `csrf_missing` / `csrf_invalid` | 403 | A cookie-authenticated POST or DELETE arrived without a valid `x-csrf-token` || `not_found` | 404 | No such agent, or it is not yours (a malformed id also answers 404, never a 500) || `not_connected` | 412 | Connect GitHub first; the response carries `connect_url` |+| `validation_error` | 400 | The body failed schema validation: more than 12 `repos` or `readmes`, a key that is not `owner/name`, or (on `/api/auth/github/token`) a pasted string that is not shaped like a GitHub token || `invalid_token` | 400 | GitHub rejected the pasted token (mistyped, truncated, or expired) || `token_scope_refused` | 400 | The pasted token carries scopes outside the allowlist; `refused_scopes` names them || `invalid_selection` | 400 | A selected key is not in the catalog you were shown; `rejected` names each one |diff --git a/docs/hold-to-access.md b/docs/hold-to-access.mdindex cc37175a1..8558c67b4 100644--- a/docs/hold-to-access.md+++ b/docs/hold-to-access.md@@ -166,6 +166,11 @@ feature **Live** vs **Planned**, so the platform never promises an unwired perk.- **Free-quota multiplier** — a verified tier pass lifts the anonymous free-generationceiling by `rateMultiplier` in [`api/forge.js`](../api/forge.js) (`freeLaneMultiplier`),zero added latency.+- **Charged-at tier on `/credits`**: every credit debit already applies the discount, and+ `GET /api/credits` reports the caller's resolved tier as `holder` (the same shape+ `/api/pricing` returns, degrading to `null` on an RPC hiccup rather than failing the+ balance read), so the [`/credits`](../pages/credits.html) page shows the tier you are+ actually being charged at and the next one up.---diff --git a/docs/ibm.md b/docs/ibm.mdindex 626d3d434..c9d0acd39 100644--- a/docs/ibm.md+++ b/docs/ibm.md@@ -84,6 +84,7 @@ The shared server-side client lives in [`api/_lib/watsonx.js`](../api/_lib/watso2. **Project / space scoping.** Every inference body carries `project_id` (or `space_id`) — watsonx requires scoping on each call, so `watsonxConfig().configured` is only `true` when an API key **and** a project (or space) are both present.3. **Version stamping.** Calls are version-stamped via a `?version=` query param. The chat/embed/vision endpoints use `2024-05-31`; the Time Series Forecasting API (GA'd Feb 2025) uses `2025-02-11`. Both are overridable.4. **Real errors, surfaced.** Any IAM or upstream failure throws with the true status and message (auth, quota, model-not-enabled-in-region), so the calling endpoint reports the real cause rather than a generic 500.+5. **Every call has a deadline.** Both legs go through the shared `fetchUpstream` wrapper: the IAM exchange is idempotent, so it gets a 10 s deadline and up to three attempts; an inference is not, so it gets one attempt with a 45 s deadline (`api/_lib/watsonx-forecast.js` uses the same 45 s for the Time Series API, and `/api/brain/chat` aborts a watsonx stream that has not returned headers within 45 s). A stalled watsonx connection can no longer hold a request open indefinitely.The streaming chat endpoint returns an OpenAI-shaped SSE stream (`choices[].delta.content`), so the avatar runtime reuses its existing OpenAI delta reader verbatim.@@ -203,7 +204,7 @@ The Twin mirrors a live token's vitals (momentum, volatility, activity, liquiditThe Galaxy embeds every public agent with `granite-embedding-278m-multilingual`, projects the vectors into 3D with PCA, clusters them with k-means, and asks Granite chat to name each cluster. The result is a 3D star-map layout where semantically similar agents sit near each other. A natural-language search ("a witty Solana trading assistant") embeds the query and returns the nearest agents by cosine similarity: matching on meaning, not keywords.-The constellation is cached (keyed by a content hash of the agent set + model) so repeat visits are instant; `?refresh=1` forces a rebuild. The standalone embeddings endpoint, `POST /api/watsonx/embed`, exposes the same Granite vectors for your own semantic search or clustering:+The constellation is cached (keyed by a content hash of the agent set + model) so repeat visits are instant; `?refresh=1` forces a rebuild. Search has no provider failover and none would be correct (the stored agent vectors live in Granite's space, so a vector from another lane would be a different geometry), so when the query cannot be embedded the endpoint degrades the *method* instead: it ranks the same corpus lexically and answers 200 with `ranking: "lexical"` and `degraded: { reason: "embedder_unavailable", retryable: true }`, rather than a 502. A normal search reports `ranking: "semantic"`. Each result's `home_url` is the agent's canonical `/agents/:id` page. The standalone embeddings endpoint, `POST /api/watsonx/embed`, exposes the same Granite vectors for your own semantic search or clustering:```bashcurl -s https://three.ws/api/watsonx/embed \@@ -213,7 +214,7 @@ curl -s https://three.ws/api/watsonx/embed \It returns one vector per input (the response reports the model and its native `dimensions`), plus a `cachedHits` count: a warm process-local LRU keeps repeat embeddings free, and per-IP + global rate limits cap watsonx spend. The response itself is sent `cache-control: no-store`, because a POST body varies per request and must never be shared-cached.-**Always read `model` from the response.** The endpoint leads with Granite on watsonx.ai and falls through to the platform's free-first embedding chain (NVIDIA NIM, then Vertex, then OpenAI) when watsonx cannot serve a full batch, so a 200 does not by itself mean Granite answered. Every vector in one response comes from one provider, so `dimensions` is uniform. Only when no provider at all is configured does it answer `503 embed_unconfigured`, which is what lets a caller show an honest "not configured" state instead of inventing vectors.+**Always read `model` from the response.** The endpoint leads with Granite on watsonx.ai and falls through to the platform's free-first embedding chain (NVIDIA NIM, then Vertex, then OpenAI) when watsonx cannot serve a full batch, so a 200 does not by itself mean Granite answered. The fallback walks every configured lane in that order (`embedPassagesAny`), not just the preferred one, so a single NIM throttle no longer fails the request while Vertex and OpenAI sit idle. Every vector in one response comes from one provider, so `dimensions` is uniform. Only when no provider at all is configured does it answer `503 embed_unconfigured`, which is what lets a caller show an honest "not configured" state instead of inventing vectors; when every configured lane fails at the network level it answers `503 embed_unavailable` with the real upstream cause, a retryable status rather than a 502 the caller would read as permanent.## watsonx Constellationdiff --git a/docs/internal/MAINNET-TEST-2026-07-03.md b/docs/internal/MAINNET-TEST-2026-07-03.mdindex e78da7a6f..1306586ae 100644--- a/docs/internal/MAINNET-TEST-2026-07-03.md+++ b/docs/internal/MAINNET-TEST-2026-07-03.md@@ -2,7 +2,7 @@_Historical record: a point-in-time test report from 2026-07-03, when production still ran on Vercel. Production migrated to Google Cloud Run on 2026-07-07 (env vars now live on the Cloud Run service, not Vercel; deploy is `npm run deploy:gcp:full`, which runs `build:gcp` then `deploy:gcp`). The Vercel references, `vercel env` diagnostics, and secret-outage below describe that day's state. Do not read them as current infrastructure guidance. Current ops: [docs/ops/gcp-production.md](../ops/gcp-production.md)._-_Status as of 2026-08-05: the blocking outage below is resolved. The report's own verification step, `GET https://three.ws/api/auth/siws/nonce`, returns **200** with a real nonce (checked 2026-08-05), which per the corrected root cause means `JWT_SECRET` is restored in production; wallet login works again and the "test is BLOCKED at authentication" state no longer holds. Custodial key handling has since moved to a dedicated `WALLET_ENCRYPTION_KEY` with `JWT_SECRET` dual-read for v1 records ([api/_lib/secret-box.js](../../api/_lib/secret-box.js); see H8 in [docs/security/SECURITY_AUDIT.md](../security/SECURITY_AUDIT.md)). The findings below are preserved as written._+_Status as of 2026-08-05: the blocking outage below is resolved. The report's own verification step, `GET https://three.ws/api/auth/siws/nonce`, returns **200** with a real nonce (checked 2026-08-05), which per the corrected root cause means `JWT_SECRET` is restored in production; wallet login works again and the "test is BLOCKED at authentication" state no longer holds. Custodial key handling has since moved to a dedicated `WALLET_ENCRYPTION_KEY` with `JWT_SECRET` dual-read for v1 records ([api/_lib/secret-box.js](../../api/_lib/secret-box.js); see H8 in [docs/security/SECURITY_AUDIT.md](../security/SECURITY_AUDIT.md)). Since 2026-08-11 an unset `JWT_SECRET` only drops that legacy candidate from the decrypt list; it no longer breaks decryption of records written under the dedicated key, so the exact failure below (an empty `JWT_SECRET` locking every wallet) cannot recur on a deployment that holds `WALLET_ENCRYPTION_KEY`. The findings below are preserved as written._Real-SOL verification of every money-touching surface, run against production three.ws with a throwaway burner wallet. Audience: engineers. Every claim below carries a transaction signature or an HTTP transcript reference.diff --git a/docs/js-api.md b/docs/js-api.mdindex e4e796556..c41eac1da 100644--- a/docs/js-api.md+++ b/docs/js-api.md@@ -85,7 +85,7 @@ Processes a fileset from a drag-and-drop or file input event.1. Iterates the `fileMap` to find the root `.gltf` or `.glb` file2. Extracts the `rootPath` (directory portion of the file path)3. Calls `this.view(rootFile, rootPath, fileMap)`-4. Reports through `onError()` if no `.gltf`/`.glb` file is found+4. If no `.gltf`/`.glb` file is found, hides the spinner, logs a warning, and shows the viewer-status overlay ("No .gltf or .glb file in that drop. Pick a model file to view it.") with a **Choose a file** action that re-opens the file picker#### `view(rootFile: File | string, rootPath: string, fileMap: Map<string, File>)`@@ -110,7 +110,12 @@ Flow:Console-only diagnostic logging. The user-facing error surface is theviewer-status overlay driven by the `LOAD_END` protocol payload (see`_classifyLoadError` in `src/app.js`), which turns a failed load into a readable-message with a recovery action instead of a browser dialog.+message with a recovery action instead of a browser dialog. The overlay is+rendered by `_showViewerError(label, onAction, opts)`; `opts.actionLabel` and+`opts.busyLabel` reword the button for recoveries that are not a plain retry,+and `opts.keepOpenUntilLoad` clears the overlay instead of showing a busy state.+A failed `view()` keeps a replay handle (`_retryLastView`), so the Retry button+works for anonymous visitors on `/app` who have no agent to re-fetch.#### `showSpinner()` / `hideSpinner()`@@ -254,7 +259,7 @@ Adds a loaded model to the scene.1. Calls `this.clear()` to remove any existing model2. Computes bounding box and centers the model at origin-3. Configures camera near/far planes and position based on model size+3. Configures camera near/far planes and position based on model size; the seat is placed in front of the rig's face by reading its facing yaw (`estimateFacingYaw` in `src/viewer/facing.js`), so an avatar authored facing -Z or +X still opens front-on, and the historical +Z seat is used when no rig is readable4. Respects `options.cameraPosition` if provided5. Saves initial OrbitControls state6. Detects embedded lights (sets `state.punctualLights = false` if found)@@ -461,10 +466,10 @@ Returns a `<footer>` with:- X link to [@trythreews](https://x.com/trythreews)- "showcase" link to `/showcase`-- "validation" link to `/validation/`-- "reputation" link to `/reputation/`-- "help & feedback" link to GitHub issues-- GitHub repository link+- "validation" link to `/validation`+- "reputation" link to `/reputation`+- "help & feedback" link to the GitHub issue form (`nirholas/three.ws/issues/new`)+- GitHub repository link (`nirholas/three.ws`); every external link carries `rel="noopener noreferrer"`- Pipe separators between items**No props.**diff --git a/docs/kol-tracker.md b/docs/kol-tracker.mdindex 2da91e146..71a6ac754 100644--- a/docs/kol-tracker.md+++ b/docs/kol-tracker.md@@ -20,6 +20,8 @@ Influence and skill are different assets, and only one of them is priced into a- **Followers**, only for verified handles; a wallet with no attached handle shows a blank, never a fabricated count.- **Volume**, **Win Rate**, and **Trades** for the window.+The column set is data-driven: a column that every row leaves empty in the current window (followers when no verified handle ranks, volume when no wallet took the on-chain path) is dropped rather than rendered as a column of blanks, and the board's minimum width shrinks with it. The handle links to X, and the wallet address under every name links to its Solscan account. An "updated" stamp next to the row count says when the board was last fetched.+A segmented control switches the window between 24H, 7D, and 30D (arrow keys work on it), and the column headers relabel to match. Loading renders skeleton rows; an empty tracked list renders a designed empty state; a failed fetch renders an error state. The board never falls back to placeholder rows.## How ranking works (as coded)@@ -100,7 +102,7 @@ Recent pump.fun buys and sells by the tracked wallets for one mint, via Helius,curl 'https://three.ws/api/kol/trades?mint=<MINT_ADDRESS>&limit=20'```-Response: `{ mint, trades, wallets }` where each trade carries `wallet`, `side`, `amountSol`, `amountToken`, `price`, `signature`, `ts`, `time`, `usd`, `source` (`kol`, `whale`, or `smart-money` from the wallet's tags), and `label`. The `x-kol-source` response header is `helius` when the provider is configured; with no provider key the feed returns an empty list and `x-kol-source: unconfigured`, which is distinct from a configured provider outage (a `502 provider_unavailable` error).+Response: `{ mint, trades, wallets }` where each trade carries `wallet`, `side`, `amountSol`, `amountToken`, `price`, `signature`, `ts`, `time`, `usd`, `source` (`kol`, `whale`, or `smart-money` from the wallet's tags), and `label`. The `x-kol-source` response header is `helius` when the provider is configured; with no provider key the feed returns an empty list and `x-kol-source: unconfigured`, which is distinct from a configured provider outage. When Helius fails but a last-good answer for that mint is still held, it is served with `x-kol-stale: 1` and `stale: true, as_of` in the body rather than blanking the feed; with no last-good copy either, the error (a `502 provider_unavailable`) carries `Retry-After: 15`.### `GET /api/kol/wallets`diff --git a/docs/live-steps.md b/docs/live-steps.mdindex 436acbc94..571b7588b 100644--- a/docs/live-steps.md+++ b/docs/live-steps.md@@ -42,7 +42,7 @@ An id that is not registered renders a visible "this live step is not registered### Redaction-Fields whose names look like credentials (`sid`, `csrf`, any `*_token`, `authorization`, `cookie`, `api_key`, and friends) are replaced in the rendered copy, and the card says how many were hidden. This matters because documentation gets screenshotted, recorded, and pasted into issues, and a page that displays a working session identifier will eventually leak one.+Fields whose names look like credentials are replaced in the rendered copy, and the card says how many were hidden. The match is on the exact key name, case-insensitively, against a fixed list: `sid`, `csrf`, `csrf_token`, `token`, `access_token`, `refresh_token`, `id_token`, `secret`, `session`, `password`, `authorization`, `cookie`, `api_key` / `apikey`, and `private_key` / `privatekey`. A key outside that list (`foo_token`, say) is shown as is, so name new credential fields from the list. This matters because documentation gets screenshotted, recorded, and pasted into issues, and a page that displays a working session identifier will eventually leak one.Redaction only touches the **display**. Chained exports read the raw response body, so a step can consume a value that was never shown on screen.diff --git a/docs/marketplace.md b/docs/marketplace.mdindex 1c106be1c..fc9bd1a0d 100644--- a/docs/marketplace.md+++ b/docs/marketplace.md@@ -106,7 +106,13 @@ purchase mint. A wallet that has never held the mint, or holds less than theprice plus fee, gets a `409 insufficient_funds` naming the shortfall(`"this wallet is 0.35 short of …"`) instead of a transaction that can only failin-wallet. If the RPC cannot answer, the transaction is built anyway and the-chain decides, so a throttled node never blocks a payable purchase.+chain decides, so a throttled node never blocks a payable purchase. The other+chain reads on the checkout paths (the recent blockhash here and in the agent+purchase, the mint decimals in `agent-purchase.js` and `purchase-as-agent.js`)+go through the shared Solana read guards in `api/_lib/solana/read-guards.js`: a+cached blockhash still inside its validity window answers when the chain cannot,+and USDC-class mints resolve their decimals from a constant table without a+network call, so an RPC blip degrades to a served request instead of a 500.The payment modal shows the sponsored QR first and offers a one-click swap to thedirect-transfer QR for wallets that do not implement transaction requests.diff --git a/docs/mcp-3d-studio.md b/docs/mcp-3d-studio.mdindex 034a22c76..229f1bfb7 100644--- a/docs/mcp-3d-studio.md+++ b/docs/mcp-3d-studio.md@@ -67,6 +67,7 @@ analyze: inspect_model · optimize_model preview: preview_3d| `optimize_model(url)` | Actionable size/perf suggestions: Draco/Meshopt, KTX2, triangle budget. || `preview_3d(glb_url, …)` | Render any public GLB as an interactive `<model-viewer>` artifact (orbit, AR, auto-rotate). || `export_ar(glb_url, title?, kind?)` | Read-only: turn any public GLB into the device-aware AR link set (`arLaunchUrl`, `sceneViewerUrl`, `viewerUrl`, plus `irlUrl` when `kind: "avatar"`) and a [Spatial MCP](./spatial-mcp.md) artifact. Free. See [AR & WebXR](./ar.md#one-tap-ar-for-any-glb--get-apiar--export_ar). |+| `x402_preflight(origin, network?)` | Read-only, free: fetch an x402 seller's signed payability attestation from `<origin>/.well-known/x402-preflight`, verify its ed25519 signature, expiry, and subject, and answer whether that seller can actually settle before you pay it. An attestation that does not verify is reported as unverified, never as health. Spec: [`specs/x402-preflight.md`](../specs/x402-preflight.md). |Generation, rigging, and most mesh ops are **asynchronous**: the tool returns a`job_id` immediately, then you poll `generation_status` (reconstruction is@@ -143,6 +144,8 @@ timestamp.| `tripo` | geometry, image | **BYOK** | Cleanest quad topology. || `hunyuan3d` | image | self-host | High-poly, image-conditioned (GCP). |+When no `backend` is named, the resolver walks the free lanes first: the tier's named free engine (the self-hosted TRELLIS worker at `draft` and `standard`, the self-hosted Hunyuan3D worker at `high`), then the per-path fallback chain (self-host TRELLIS, self-host Hunyuan3D, the free HuggingFace Spaces lane, and last the free NVIDIA NIM TRELLIS lane, which is text-only). The paid Replicate `trellis` lane is the standing default only when no free lane is live on the deployment. Lane health is consulted, so a cold or down free worker is skipped for the next healthy one before submit.+**BYOK note:** the geometry backends (Meshy/Tripo) have no platform key. Supplyyour own via the `x-forge-provider-key` request header (or a key stored on yourthree.ws account). Without one, the geometry path returns a designed `needs_key`@@ -170,8 +173,9 @@ For tool calls there are two lanes:| `text_to_3d` / `image_to_3d` | by tier — $0.05 draft / $0.15 standard / $0.50 high || `auto_rig_model`, `retexture_model`, `retexture_region` | $0.05 || `stylize_model`, `remesh_model`, `segment_model` | $0.02 |+| `capture_scene`, `anchor_provenance` | $0.05 || `remove_background`, `pose_model`, `apply_animation`, `direct_prompt`, `generate_material` | $0.01 |-| `generation_status`, `preview_3d`, `list_animations`, `animation_signature`, `find_similar_animations`, `inspect_model`, `optimize_model`, `getting_started` | free |+| `generation_status`, `preview_3d`, `list_animations`, `animation_signature`, `find_similar_animations`, `text_to_animation`, `inspect_model`, `optimize_model`, `save_avatar`, `export_ar`, `verify_provenance`, `x402_preflight`, the persona tools, `validate_spatial_response`, `getting_started` | free |Payment settles only after the work succeeds — a wholesale failure costsnothing, and the same signed payment cannot be replayed.diff --git a/docs/mcp-studio.md b/docs/mcp-studio.mdindex d149447a1..8039cc911 100644--- a/docs/mcp-studio.md+++ b/docs/mcp-studio.md@@ -57,22 +57,25 @@ launcher, living avatars, link unfurls) is documented end to end in## Tools-`tools/list` returns exactly **ten** tools, and they split three ways:+`tools/list` returns exactly **eleven** tools, and they split four ways:- **Six generation tools** (`forge_free`, `text_to_avatar`, `mesh_forge`,`rig_mesh`, `forge_avatar`, `refine_model`), in the table below.- **One collector**, `check_job`, also in the table below.+- **One inspector**, `look_at_model`, also in the table below.- **Three persona/embodiment tools** (`create_agent_persona`,`get_agent_persona`, `persona_say`), in the **Embodiment** section further down.-All ten are free and keyless.+All eleven are free and keyless.The six generation tools run operator-funded on the platform's own generationpipeline. Annotations: `readOnlyHint:false`, `destructiveHint:false`,`idempotentHint:false`, `openWorldHint:true` (work runs against external modelAPIs; nothing is ever modified or deleted). `check_job` is the exception: it is apure status probe (`readOnlyHint:true`, `idempotentHint:true`) and never counts-against the generation quota.+against the generation quota. `look_at_model` is read-only and idempotent too,+but it renders frames server-side, so it rides the same per-IP generation+quota as the six generators.| Tool | Title | Input | Returns ||---|---|---|---|@@ -83,6 +86,7 @@ against the generation quota.| `forge_avatar` | Generate a rigged, animation-ready avatar | `prompt?` / `image_url?`, `allow_non_humanoid?` | rigged GLB avatar || `refine_model` | Refine a 3D model by describing a change | `glb_url`, `instruction`, `parent_prompt?`, `parent_lineage?`, `parent_index?` | refined GLB + version lineage || `check_job` | Check a pending 3D generation and collect it | `job_id` | GLB model, or an updated pending state |+| `look_at_model` | Look at a 3D model | `glb_url`, `views?` (up to 6 of `front`, `three-quarter`, `side`, `back`, `top`, `bottom`; default three-quarter, front, side, back), `size?` (128 to 1024 px, default 512) | rendered frames as images, plus geometry stats (triangles, materials, textures) and a plain reading of them |### Quality tiers@@ -341,11 +345,14 @@ rows, cloned so the ChatGPT pipeline can be tuned without touching the forge orany surface that rides it. The agent-facing REST endpoints (`/api/3d/generate`,`/api/v1/ai/text-to-3d`) stay on `/api/forge`.-The inline widget and the `/api/ar` launch page both load Google's-`<model-viewer>` from one pinned URL in+The inline widget loads Google's `<model-viewer>` from one pinned URL in[`api/_lib/model-viewer-cdn.js`](../api/_lib/model-viewer-cdn.js), which is alsothe origin the widget's `openai/widgetCSP` allowlists, so the script tag and its-CSP entry cannot drift apart.+CSP entry cannot drift apart. The `/api/ar` launcher no longer inlines a+`<model-viewer>` of its own: Android gets a Scene Viewer intent, and every other+device (and every live avatar) is sent on to `/ar/view`, a Vite-bundled page+that generates a real USDZ from the GLB on the device so iPhone gets genuine+Quick Look rather than a camera overlay (`api/_lib/ar-launch.js`).## Relateddiff --git a/docs/mcp-tools.md b/docs/mcp-tools.mdindex 25c21ff96..773b87794 100644--- a/docs/mcp-tools.md+++ b/docs/mcp-tools.md@@ -83,8 +83,15 @@ and direction tools are flat per call.| `anchor_provenance` | $0.05 | Sign a content credential and anchor its hash on Solana. |Free studio helpers (no charge): `getting_started`, `generation_status`,-`preview_3d`, `list_animations`, `inspect_model`, `optimize_model`, `save_avatar`,+`preview_3d`, `list_animations`, `animation_signature`, `find_similar_animations`,+`text_to_animation`, `inspect_model`, `optimize_model`, `save_avatar`, `export_ar`,+`verify_provenance`, `x402_preflight` (asks any x402 seller's signed payability+attestation whether it can actually settle before you pay it; free on purpose and+permanently), the persona tools (`create_agent_persona`, `get_agent_persona`,+`persona_say`, `persona_identity`, `persona_tip`, `persona_send`), and`validate_spatial_response` (the [Spatial MCP](spatial-mcp.md) conformance gate).+Every catalog tool is either priced or on this explicit free list; a test fails+the build if a new tool is neither.## Agent & commerce tools — `3d-agent-local`diff --git a/docs/media-api.md b/docs/media-api.mdindex 3fbd4ea93..b59c26edc 100644--- a/docs/media-api.md+++ b/docs/media-api.md@@ -532,7 +532,10 @@ staged as web-ready GLBs. Same pagination (`?limit=1..1000`, `?offset=`),same empty-until-staged behavior, no auth. One difference from the characterlibrary: this endpoint validates the cursors strictly, so a malformed`?limit`/`?offset` returns `400 invalid_limit` / `400 invalid_offset` instead-of being coerced into a page. See [the object library doc](./object-library.md)+of being coerced into a page. The manifest is served with+`access-control-allow-origin: *`, so a studio embedded on another origin can+render the object tray from it (the objects themselves already load cross-origin+through `/cdn/<key>`). See [the object library doc](./object-library.md)for the full parameter table.### Response@@ -599,7 +602,7 @@ the mesh arrived static, queues an auto-rig so the avatar can animate.### Response-`201` with `{ "avatar": { ... }, "view_url": "https://three.ws/discover/avatar/<id>" }`.+`201` with `{ "avatar": { ... }, "view_url": "https://three.ws/avatars/<id>" }` (the avatar detail page, the canonical link target across the platform).### Errors@@ -682,7 +685,11 @@ Poll the job on `/api/forge?job=<job_id>` like any forge generation.| Rate limit | `429` with `Retry-After` |When the vision lane is unconfigured or errors, the face check fails open and-the submission proceeds; forge still validates the image.+the submission proceeds; forge still validates the image. The hand-off to+`/api/forge` is bounded to 30 seconds and is deliberately never retried, since+that POST enqueues a generation and a replay would queue (and bill) a second+job; a hang there surfaces as `502 generation_unreachable` rather than an+endpoint that never answers.### curl@@ -740,6 +747,9 @@ policy as `/api/input-photo`. No auth; rate-limited per IP.| Generation service unreachable | `502 generation_unreachable` || Rate limit | `429` with `Retry-After` |+As with `/api/input-photo`, the hand-off to `/api/forge` is bounded to 30+seconds and never retried, so the same photos can never be queued twice.+### curl```bashdiff --git a/docs/news-rights.md b/docs/news-rights.mdindex 15b10129a..17af462c9 100644--- a/docs/news-rights.md+++ b/docs/news-rights.md@@ -61,7 +61,7 @@ Every registry feed is ingested. Some are crypto-native: every article is on topSo the human-facing feeds apply a display gate with two conditions:-1. **Relevance** — a crypto-native source always shows. A broad source's article shows only if the article itself is about crypto (a detected ticker, or a term from the crypto lexicon). This is what keeps "Ryanair broken window" and "3M stock jumps" out while letting the same source's Bitcoin coverage through.+1. **Relevance**: a crypto-native source always shows. A broad source's article shows only if the article itself is about crypto (a detected ticker, or a term from the crypto lexicon). Both are matched as whole words: the lexicon test is a `\b`-anchored regex (`CRYPTO_TERM_RE`), so "defied" no longer fires on `defi` and "tether" is in the list explicitly instead of matching through `ether`, and coins whose bare name is an ordinary word (NEAR, OP, MKR) are tagged only from a qualifying phrase ("NEAR Protocol", "Optimism mainnet", "MakerDAO") or a cashtag. This is what keeps "Ryanair broken window", "3M stock jumps", and "8 defied the selloff" out while letting the same source's Bitcoin coverage through.2. **Quality** — a credibility floor (default 0.6, override with `NEWS_MIN_CREDIBILITY`). Scored sources must clear it; unscored registry sources are presumed acceptable; legacy archive rows with no registry entry are never dropped on quality grounds.The gate is **display-only**. It runs on `/api/news/feed`, the RSS mirror, the daily digest, and related coverage — never on ingestion. The archive cron and the agent-signal callers still receive the full firehose. `GET /api/news/feed?raw=1` bypasses the gate for debugging or parity checks. An explicit single-source request (`?source=`) is also exempt: you asked for that outlet by name.diff --git a/docs/nvidia-models.md b/docs/nvidia-models.mdindex 4109d9987..77d4774f0 100644--- a/docs/nvidia-models.md+++ b/docs/nvidia-models.md@@ -31,8 +31,8 @@ Because it is one key for everything, a deployment either has the whole NVIDIA l| 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` | ✅ |+| **Text → image** | `black-forest-labs/flux.1-dev` | `api/_mcp3d/text-to-image.js` | ✅ |+| **LLM (default lane)** | `nvidia/nemotron-3-super-120b-a12b` (compact rung: `nvidia/nemotron-3-nano-30b-a3b`) | `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` | `api/_lib/embeddings.js` (and `api/agents/_id/embed.js`, which delegates to it) | ✅ |@@ -65,18 +65,18 @@ This is the headline free model. **Microsoft TRELLIS hosted on NVIDIA NVCF gives----## 2. Text → image — FLUX.1-schnell+## 2. Text → image: FLUX.1-dev-**Model:** `black-forest-labs/flux.1-schnell` · **Endpoint:** `ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-schnell`+**Model:** `black-forest-labs/flux.1-dev` · **Endpoint:** `ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-dev`**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.+FLUX.1-dev is the **free NVIDIA text-to-image lane** (the hosted FLUX.1-schnell preview was retired, so the lane moved to the dev checkpoint at 20 steps, CFG 3.5). It is a synchronous invoke: the image returns inline as base64, no poll.**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.+**Ladder order.** When `GOOGLE_CLOUD_PROJECT` is set, Vertex Imagen leads by default because it outdraws distilled FLUX for photoreal reference images and spends the GCP credit pool the platform is funded to burn (`VERTEX_IMAGEN_FIRST=0` restores the NIM-first order). After that: NVIDIA FLUX.1-dev (free) → the Hugging Face router (`HF_TOKEN`; fal-ai, then nscale, both serving FLUX.1-schnell in 2-5 s) → the Livepeer federation lane (behind `LIVEPEER_FEDERATION_ENABLED`) → Pollinations (keyless, so a fallback always exists past every keyed rung) → Replicate `flux-schnell` ($0.003/image, the paid backstop). The whole ladder shares one budget, `TEXT_TO_IMAGE_BUDGET_MS` (default 60 s): each lane gets a bounded slice of what remains so a stalled provider cannot hold a Forge submit for minutes, and exhausting the budget returns a retryable `rate_limited` error (`retryAfter: 15`) rather than a hung request.---@@ -86,10 +86,10 @@ NVIDIA NIM hosts 100+ open-weight chat models behind the one key, all OpenAI-com### 3a. The default production lane-**Model:** `meta/llama-3.3-70b-instruct`+**Model:** `nvidia/nemotron-3-super-120b-a12b` (with `nvidia/nemotron-3-nano-30b-a3b` as the compact Nemotron rung)**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 → Cerebras → OpenRouter → NVIDIA NIM**, followed by further keyless free rungs (OVH, Gemini, Pollinations) and only at the very end a paid backstop (Anthropic/OpenAI). NVIDIA serves the **same Llama 3.3 70B family** as the Groq/Cerebras/OpenRouter rungs but on an independent provider, so an outage on the other free lanes still answers here. It's tool/function-calling capable, so it's eligible for tool-required requests.+The platform's general LLM helper runs a **free-first ladder: Groq → Cerebras → OpenRouter → NVIDIA NIM**, followed by further keyless free rungs (OVH, Gemini, Pollinations) and only at the very end a paid backstop (Anthropic/OpenAI). Every free rung was re-pointed on 2026-08-27 to models the providers still serve: Groq now runs `qwen/qwen3.8-27b` (instant tier `openai/gpt-oss-20b`), Cerebras keeps `llama-3.3-70b`, and the NVIDIA rung runs Nemotron 3 Super 120B, an NVIDIA MoE on an independent provider, so an outage on the other free lanes still answers here. Both NVIDIA rungs are called with thinking disabled (`chat_template_kwargs: { enable_thinking: false }`) so a chat turn answers instead of reasoning out loud. Both are tool/function-calling capable, so they are 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.@@ -107,7 +107,7 @@ This lane powers the platform's built-in AI surfaces — chat, embedded site wid| 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 `nvidia/llama-3.3-nemotron-super-49b-v1.5` also appears in the routing catalog as a tool-capable fallback model.+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. The routing catalog in `chat-models.js` also lists `nvidia/nemotron-3-super-120b-a12b`, `nvidia/nemotron-3-nano-30b-a3b`, and `nvidia/llama-3.3-nemotron-super-49b-v1.5` as tool-capable NVIDIA models, and the Brain's own fallback chain still appends `meta/llama-3.3-70b-instruct` on NIM behind the OpenRouter rungs when a chosen route is dead.> **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.@@ -127,6 +127,8 @@ Two free NIM vision lanes on the OpenAI-compatible chat host. Nemotron Nano VL lAll three **fail safe**: if the vision lane is unavailable, the feature quietly switches off — it never blocks or breaks the primary flow.+The chain is budgeted and remembers what hurt. Each attempt gets an even share of whatever remains on the caller's deadline (`laneAttemptTimeout`, never below 3.5 s), so the first rung cannot consume the budget of the rest, and the pre-chain inline image fetch is capped at a quarter of the deadline and 8 s. A lane that fails is cooled for 45 s through the shared provider-health ledger (`api/_lib/provider-health.js`) and moved behind the healthy rungs on the next call rather than re-picked; a `429` cools every sibling lane on that host and skips them for the rest of the call, and a `401`/`403`/`402` earns the longer auth cooldown. A success clears the lane's cooldown.+---## 5. Embeddings — semantic retrieval@@ -134,7 +136,7 @@ All three **fail safe**: if the vision lane is unavailable, the feature quietly**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.+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. At ingest, `embedPassagesAny()` walks every configured embedder in free-first order (NIM → Vertex → OpenAI, the caller's preferred tag first), cooling a lane that fails for 45 s (longer on an auth fault) so the next ingest starts on a healthy rung, and returns the tag it actually used so the document set is stamped with the space its vectors live in. Search-side, the Agent Galaxy falls back to lexical ranking when the embedder cannot answer, because a query vector from another model cannot be compared against vectors stored in a different space.**Also:** the agent-embed endpoint [api/agents/_id/embed.js](../api/agents/_id/embed.js) does not carry a provider list of its own. It delegates to the registry above, so `POST /api/agents/:id/embed` serves this same model and returns the tag alongside the vector. It previously called `baai/bge-m3` directly; NVIDIA stopped serving that model on the hosted endpoint (500 on every request), which is exactly the failure mode a single registry prevents.@@ -186,6 +188,9 @@ The free NVIDIA TTS lane: **Magpie multilingual on Riva**, selected by an NVCF `| `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) |+| `TEXT_TO_IMAGE_BUDGET_MS` | Shared deadline for the whole text-to-image ladder (§2), default 60000 |+| `VERTEX_IMAGEN_FIRST=0` | Puts the free NIM FLUX lane ahead of Vertex Imagen again (§2) |+| `HF_TOKEN` | Unlocks the Hugging Face router rungs (fal-ai, nscale) in the text-to-image ladder (§2) |---diff --git a/docs/onchain-agents.md b/docs/onchain-agents.mdindex 8d42cebb2..9dac38cfb 100644--- a/docs/onchain-agents.md+++ b/docs/onchain-agents.md@@ -13,7 +13,8 @@ For every agent, one **Metaplex Core asset** that is:- **minted into the three.ws Agents collection** — authority-managed, so three.ws can curate on-chain metadata on the owner's behalf;- **owned by the agent** (its own custodial Solana wallet) or held in **authority custody** until claimed — see [Custody model](#custody-model);- carrying an on-chain **Attributes plugin** (platform, links, `$THREE`, schema — real bytes in the asset account) and an enforced **5% Royalties plugin**;-- pointing at a pinned **manifest** (Metaplex token-metadata + `agent-manifest/0.1`) on IPFS, so Phantom / Solscan / Magic Eden render it.+- pointing at a pinned **manifest** (Metaplex token-metadata + `agent-manifest/0.1`) on IPFS, so Phantom / Solscan / Magic Eden render it;+- **enrolled in the Metaplex Agent Registry** right after the mint: an Agent Identity PDA, authority-signed, whose URI points at the agent's live `/api/agents/:id/registration` document (see [What gets recorded](#what-gets-recorded)).The live mainnet collection: [`56Gnsb7Jjg1N9c8V7EAnDC4HmQbQjsEueSUA3EK5272H`](https://solscan.io/account/56Gnsb7Jjg1N9c8V7EAnDC4HmQbQjsEueSUA3EK5272H).@@ -48,6 +49,7 @@ Files:|---|---|| [api/_lib/onchain-deploy.js](../api/_lib/onchain-deploy.js) | Shared mint logic — collection resolution, manifest pin, Core mint, DB persist. || [scripts/deploy-agents-onchain.mjs](../scripts/deploy-agents-onchain.mjs) | CLI runner — dry-run preview, canary, full fleet. |+| [scripts/register-agents-onchain.mjs](../scripts/register-agents-onchain.mjs) | CLI back-fill: enrols already-minted agents that have a Core asset but no Agent Identity PDA (same `--network` / `--limit` / `--dry-run` / `--confirm` flags). || [api/_lib/solana-collection.js](../api/_lib/solana-collection.js) | Collection authority + address helpers. || [api/_lib/three-brand.js](../api/_lib/three-brand.js) | Manifest + on-chain attributes builders. |@@ -89,8 +91,9 @@ One funded wallet does everything — it is the **collection authority**, the **|---|---|| Deploy the collection (once) | ~0.003 SOL || Mint one agent asset | ~0.004 SOL (rent + fee) |+| Register its Agent Identity PDA | ~0.003 SOL (rent + fee) |-So ~0.05 SOL canaries a handful; **~0.004 × N** covers a fleet of N (≈ 7.5 SOL for ~1,850 agents). The runner checks the balance before each mint and pauses cleanly if it runs low — top up and re-run.+So ~0.05 SOL canaries a handful; **~0.007 × N** covers a fleet of N (≈ 13 SOL for ~1,850 agents). The runner checks the balance before each mint and pauses cleanly if it runs low: top up and re-run.---@@ -118,7 +121,9 @@ On a confirmed mint, `deployAgentOnce()` writes to `agent_identities.meta`:"chain": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp","family": "solana","cluster": "mainnet",+ "onchain_id": "<asset pubkey>","sol_asset": "<asset pubkey>",+ "contract_or_mint": "<asset pubkey>","metadata_uri": "https://ipfs.io/ipfs/<cid>","owner": "<owner pubkey>","custody": true,@@ -130,6 +135,8 @@ On a confirmed mint, `deployAgentOnce()` writes to `agent_identities.meta`:`sol_mint_address` is the canonical key every read path uses (explore, discover, profiles). It also makes re-runs **idempotent**: an agent that already has it is skipped. (Devnet runs are isolated under `meta.devnet` so they never block a real mainnet mint.) An `agent_actions` row (`type: solana.deploy`) is logged, and on mainnet a truthful `agent-onchain` feed event fires.+Right after the mint, `registerAgentOnce()` enrols the asset in the Metaplex Agent Registry. The collection authority signs (the owner still never signs and needs no SOL), the Agent Identity PDA's URI is set to the agent's live `/api/agents/:id/registration` document rather than a pinned snapshot (the registry program has no instruction to change a URI later, so a mutable endpoint keeps `active`, services, and the model current), and an `agent_registry` block is merged into the same `meta` (`standard: metaplex-agent-registry`, `program`, `identity_pda`, `asset`, `collection`, `authority`, `registration_uri`, `network`, `tx_hash`, `registered_at`; under `meta.devnet` for devnet runs). A second `agent_actions` row (`type: solana.register`) is logged. A registry failure never undoes the mint: the asset and `sol_mint_address` are already persisted, the runner prints `registry skipped: <error> (back-fill later)`, and `scripts/register-agents-onchain.mjs` picks up every agent that has `sol_mint_address` but no `agent_registry.identity_pda`.+---## Setup@@ -218,7 +225,7 @@ before and after the removal are identical.## Tutorial 3: The full fleet-Once the canary checks out and the funder holds enough SOL (~0.004 × N):+Once the canary checks out and the funder holds enough SOL (~0.007 × N):```bash# CLI, in batches:@@ -265,6 +272,7 @@ A confirmed canary asset shows `inCollection=true`, `royalty=500bps`, `attrs=11`| `solana rpc 429` / send timeouts | The public endpoint is rate-limited. Set `SOLANA_RPC_URL` to a Helius/Quicknode/Triton endpoint for the full run. || Manifest URI doesn't resolve | `PINATA_JWT` missing/invalid and no R2 configured. Set a valid `PINATA_JWT` (or `WEB3_STORAGE_TOKEN`, or the `S3_*` set). || An agent re-deploys unexpectedly | It shouldn't — `meta.sol_mint_address IS NULL` is the skip guard. If you intentionally re-mint, clear `sol_mint_address`/`onchain` from its `meta` first. |+| `↳ registry skipped: …` under a ✓ mint | The Core asset minted and persisted, but the Agent Registry enrolment failed (usually the RPC). Re-run `node --env-file=.env scripts/register-agents-onchain.mjs --confirm`; it only targets agents with `sol_mint_address` and no `agent_registry.identity_pda`, and already-registered assets short-circuit without a transaction. |---diff --git a/docs/openai-pr/02-wellknown-manifest-conflict.md b/docs/openai-pr/02-wellknown-manifest-conflict.mdindex dc335c6a4..53f0e310a 100644--- a/docs/openai-pr/02-wellknown-manifest-conflict.md+++ b/docs/openai-pr/02-wellknown-manifest-conflict.md@@ -13,7 +13,7 @@ asserts the app has a **zero payment surface** and no crypto capability. But a previewer-discoverable manifest at a well-known path says the opposite.[`public/.well-known/ai-plugin.json`](../../public/.well-known/ai-plugin.json)-currently reads (verbatim):+read, until commit `1dbbe0b6d` (2026-08-06) rewrote it (verbatim):```"description_for_human": "three.ws — 3D avatar/world generation and live crypto intelligence APIs, pay-per-call via x402.",@@ -24,10 +24,28 @@ And [`public/.well-known/openapi.yaml`](../../public/.well-known/openapi.yaml) (describes the general REST platform (Auth/Avatars/Keys/OAuth/MCP) and does **not**include the 3D Studio endpoints (`/api/3d/studio`, `/api/ar`, `forge_free`).-An OpenAI reviewer hitting `https://three.ws/.well-known/ai-plugin.json` sees a-crypto/payments pitch, directly contradicting the submission. This is the single+An OpenAI reviewer hitting `https://three.ws/.well-known/ai-plugin.json` saw a+crypto/payments pitch, directly contradicting the submission. This was the singlemost likely thing to sink the review.+**Where it stands now.** The served manifest leads with the free lane: its+`description_for_human` is "Free, keyless 3D avatar and world generation, plus an+optional paid API catalog for agents.", and `description_for_model` names the free+surface first (`POST /api/3d/studio`, the MCP lane at `/api/mcp-studio`, the viewer,+`/api/ar`, the read-only `/api/crypto` index) and points free-lane callers at+[`public/.well-known/3d-studio-openapi.yaml`](../../public/.well-known/3d-studio-openapi.yaml),+before describing the paid `/api/x402/*` catalog as separate and optional. `logo_url`+is `https://three.ws/pwa-512x512.png` and `legal_info_url` is `/legal/tos`. The+3D Studio schema is served at that path and byte-pinned to+`prompts/store-submissions/_generated/openai-actions.yaml` by+`npm run check:studio-openapi` (`scripts/sync-studio-openapi.mjs` regenerates the copy).+`tests/wellknown-manifests.test.js` asserts the served schema carries no+crypto/payment token and that the platform manifest never advertises the free lane+as paid; `tests/api/3d-studio-openapi.test.js` pins the schema to exactly+`/api/3d/studio` and `/api/ar`, keyless, with the AR parameters `api/ar.js` reads.+`openapi.yaml` still describes the general platform only, which is correct: the free+lane has its own artifact.+## Important scoping decision (this is why the task is delicate)This manifest is **also a real, live product surface** for the general three.ws@@ -62,9 +80,9 @@ manifest layer. Recommended approach (implement this unless you find it wrong):3. **Fix the misleading fields on the platform manifest that a 3D-app reviewer wouldsee as conflicting**, without deleting the real x402 catalog:- - `logo_url` is `favicon.ico` (`ai-plugin.json:14`). The submission cites a- 512x512 owned-IP icon. At minimum the logo should be a real branded PNG, not the- favicon.+ - `logo_url` was `favicon.ico` (`ai-plugin.json:14`). The submission cites a+ 512x512 owned-IP icon, and the manifest now points at `pwa-512x512.png`;+ `tests/wellknown-manifests.test.js` fails if it ever reverts to the favicon.- Make it unambiguous, in both the human and model descriptions, whichcapabilities are free and which are paid, so nothing reads as "the 3D app costscrypto." The 3D generation lane IS free and keyless. Say so plainly.@@ -102,11 +120,12 @@ manifest layer. Recommended approach (implement this unless you find it wrong):## Definition of done-- [ ] The 3D Studio app has a served, payment-free, self-describing discovery artifact- (jointly with Task 05).-- [ ] The platform `ai-plugin.json` no longer reads as "the 3D app is a paid crypto+- [x] The 3D Studio app has a served, payment-free, self-describing discovery artifact+ (jointly with Task 05): `/.well-known/3d-studio-openapi.yaml`.+- [x] The platform `ai-plugin.json` no longer reads as "the 3D app is a paid cryptoservice"; free vs paid is explicit; logo is a real branded asset.-- [ ] A test asserts the 3D-app schema is crypto/payment-free.+- [x] A test asserts the 3D-app schema is crypto/payment-free+ (`tests/wellknown-manifests.test.js`, `tests/api/3d-studio-openapi.test.js`).- [ ] `npm test` green.- [ ] Any commit that would trip the commit gate is prepared but NOT committed;flagged to the owner in your report with the exact diff.diff --git a/docs/openai-pr/03-forge-free-tier-truth.md b/docs/openai-pr/03-forge-free-tier-truth.mdindex 0d178bad1..eee30d879 100644--- a/docs/openai-pr/03-forge-free-tier-truth.md+++ b/docs/openai-pr/03-forge-free-tier-truth.md@@ -8,24 +8,42 @@ The submission answer sheet and the code disagree about what quality tier`forge_free` returns by default.**The code** ([`api/_mcp-studio/tools.js`](../../api/_mcp-studio/tools.js),-`handleForgeFree`) defaults to `standard` and degrades `high` to `standard` on-402/timeout. Verbatim comment:+`handleForgeFree`) defaults to `standard` and degrades an explicit `high` to+`standard` on a 402 or submit timeout. When this task was written the comment above+that line said the high tier was blocked on an async worker; today it reads+(verbatim):```-// Fast free lane by default. The deployed high-tier free engine (Hunyuan3D-// via HF Spaces) blocks the submit for 50-280s with no poll handle, which no-// ChatGPT tool call survives ... True high-by-default lands when the async-// self-host Hunyuan3D worker deploys (GCP_HUNYUAN3D_URL).+// Standard by default, and every doc describing this tool says exactly that.+// The high tier is a real, working option, not a stub: it runs on our own+// async Hunyuan3D worker (GCP_HUNYUAN3D_URL) behind a genuine poll handle,+// and a live production probe on 2026-08-06 returned a 2.69 MB high-tier GLB+// from backend `hunyuan3d` end to end. It stays opt-in rather than default+...const tier = VALID_TIER.has(args.tier) ? args.tier : 'standard';```+The two reasons it stays opt-in are in that comment: the worker is scale-to-zero,+so a cold container adds a spin-up on top of the generation, and the high-tier+access gate is cleared only by the platform seed token (`CRON_SECRET`), so a+deployment without it would quietly serve standard under a "high by default" promise.+A job that outlives `STUDIO_FORGE_TIMEOUT_MS` comes back as a pollable handle, never+an error.+**The submission doc**([`prompts/store-submissions/_generated/openai-submission.md`](../../prompts/store-submissions/_generated/openai-submission.md))-is internally inconsistent:-- Line ~31 correctly says the tools "default to the standard tier."-- Line ~146 (the tool table) says `forge_free` "Defaults to the highest quality tier+was internally inconsistent:+- Line ~31 correctly said the tools "default to the standard tier."+- Line ~146 (the tool table) said `forge_free` "Defaults to the highest quality tier(dense geometry + PBR textures)."+The tool table row now reads "Defaults to the standard tier (fast, reliable,+textured); the caller may request `draft` (fastest) or `high` (best, slower; falls+back to standard under load)", the tool's own `description` and its `tier` enum+say the same, and the live evidence for both tiers is in+`prompts/store-submissions/_generated/forge-free-tier-evidence.json` (a `d97e8e94d`+attempt to make high the default was rolled back in `b39d6e2f7`).+A reviewer who reads "highest quality tier" and then gets a standard-tier model hascaught us in a misstatement. Pick the honest resolution and make ALL surfaces agree.@@ -81,14 +99,22 @@ and a doc claiming it works.- A real `forge_free` call against `/api/mcp-studio` returns a tier consistent withevery doc. Save the response JSON as evidence.- `npm test` green (run `tests/mcp-forge-free.test.js` and `tests/mcp-studio.test.js`).+ Note which server each covers: `tests/mcp-studio.test.js` is the ChatGPT-facing+ `/api/mcp-studio` tool (standard default). `tests/mcp-forge-free.test.js` is the+ public `mcp-server` package's `forge_free` (`mcp-server/src/tools/forge-free.js`),+ which defaults to `draft` and no longer pins a backend: the forge router's own+ free-lane default (self-host TRELLIS, then Hunyuan3D, then HuggingFace, then NVIDIA+ NIM as the last resort) picks the engine, never the paid Replicate lane.## Definition of done-- [ ] Every doc, the submission sheet, and the tool's own `description` agree with the- code on the default tier.+- [x] Every doc, the submission sheet, and the tool's own `description` agree with the+ code on the default tier (Path A: standard by default, high opt-in; the async+ Hunyuan3D worker from Path B is deployed and proven, but the default stays+ standard for the reasons in the code comment).- [ ] If Path B: worker deployed and proven with real evidence; default is genuinelyhigh.-- [ ] If Path A: no surface claims "highest quality by default" anymore.+- [x] If Path A: no surface claims "highest quality by default" anymore.- [ ] `npm test` green.- [ ] `data/changelog.json` entry only if user-visible behavior changed (Path B yes;Path A is a docs/accuracy fix, `docs` tag).diff --git a/docs/openai-pr/04-openai-surface-test-coverage.md b/docs/openai-pr/04-openai-surface-test-coverage.mdindex 88e17c0e4..ff73047a3 100644--- a/docs/openai-pr/04-openai-surface-test-coverage.md+++ b/docs/openai-pr/04-openai-surface-test-coverage.md@@ -13,10 +13,13 @@ silently break what the reviewer sees.### Gap 1 — `api/ar.js` HTTP handler is untested`api/ar.js` is the "View in your space" / "Bring it to life" endpoint every generation-links to. Only the pure lib `api/_lib/ar-launch.js` is tested (`tests/ar-export.test.js`).-The handler's own behavior is unverified:-- User-agent branching (Android → Scene Viewer 302 intent; iOS/desktop → HTML launch- page; `kind=avatar` → IRL handoff).+links to. Only the pure lib `api/_lib/ar-launch.js` was tested (`tests/ar-export.test.js`).+The handler's own behavior was unverified:+- User-agent branching (Android → Scene Viewer 302 intent; iOS/desktop → a 200+ interstitial carrying the model's own og:image and title for unfurls, which hands+ off to `/ar/view`, where a real USDZ is generated on the device for Apple Quick+ Look; `kind=avatar` → everyone, Android included, lands on `/ar/view` with the IRL+ handoff).- The designed error page for a bad/missing `src`.- `assertArAssetUrl` rejection (non-https, non-`.glb/.gltf`) surfacing as a propererror response, not a crash.@@ -27,6 +30,12 @@ for each UA class and asserts status, `Location`/redirect, headers, and that thelaunch page contains the model URL and the AR launch elements. Follow the request/response mocking pattern used by the other `tests/api/*.test.js` files in this repo.+Closed: [`tests/api/ar-endpoint.test.js`](../../tests/api/ar-endpoint.test.js) covers+the Android redirect and its `no-store`, the iOS/iPad/desktop interstitial with the+title and the forwarded host carried through, the `kind=avatar` handoff, the designed+400 page for every bad-input class (including `.gltf` lookalikes), `Vary: user-agent`,+the CORS preflight, and an absent User-Agent.+### Gap 2 — `pages/embodiment/embed.html` wiring is untestedThe persona widget iframes this page. Its param parsing (`persona/glb/name/state/@@ -39,15 +48,34 @@ the repo already uses for page-level tests) that:- Loads with an unresolvable persona and asserts the designed error/empty state, not ablank void or console error.+Closed on two levels: [`tests/api/embodiment-embed-page.test.js`](../../tests/api/embodiment-embed-page.test.js)+pins the page's wiring contract (the documented query params, the persona resolve and+its failure surface, the designed error when neither `glb` nor `persona` is supplied,+the opt-in `wallet=1` identity poll, and that a resolved persona's name survives every+later state change instead of reverting to "Agent"), and+[`tests/e2e/embodiment-embed.spec.js`](../../tests/e2e/embodiment-embed.spec.js)+loads the page in a real browser.+### Gap 3 — No contract test binding `api/3d/studio.js` to `openai-actions.yaml`-The custom-GPT Actions response shape (`{status, glbUrl, viewerUrl, arUrl, format}` or-`{status:'pending', job, poll}`) must match the served OpenAPI schema (Task 05 serves-it). Add a contract test that loads the OpenAPI schema and validates a real+The custom-GPT Actions response shape (`{status:'done', glbUrl, viewerUrl, arUrl,+format, previewImageUrl?, tier?}` or `{status:'pending', job, poll, watchUrl,+previewImageUrl?, tier?, etaSeconds?}`) must match the served OpenAPI schema (Task 05+serves it). Add a contract test that loads the OpenAPI schema and validates a real`api/3d/studio.js` response object against it (the response-shaper is pure andexported per the file). Use an existing JSON-schema/OpenAPI validator already in`package.json` if present; do not add a heavy new dependency for this.+Closed: [`tests/api/3d-studio-actions-contract.test.js`](../../tests/api/3d-studio-actions-contract.test.js)+compiles the served+[`public/.well-known/3d-studio-openapi.yaml`](../../public/.well-known/3d-studio-openapi.yaml)+with `ajv` (2020-12 draft, plus `ajv-formats`, both already dependencies) and validates+the exported `shapeSubmit` / `shapePoll` output for the inline-done, queued, running,+finished, failed, and transient-hiccup states, plus every typed error envelope (400+`invalid_prompt`, `invalid_tier`, `prompt_rejected`, `bad_request`, `missing_job`,+`invalid_job`; 429 `rate_limited` with `retry_after`; 502 `generation_failed`; 503+`not_configured`) against the schema's `GenerationState` and `ErrorResponse`.+## Constraints- Every rule in `00-START-HERE.md`. No mocked *generation* results that pretend to be@@ -66,11 +94,11 @@ exported per the file). Use an existing JSON-schema/OpenAPI validator already in## Definition of done-- [ ] `tests/api/ar-endpoint.test.js` covers all UA classes, the error page, and+- [x] `tests/api/ar-endpoint.test.js` covers all UA classes, the error page, andheaders.-- [ ] A page-level test covers `pages/embodiment/embed.html` param parsing, persona+- [x] A page-level test covers `pages/embodiment/embed.html` param parsing, personaresolve, and the failure state.-- [ ] A contract test binds `api/3d/studio.js` output to the served OpenAPI (coordinate+- [x] A contract test binds `api/3d/studio.js` output to the served OpenAPI (coordinatewith Task 05 for the schema location).- [ ] `npm test` green.- [ ] Each new test demonstrably fails when its target is broken (verified, thendiff --git a/docs/ops/db-retention.md b/docs/ops/db-retention.mdindex 34fde6ec8..9b905821b 100644--- a/docs/ops/db-retention.md+++ b/docs/ops/db-retention.md@@ -19,7 +19,11 @@ Two families grow without bound:day** (≈30 MB/day), and its mint-keyed satellites grow in lockstep —`pump_coin_wallets`, `coin_smart_money`, `smart_money_scored`,`pump_coin_outcomes`, `oracle_conviction`, `oracle_conviction_history`. All- told the family adds **~60 MB/day**.+ told the family adds **~60 MB/day**. The smart-money judge+ (`api/cron/smart-money-rollup.js`) has to outrun this window: it walks unjudged+ coins oldest-first at 400 per run (raised from 80 on 2026-08-16, when a 309k+ backlog was ageing toward the cliff), because a coin pruned before it is judged+ never folds its buyers into `wallet_reputation` at all.2. **`avatar_regen_jobs`.** Each reconstruct job's `params` carries the multi-MBbase64 **source** images. The live path drops them once a job leavesreconstruction, but terminal jobs that took another route kept them — 346 rows@@ -51,6 +55,17 @@ Bounded + idempotent. Each tick:works **even at the cap**, where an `UPDATE` would itself fail with 53100.`wallet_reputation` (the durable, wallet-keyed output) and `pumpfun_graduations`(win/loss ground truth) are **never** touched.+- **Ledger windows with their own clocks.** The x402 audit ledger keeps a longer+ window (`X402_AUDIT_RETENTION_DAYS`, tightening to+ `X402_AUDIT_MIN_RETENTION_DAYS` under pressure), and `x402_spent_payments`, the+ replay guard behind `api/_lib/x402/spent-payments.js`, keeps a **fixed** window+ (`X402_SPENT_RETENTION_DAYS`) that the valve never shortens: a shorter window is+ a shorter replay-protection window, and the rows are too small to be why the+ branch is under pressure. `x402_self_facilitator_log` (the settle book, the+ largest table this cron does not touch) is deliberately unmanaged because+ `/api/x402-ring` aggregates it with no time filter for its `lifetime` totals;+ pruning it is a product decision about published revenue figures, not a+ retention one.- **Avatar job hygiene** — deletes terminal jobs past 30 days and strips base64source images from terminal jobs past a day.- **VACUUM** (plain) of the pruned tables so freed pages become reusable by@@ -85,6 +100,9 @@ fires one deduped `db:retention-pressure` alert.| `DB_COMPACT_ENABLED` | `1` | Set `0` to disable the `VACUUM FULL` compaction step entirely. || `DB_COMPACT_MIN_FREE_MB` | `25` | Only rewrite a table holding at least this much reclaimable space (and at least 30% of its file). || `DB_COMPACT_MAX_TABLES` | `3` | Most tables one tick may rewrite. |+| `X402_AUDIT_RETENTION_DAYS` | `90` | x402 audit ledger window (`x402_autonomous_log` and the audit log). Clamped `[7, 3650]`. |+| `X402_AUDIT_MIN_RETENTION_DAYS` | `30` | Floor the valve tightens the audit window to. Clamped `[1, audit retention]`. |+| `X402_SPENT_RETENTION_DAYS` | `90` | Fixed window for `x402_spent_payments` replay proofs. Clamped `[30, 3650]` so a typo cannot shrink the guard to hours; never tightened by the valve. |### Sizing the high-water mark (read before changing it)diff --git a/docs/ops/gcp-credits.md b/docs/ops/gcp-credits.mdindex a6429edac..7b4afc453 100644--- a/docs/ops/gcp-credits.md+++ b/docs/ops/gcp-credits.md@@ -361,7 +361,7 @@ Vertex speaks the Anthropic Messages API with four differences, all handled in- Model id in the **URL path**, not the body: `…/publishers/anthropic/models/<id>:streamRawPredict` (stream) / `:rawPredict` (non-stream). Regional endpoints prefix the host (`us-east5-aiplatform.googleapis.com`); `global` uses the bare host.- Body gains `"anthropic_version": "vertex-2023-10-16"` and drops `model` (+ `stream`).-- Auth: `Authorization: Bearer <oauth>` (via `api/_lib/gcp-auth.js` — shared with Imagen) — no `x-api-key`, no `anthropic-version` header.+- Auth: `Authorization: Bearer <oauth>` (via `api/_lib/gcp-auth.js`, shared with Imagen): no `x-api-key`, no `anthropic-version` header. The token is cached per process and refreshed five minutes ahead of expiry; if a refresh fails, the cached token is served until its hard expiry margin so a metadata-server blip does not fail a request.- Model id: bare aliases pass through (`claude-sonnet-4-6`); a dated first-party id converts to the `@` form (`claude-haiku-4-5-20251001` → `claude-haiku-4-5@20251001`) via `toVertexModelId()`.SSE event shapes are identical to first-party, so every existing stream parser works unchanged.@@ -408,7 +408,7 @@ behavior is intact.- **Preview first:** set `VERTEX_CLAUDE_ENABLED=1` (and optionally `VERTEX_CLAUDE_PRIMARY=1`) in Vercel **preview** only. Production flags stay unset — flipping production changes the billing lane and is the owner's call.- **Production flip (owner):** `printf '1' | vercel env add VERTEX_CLAUDE_ENABLED production` (+ `VERTEX_CLAUDE_PRIMARY` for chain inversion), then redeploy.-- **Rollback (instant, no code deploy):** unset `VERTEX_CLAUDE_ENABLED` / `VERTEX_CLAUDE_PRIMARY`. Every lane falls through to Groq → OpenRouter → NVIDIA → paid backstop exactly as before.+- **Rollback (instant, no code deploy):** unset `VERTEX_CLAUDE_ENABLED` / `VERTEX_CLAUDE_PRIMARY`. Every lane falls through to the free lanes (Groq → OpenRouter → NVIDIA → SambaNova → Mistral → Z.AI, each present only when its key is) → paid backstop exactly as before.---@@ -444,10 +444,21 @@ location (un-prefixed host).| `VERTEX_IMAGEN_MODEL` | `gemini-2.5-flash-image` | Generation model. An `imagen-*` value uses the legacy `:predict` path. || `VERTEX_IMAGEN_EDIT_MODEL` | `gemini-2.5-flash-image` | Edit model (`editImage()`); `imagen-*` routes to `:predict` inpainting. |-Ladder is unchanged and fully preserved: **NIM FLUX → Vertex → Replicate**, with-any Vertex error degrading cleanly to FLUX. Which provider served each image is-logged (`[text-to-image] served by <model>`) and persisted on the forge job as-`text_to_image_model`.+The ladder today (`textToImage()` in `api/_mcp3d/text-to-image.js`): **Vertex+Gemini first when the lane is configured** (`VERTEX_IMAGEN_FIRST=0` restores the+legacy NIM-first order without touching the on/off gate) → NVIDIA NIM+**FLUX.1-dev** (moved off `flux.1-schnell` on 2026-08-27 when that endpoint+stopped answering) → Hugging Face-routed fal-ai and nscale FLUX.1-schnell+(`HF_TOKEN`) → the Livepeer federation lane (flag-gated) → Pollinations+(keyless, always present, lower fidelity) → Replicate (paid backstop). Every+rung runs under one shared budget (`TEXT_TO_IMAGE_BUDGET_MS`, default 60 s): a+lane with a fallback behind it is capped at max(25% of the budget, 60% of what+is left), a lane with under 10% left is skipped, and an exhausted ladder answers+a retryable `rate_limited` that the forge boundary maps to a 429. Any Vertex+error degrades cleanly to the next rung, and because Pollinations needs no key,+no single provider's failure is ever the terminal error. Which provider served+each image is logged (`[text-to-image] served by <model>`) and persisted on the+forge job as `text_to_image_model`.### Verification status@@ -509,14 +520,18 @@ Live FLUX side-by-side samples were not captured: the prod `/api/v1/ai/image` POreturned `FUNCTION_INVOCATION_TIMEOUT` during the run and there is no NVIDIA key inthe local env, so FLUX could not be driven locally. The verdict rests on theinspected Gemini outputs plus the known FLUX.1-schnell characteristics; it does not-depend on ranking the two lanes, because Gemini stays the **fallback** (NIM FLUX-still leads the ladder) and its quality clears the bar for that role.--**Recommendation:** quality is not a blocker. Keep **NIM FLUX primary** (free, fast,-already carries prod) and Gemini as the credit-funded fallback that activates-whenever NIM is absent/down. No quality carve-out (draft-lane-only) is needed. The-GCP envs are already in Vercel prod, so the lane goes live on the next deployment;-instant rollback stays available via `VERTEX_IMAGEN_ENABLED=0`.+depend on ranking the two lanes, because at the time Gemini was the **fallback**+(NIM FLUX led the ladder until 2026-07-16) and its quality clears the bar for+either role.++**Recommendation (2026-07-07, since superseded):** quality is not a blocker. The+gate recommended keeping NIM FLUX primary with Gemini as the credit-funded+fallback. On 2026-07-16 the order was inverted (`VERTEX_IMAGEN_FIRST`, on by+default whenever the lane is configured) because the reference image is the sole+source of the 3D model's texture and proportions, and the credit pool is funded+to be spent on exactly that kind of quality. Instant rollback stays available via+`VERTEX_IMAGEN_ENABLED=0`, and `VERTEX_IMAGEN_FIRST=0` demotes Gemini to fallback+without switching it off.### Deploy & rollback@@ -526,7 +541,8 @@ instant rollback stays available via `VERTEX_IMAGEN_ENABLED=0`.- **Production** only after the quality gate passes cleanly:`printf '1' | vercel env add VERTEX_IMAGEN_ENABLED production`.- **Rollback (instant, no deploy):** set `VERTEX_IMAGEN_ENABLED=0` in the affected- environment — the lane drops to NIM FLUX → Replicate immediately. Removing+ environment: the ladder continues from NIM FLUX.1-dev through the HF-routed,+ Livepeer, Pollinations and Replicate rungs immediately. Removing`GOOGLE_CLOUD_PROJECT` also disables it but would break Vertex Claude/workers, soprefer the flag. To pin a specific model instead, set `VERTEX_IMAGEN_MODEL`.@@ -777,8 +793,8 @@ change, never a code migration. Proven at the code level by| Lane | Gate (present ⇒ GCP lane live) | Reverts to | Code ||---|---|---|---|-| **Vertex Claude** (chat/LLM) | `VERTEX_CLAUDE_ENABLED` (+`_PRIMARY`), needs `GOOGLE_CLOUD_PROJECT` | Groq → OpenRouter → NVIDIA → paid backstop | `api/_lib/vertex-claude.js`, `api/chat.js` `providerOrder()` |-| **Vertex Imagen** (text→image) | `GOOGLE_CLOUD_PROJECT` (+`GCP_SERVICE_ACCOUNT_JSON`) | free NIM FLUX → Replicate | `api/_mcp3d/vertex-imagen.js`, `text-to-image.js` |+| **Vertex Claude** (chat/LLM) | `VERTEX_CLAUDE_ENABLED` (+`_PRIMARY`), needs `GOOGLE_CLOUD_PROJECT` | free lanes (Groq → OpenRouter → NVIDIA → SambaNova → Mistral → Z.AI) → paid backstop | `api/_lib/vertex-claude.js`, `api/chat.js` `providerOrder()` |+| **Vertex Imagen** (text→image) | `GOOGLE_CLOUD_PROJECT` (+`GCP_SERVICE_ACCOUNT_JSON`) | free NIM FLUX.1-dev → HF-routed FLUX → Livepeer → Pollinations → Replicate | `api/_mcp3d/vertex-imagen.js`, `text-to-image.js` || **Forge TRELLIS self-host** | `MODEL_TRELLIS_URL` + `GCP_RECONSTRUCTION_KEY` | free NIM/HF → Replicate | `api/_lib/forge-tiers.js` || **Forge Hunyuan3D self-host** | `GCP_HUNYUAN3D_URL` + `GCP_RECONSTRUCTION_KEY` | free HF Spaces → Replicate | `forge-tiers.js` || **Forge TripoSG sketch** | `GCP_TRIPOSG_URL` + `GCP_RECONSTRUCTION_KEY` | none — option hides | `forge-tiers.js` |@@ -878,7 +894,7 @@ standard $0.15, high $0.50; Game-Ready $0.10.** (The prompt's "$0.25/$0.45" are| **Vertex Claude** | **Keep only if Vertex ≤ first-party Anthropic per token AND quality holds; else revert to free lanes** | Chat's free tier (Groq/OpenRouter/NVIDIA) costs $0 and already carries prod. Vertex Claude earns its keep only where quality needs a frontier model AND the Vertex partner-model token price beats calling Anthropic first-party. Compare `burn-report.mjs` vertex-claude spend ÷ tokens vs Anthropic list price. If Vertex ≈ Anthropic, revert to first-party (one less dependency); if free lanes suffice for the traffic, revert to free. || **Forge self-host — FREE-tier gens** | **Kill (revert to NIM/HF)** | Self-host serves free-first, so most gens earn **$0**. On credits: ~100% margin. Post-expiry: **$0.012–0.039 GPU for $0 revenue = pure loss.** Free NIM/HF cost $0 and cover these. || **Forge self-host — PAID x402 gens** | **Keep iff paid volume clears the floor** | Paid standard: **$0.15 − ~$0.012–0.024 ≈ 6–12× margin.** High: **$0.50 − ~$0.024–0.039 ≈ 13–20×.** Great per-call, but scale-to-zero means cold starts and near-idle GPU at low volume. Keep only if `burn-report.mjs` forge-gpu paid-gen volume beats Replicate (~$0.03–0.05/run, zero idle); else revert paid tiers to Replicate too. |-| **Vertex Imagen** | **Kill (revert)** | Free **NIM FLUX already leads** the chain; Imagen only serves when NIM is absent/down. On credits it was a free quality bump (~$0.02–0.04/img); post-expiry it's real money for a rarely-leading lane. NIM (free) + Replicate ($0.003) cover it. |+| **Vertex Imagen** | **Kill (revert)** | Gemini **leads** the chain today (`VERTEX_IMAGEN_FIRST`, on by default) for quality. On credits that is a free quality bump (~$0.02 to $0.04/img); post-expiry it is real money on every text→3D submit. Free NIM FLUX.1-dev, the HF-routed rungs, keyless Pollinations and Replicate ($0.003) cover it: `VERTEX_IMAGEN_FIRST=0` keeps Gemini as fallback only, `VERTEX_IMAGEN_ENABLED=0` drops it. || **Avatar reconstruct/rerig** | **Revert to Replicate** | `resolveProviderName()` already prefers Replicate; its pinned reliability at per-run cost beats idle GPU unless reconstruct volume is high (check the report). || **Editing workers** | **Revert / delete at teardown** | Auxiliary, low value; degrade to in-lane fallback or hide. No standing cost once min-instances=0. || **Vanity inventory** | **Done — keep the assets** | One-shot batch already ground; inventory persists in the app store and sells down at **zero ongoing GCP cost.** |@@ -1327,7 +1343,7 @@ flag alone — no code deploy:|---|---|---|| Vertex Claude | `vercel env rm VERTEX_CLAUDE_PRIMARY production` | chat falls back to free/BYOK lanes instantly (see prompt 02 section) || Forge GPU fleet | `vercel env rm FORGE_SELFHOST_PRIMARY production` | routing stops preferring the self-host GPU workers |-| Imagen | `vercel env add VERTEX_IMAGEN_ENABLED production` = `0` | text→image drops to the free NIM FLUX lane |+| Imagen | `vercel env add VERTEX_IMAGEN_ENABLED production` = `0` | text→image continues from the free NIM FLUX.1-dev rung (`VERTEX_IMAGEN_FIRST=0` keeps Gemini as fallback instead) |**Fast "stop the bleed now" — `scripts/gcp/emergency-stop.sh`** (dry-run bydefault): drops **every** Cloud Run service + job to `--min-instances=0`, cancels@@ -1459,7 +1475,7 @@ until today.defaults it on whenever `GOOGLE_CLOUD_PROJECT` is set (prompt 03's own design), sosetting `GOOGLE_CLOUD_PROJECT` alone activates the Imagen fallback lane; the prompt-03quality gate already passed (see above), so this is live now, fallback-only, NIM FLUX- still leads.+ still leads (as of that date; Gemini has led the ladder since 2026-07-16).**Not set** (matches every prompt's explicit fail-safe/owner-gate guardrail):`VERTEX_CLAUDE_PRIMARY`, `FORGE_SELFHOST_PRIMARY`, and the four other worker URLs(`GCP_HUNYUAN3D_URL`/`GCP_TRIPOSG_URL`/`GCP_RECONSTRUCTION_URL`/`GCP_TEXT2MOTION_URL`)diff --git a/docs/ops/gcp-production.md b/docs/ops/gcp-production.mdindex 75a36cff4..8a7809bbf 100644--- a/docs/ops/gcp-production.md+++ b/docs/ops/gcp-production.md@@ -35,7 +35,7 @@ Cloud Run service "three-ws-api" (us-central1, min 0, 2 vCPU / 2 Gi, timeout 900allow-unauthenticated, runtime SA three-ws@…)└─ one Express container (server/index.mjs) serving:• static frontend from dist/ (baked into the image)- • the vercel.json route table (1,236 rules as of 2026-08-13:+ • the vercel.json route table (1,285 rules as of 2026-09-01:headers/rewrites/redirects/404)• all api/** handlers with Vercel-parity filesystem routing│@@ -119,11 +119,13 @@ aerial-vehicle-466722-p5 --filter="bindings.members:three-ws-build@"`.```bash# Frontend changed? Build first — dist/ ships from the local build.-# build:gcp = check:conflicts -> check:browser-graph -> ensure:avatar-studio-# -> build:info:snapshot -> build:chat -> site build -> agent-3d CDN lib-# (build:lib:full) -> publish:lib -> build:info -> check:dist -> check:pages,-# IN THAT ORDER. The order is load-bearing: the-# site `vite build` WIPES dist/, so it must run before publish:lib mirrors the+# build:gcp = check:conflicts -> check:browser-graph -> check:tdz-bootstrap+# -> ensure:avatar-studio -> build:info:snapshot -> build:lib:full (the agent-3d+# UMD lib) -> build:avatar-sdk -> build:chat -> build (the site `vite build`)+# -> publish:lib -> build:info -> check:dist -> check:pages, IN THAT ORDER. The+# order is load-bearing: build:lib:full and build:avatar-sdk must run BEFORE the+# site build (it resolves avatar-sdk/src/agent.js against the copied bundle), and+# the site `vite build` WIPES dist/, so it must run before publish:lib mirrors the# lib into dist/. Plain `npm run build` is NOT enough (skips the lib publish, so# /agent-3d/latest/agent-3d.js 404s and the hero avatar dies). Hand-running# `build:vercel` as the frontend build is also WRONG — it builds the SDK/lib@@ -233,7 +235,7 @@ npm run smoke:prod> is a hard 404 at `/<slug>` unless `vercel.json` carries a rewrite. That> shipped twice in three days: `/timeline` (fixed by `5688277bd`, "page shipped> without a route entry") and `/tracker` (advertised 2026-07-23, 404 until a-> route landed two days later). `check:pages` resolves all ~424 declared paths+> route landed two days later). `check:pages` resolves all ~760 declared paths> through the real route table and fails the build on any that dead-end. When it> fires it tells you which of the two causes applies: a missing `vercel.json`> rewrite, or a page that was never built (missing `vite.config.js` input entry).@@ -472,6 +474,16 @@ pattern-matching an RPC error string, whose wording varies by provider.To resume autonomous spend, fund the payer's USDC float. The loop self-recoverson the next tick — no redeploy, no flag flip.+The sponsor's SOL floor gate has the opposite default. Its balance read can also+come back `null`, and until 2026-08-28 that read as "not paused": all four paid+RPC lanes were over quota at the moment the sponsor sat at 0.000899 SOL, so the+loop spent three hours signing payments that could not settle (95 attempts, 0+settled). An unreadable balance is not evidence of solvency, so a `null` read now+defers to `sponsorKnownBelowFloor()` (`api/_lib/x402/self-facilitator.js`), which+the settle path itself writes when the chain rejects the sponsor for+rent-exemption. That second opinion costs no RPC call, so the gate still answers+when the RPC does not.+### Ops alerts: dashboard-primary (2026-07-12)Ops alerting used to be Telegram-only, and Telegram-only meant that with no chat@@ -493,7 +505,7 @@ Telegram is now an **optional extra push**, off by default. When both`TELEGRAM_BOT_TOKEN` and `TELEGRAM_ALERTS_CHAT_ID` are set, alerts also push tothat private chat (deduped per signature for 1h, capped at 20/h). It isdeliberately unset in production — the dashboard is the channel. `/api/healthz`-reports `alerts.primary: "dashboard"` and `alerts.telegram_push:+reports `alerts.primary: "ops_alerts"` and `alerts.telegram_push:"disabled"|"enabled"`; a disabled push is expected, not a fault. The`@threewsbot` token remains in Secret Manager (`telegram-bot-token`) foruser-facing bot use (e.g. changelog push to holders); it is **not** wired to opsdiff --git a/docs/ops/payment-outcomes.md b/docs/ops/payment-outcomes.mdindex 61d8d35a7..1a4f5607a 100644--- a/docs/ops/payment-outcomes.md+++ b/docs/ops/payment-outcomes.md@@ -78,6 +78,19 @@ window and names the dominant cause in `ring_settle.metrics.cause`:or `rail` (genuine settle faults). `governorSkips` is carried even on a healthyrate so a wallet sliding toward its budget shows up before the rate does.+A rent-exemption failure on the fee payer (`InsufficientFundsForRent` on+account index 0, in either spelling the RPCs use) wears a rail-shaped reason+token (`simulation_failed`, `sweep_broadcast_failed`) while being the opposite+of a rail fault: the transaction never reached the rail because the sponsor+could not pay for it. The sensor flags those rows from the full `error_msg`+and counts them as floor signals, not faults, so a dry sponsor reads as+`cause: sponsor_floor` rather than pointing the operator at duplicate+signatures and RPC preflight (which is what happened for three hours on+2026-08-28). Because a sponsor under its floor is a hard stop, those attempts+also override the "too few attempts to judge" `unknown` verdict: once the+floor signals alone reach the minimum sample the status is `down` with a+`settle halted` detail, since under the floor nothing settles at all.+### `sponsor` (live RPC + `x402_self_facilitator_log`)The fee wallet that pays every settle's SOL fee:diff --git a/docs/ops/redis.md b/docs/ops/redis.mdindex a7f88e0e0..394acdd35 100644--- a/docs/ops/redis.md+++ b/docs/ops/redis.md@@ -136,14 +136,16 @@ degrades nothing.### Ops alert-`api/cron/forge-smoke.js` (daily cron) reads the same burn number and pages the-ops Telegram channel when the 30-day projection crosses a threshold:+`api/cron/forge-smoke.js` (daily cron) reads the same burn number and raises an+ops alert when the 30-day projection crosses a threshold:- **> 400,000 (80%)** → warning: "Redis on track to exceed quota …".- **> 450,000 (90%)** → critical: "forge + x402 outage imminent …".-Requires `TELEGRAM_BOT_TOKEN` + `TELEGRAM_ALERTS_CHAT_ID` (shared with the rest-of the ops alerting). The alert is advisory and never fails the smoke run.+It goes through `sendOpsAlert` (`api/_lib/alerts.js`), so it always lands in the+`ops_alerts` table and additionally pushes to Telegram when `TELEGRAM_BOT_TOKEN`++ `TELEGRAM_ALERTS_CHAT_ID` are set (shared with the rest of the ops alerting).+The alert is advisory and never fails the smoke run.### Config@@ -162,8 +164,9 @@ to `local` (no Redis command) or must stay Redis-backed.- **local** — per-instance in-memory is sufficient; spends zero Redis commands.Only for high-frequency, low-stakes flood guards where cross-instancecoordination buys nothing.-- **critical** — cost/money-moving or auth-security; must be Redis-backed and- **fail closed** when Redis is absent/exhausted.+- **critical**: cost/money-moving or auth-security; must be Redis-backed. When+ Redis is absent/exhausted it degrades onto the durable Postgres counter (see+ _Fallback behaviour_ above) and only denies when Postgres is down too.- **cross-instance-required** — correctness depends on shared state acrossserverless instances (atomic spend ledgers, idempotency/replay dedup, sharedfeeds/caches). Redis-backed, but fails *open* or degrades rather than denying.@@ -179,7 +182,7 @@ to `local` (no Redis command) or must stay Redis-backed.| `tokenPriceIp` | local | cache-served price reads; upstream Jupiter is rate-limit-free || `widgetRead` | local | embedded-widget read fetch — continuous third-party-page polling || `pinStatusIp` | local | pin-status progress poll |-| `authIp`, `registerIp`, `verifyEmailIp`, `forgotPasswordEmail`, `resendVerifyUser` | critical | auth/credential-guessing — fail closed |+| `authIp`, `registerIp`, `verifyEmailIp`, `forgotPasswordEmail`, `resendVerifyUser` | critical (`authIp` and `registerIp` also `degradeToMemory`) | auth/credential-guessing; Postgres fallback, then per-instance memory for the two login buckets so nobody is locked out || `chatUser`, `chatIp`, `chatHostKeyGlobal`, `brainChatUser`, `brainChatIp`, `livepeerIp` | critical | paid LLM inference || `mcp3dGenerate`, `mcpValidate`, `mcpInspect`, `mcpOptimize`, `mcpBazaar`, `mcpAgent`, `mcpAgentPay` | critical | paid compute / paid tools || `avatarPayoutDaily`, `agentBuy`, `x402PayGlobal`, `videoGenerateUser`, `videoGenerateGlobal` | critical | real money movement |@@ -190,7 +193,7 @@ to `local` (no Redis command) or must stay Redis-backed.| File | Class | Operation || --- | --- | --- |-| `api/_lib/cache.js` | cross-instance-required | shared cache GET/SET/DEL (read-memo + single-flight in front to cut burn) |+| `api/_lib/cache.js` | cross-instance-required | shared cache GET/SET/DEL (read-memo + single-flight in front to cut burn); `cacheWrapLastGood()` keeps a `<key>:lkg` sibling (24h) that is served when a refresh throws, so an upstream blip returns last-good data instead of an error || `api/_lib/feed.js` | cross-instance-required | activity feed LPUSH/LTRIM/LRANGE (8s read-coalesce window) || `api/_lib/usage.js` | cross-instance-required | usage-event buffer RPUSH/LRANGE/LTRIM (batched flush) || `api/_lib/x402-spending-ledger.js` | critical / cross-instance-required | atomic INCRBY spend caps per hour/day/address |diff --git a/docs/ops/solana-rpc-lanes.md b/docs/ops/solana-rpc-lanes.mdindex 0ab877e7c..c9b68abb5 100644--- a/docs/ops/solana-rpc-lanes.md+++ b/docs/ops/solana-rpc-lanes.md@@ -310,6 +310,43 @@ BigQuery `blockchain-analytics-*` datasets are EVM chains plus analytics, so the"prefer GCP, credits are pre-approved" rule has nothing to offer this lane. Do not spendtime re-checking it.+## When every lane fails at the wire++Ten unrelated hosts do not die in the same millisecond. On 2026-08-27 the fleet+logged `all 10 endpoints failed this request, fetch failed` about 2,000 times an+hour while a direct probe of the same lanes from the same region answered fine:+when every lane fails with a transport error (DNS, refused socket, reset) inside+one request, the weather is on our side of the wire (instance egress, resolver,+socket pool) and it clears in well under a second. `connection.js` stacks three+answers, cheapest first:++- **The error names the errno.** A thrown fetch carries the undici cause code+ (`ECONNRESET`, `EAI_AGAIN`, `ENOTFOUND`, ...) and the lane it died on, so+ `fetch failed` alone no longer sends a reader hunting for a week. `EAI_AGAIN` is+ a resolver problem, `ECONNRESET` a socket one.+- **One jittered re-sweep.** When the first sweep was transport-only, every lane+ is tried once more after a 250-700 ms pause. An HTTP 429 or a quota body is a+ verdict about the lane, not the wire, and never triggers it.+- **Last-good reads instead of a 502.** Idempotent read methods (`getBalance`,+ `getAccountInfo`, `getMultipleAccounts`, `getTokenAccountsByOwner`,+ `getTokenLargestAccounts`, `getProgramAccounts`, `getSignaturesForAddress`,+ `getTransaction`, the DAS `getAsset*` family, and a few more) answer from the+ last body a lane returned for the identical call, kept in the shared cache for+ 15 minutes and marked with an `x-solana-rpc-stale` header carrying its age in+ ms. Blockhash and slot reads are excluded on purpose: a stale blockhash+ produces a transaction that fails later and worse. A success republishes its+ body at most once a minute per call shape, so the steady state costs one cache+ write a minute per distinct read, not one per RPC call.++A batch that a lane refuses for its own per-batch cap (`maximum number of calls+in a batch`, `batch too large`) is split into at most 64 single requests, four at+a time, instead of failing the whole call; the cap is remembered per (lane,+method) for 30 minutes so the next batch goes straight to the split, and a batch+too wide to split rotates to a lane that takes it whole.+[tests/solana-rpc-transport-fallback.test.js](../../tests/solana-rpc-transport-fallback.test.js)+and [tests/solana-rpc-rotating-fetch.test.js](../../tests/solana-rpc-rotating-fetch.test.js)+pin this behaviour.+## Knock-on effects to expectRPC starvation does not stay in the RPC layer:diff --git a/docs/ops/x402-discovery-listings.md b/docs/ops/x402-discovery-listings.mdindex dd22dc435..1367603eb 100644--- a/docs/ops/x402-discovery-listings.md+++ b/docs/ops/x402-discovery-listings.md@@ -148,7 +148,11 @@ CDP/x402 team. Not ERC-8004-based. Burden: none beyond section 2.- **Bazaar extension** (`"bazaar"` key in `extensions`): `description`,`input`, `inputSchema`, `output` (example + schema), `bodyType`, and for MCP`toolName`/`transport`. The description drives semantic-search ranking; the- example input must pass JSON-Schema validation or indexing is rejected.+ example input must pass JSON-Schema validation or indexing is rejected. The+ example is also what a buyer replays after settling, so it has to resolve:+ the `/api/mcp` sample body (`bazaarExtension()` in `api/_lib/x402-spec.js`)+ points `validate_model` at `https://three.ws/avatars/cesium-man.glb`, the+ same GLB the agent card advertises, not an example.com placeholder.- **/.well-known conventions:** there is no ratified `.well-known/x402` in thecore spec — the v2 Discovery extension (facilitator-crawled metadata) is theofficial direction (<https://www.x402.org/writing/x402-v2-launch>). In the@@ -181,7 +185,7 @@ CDP/x402 team. Not ERC-8004-based. Burden: none beyond section 2.## 6. The datapoint fabric: seeding settlements on ~4.4k granular URLs-Most of our payable surface is not the ~68 named endpoints in `ring-catalog.js`. It+Most of our payable surface is not the 84 named endpoints in `ring-catalog.js`. Itis the **datapoint fabric**: one route (`api/x402/d/[...path].js`) that fans out aper-metric paid URL for every entity in every family defined in`api/_lib/market-data/datapoints.js`, at $0.0005 a call. `/.well-known/x402.json`@@ -207,7 +211,12 @@ node scripts/x402-seed-datapoints.mjs --only=coin,protocol --per-family=25It pulls its seed list **live from the discovery doc**, so there is no hand-maintainedURL list to drift, buckets by family, and settles core metrics (price, tvl, supply,-volume) first so a bounded budget proves the whole surface is live. Payments are+volume) first so a bounded budget proves the whole surface is live. The family reads+behind those URLs retry once and keep an hour-long last-known-good copy, so a+DeFiLlama or CoinGecko blip serves a slightly older row instead of a 503 on a paid+call; a datapoint served that way stamps `as_of` with the time the data was actually+fetched upstream and adds `stale: true` plus `age_seconds`, so a buyer is never sold+an hour-old number as a live one. Payments arecircular: the payer wallet pays our own treasury, so the USDC round-trips and only theSolana network fee (~$0.000005/tx) is actually burned. An `onAccept` gate refuses anypayment whose `payTo` is not our configured treasury, so a compromised or mis-set@@ -275,6 +284,13 @@ The path to being counted, all Solana, no Base required:with `ECONOMY_REBALANCE_ENABLED=1` (owner spend approval) or the payerdrains and the whole ring halts with `insufficient_payer_usdc`, which isexactly what happened 2026-07-15.+4. **Accept what the standard client builds.** The reference x402 SVM client+ (`@x402/svm`, which our own payload builder delegates to) attaches an SPL+ Memo instruction to every `exact` payment, so the self-facilitator's+ anti-drain gate skips both live Memo program ids as carrying no fund+ movement instead of rejecting the transaction. Without that, no+ third-party buyer using the stock client could settle here, and none of+ their volume would exist to be counted.## Registration log@@ -295,7 +311,16 @@ probe surfaced two classes of issue, fixed in code on 2026-07-12:WWW-Authenticate on a 402 as an MPP header and flags the missing`Payment` challenge. We speak x402, not MPP/Tempo, so the 402 branch of`api/_mcp/auth.js sendAuthChallenge()` no longer sends WWW-Authenticate- (the 401 OAuth branch keeps it).+ (the 401 OAuth branch keeps it). A spec-compliant MCP client (one sending+ `Accept: application/json, text/event-stream`) still reads as an OAuth+ protocol client and gets that 401 by default; a surface whose buyers key+ strictly on 402 (the OKX 3D tools under `api/okx/3d/`) passes+ `paymentStatus: 402` to force the Payment Required answer for every caller.+ Prepended rails are deduped against the shared builder's accepts so a+ listing never advertises the same rail twice, and `DELETE /api/mcp` with an+ `Mcp-Session-Id` this stateless server never issued answers `404+ unknown_session` (the transport's "start a fresh session" signal) rather+ than a 204 for a session it never held.- **Skipped "unprotected" endpoints**: the 29 free-tier `/api/v1/x/*`aggregator endpoints now declare `security: []` with no `x-payment-info`in `/openapi.json` (the auditor classifies x-payment-info as paid and thendiff --git a/docs/oracle-model.md b/docs/oracle-model.mdindex 0ca1e7091..f845d6d39 100644--- a/docs/oracle-model.md+++ b/docs/oracle-model.md@@ -23,14 +23,15 @@ look wildly overconfident.| Tier | Score | Claims | Observed on held-out data ||---|---|---|---|-| Prime | 86+ | P(win) >= 45% | 46.4% (n=304) |-| Strong | 72+ | P(win) >= 25% | 39.3% (n=858) |-| Lean | 56+ | P(win) >= 12% | 23.3% (n=1,415) |-| Watch | 34+ | P(win) >= 5% | 10.4% (n=2,790) |-| Avoid | 0+ | below that | 1.8% (n=68,844) |--Those observed numbers come from 74,211 launches the model had never seen. They-are recomputed on every refit and published live at+| Prime | 86+ | P(win) >= 45% | 47.6% (n=267) |+| Strong | 72+ | P(win) >= 25% | 40.3% (n=852) |+| Lean | 56+ | P(win) >= 12% | 23.4% (n=1,418) |+| Watch | 34+ | P(win) >= 5% | 10.7% (n=2,725) |+| Avoid | 0+ | below that | 1.8% (n=68,949) |++Those observed numbers are the bootstrap model's holdout: 74,211 launches the+model had never seen, from the fit shipped in `conviction-model.json`. They are+recomputed on every refit and published live at[`/api/oracle/model?view=card`](/api/oracle/model?view=card), so the table abovecan go stale but the endpoint cannot.@@ -123,7 +124,9 @@ win = moon AND hold_multiple >= 1Neither ratio can be moved by the price of SOL, and both backfill exactly fromcolumns we already stored, so the historical corpus was corrected in a single-migration with no re-fetching.+migration with no re-fetching. A row with no `hold_multiple` at all cannot+answer the survival question, so it is neither a `win` nor a `rug` (it can+still be a `moon`); it is never read as a 100% drawdown and counted as a rug.**The real rug rate is 11.4%, not 91%.** And it holds within two points acrossevery observation-age bucket from 60 minutes to three days, which is what a@@ -169,6 +172,20 @@ The code is [`api/_lib/oracle/fit.js`](https://github.com/nirholas/three.ws/blobshared by the CLI and the production cron so the terminal and the server cannever disagree about what "the model" means.+### Thin buckets say less++After the fit, every weight is shrunk toward zero in proportion to the evidence+behind it: `w * n / (n + 200)`, where `n` is the number of rows in that bucket+(`fit.shrink_prior` in the model document). A bucket with 200 rows keeps half+its fitted weight, one with 2,000 keeps 91%, one with 34 keeps 15%. Without+this, a 34-row bucket could emit a -0.64 log-odds opinion that reversed a+verdict in production; `smart_money_count >= 4` did exactly that, fitting+negative on the `win` head although those launches won at four times the base+rate, because with so few rows the regression hands the bucket whatever+residual the correlated volume and buyer-count features leave behind. The+shrinkage is applied before evaluation, never after, so the holdout numbers+describe the weights that actually ship.+### Features drop themselvesAny feature whose runner-up bucket holds fewer than 200 rows carries no fittable@@ -317,7 +334,7 @@ something) rather than being treated as zero.const { math } = oracle.explain(signals);math.formula // 'p = 1 / (1 + exp(-(intercept + sum(term log_odds))))'-math.intercept // -3.8771+math.intercept // -3.9975math.terms // one row per bucket, with its sample countmath.total_log_odds // add the column up by hand; you will land here```diff --git a/docs/oracle.md b/docs/oracle.mdindex b036c7789..340506ea4 100644--- a/docs/oracle.md+++ b/docs/oracle.md@@ -33,9 +33,9 @@ One design commitment holds the whole thing together: scoring is a pure, side-ef## The model: fitted from real outcomes-Since 2026-08-09 the conviction engine is a bucketed logistic model fitted on the platform's own labeled outcome history (92,906 launches at first fit, growing ~30k/day), not a hand-tuned point system. "Good" is defined as the coin graduated or reached a 3x-or-greater ATH multiple. Every launch-time signal is bucketed by its empirically observed ranges, each bucket carries a fitted log-odds weight, and the fused sum passes through a sigmoid to yield a calibrated P(good). The full weight table ships in `api/_lib/oracle/conviction-model.json` with each bucket's sample size and observed good-rate, and `scripts/oracle-fit.mjs` refits it from the durable training snapshot (`oracle_training_set`) whenever the data has grown.+Since 2026-08-09 the conviction engine is a bucketed logistic model fitted on the platform's own labeled outcome history, not a hand-tuned point system. v2 fitted one target ("good": the coin graduated or reached a 3x-or-greater ATH multiple) on 92,906 launches. Since 2026-08-28 the engine is **v3**: three heads fitted over one shared design matrix, all reading a `hold_multiple` that cancels the SOL price out of the label (`win`: it ran and a first-sight holder is still up; `rug`: a first-sight holder is down more than half; `moon`: it ran at all, the v2 target). The published 0-100 score anchors on `win`, and rug risk is published beside it as its own number rather than folded in (`rugRisk`, `upside`, `giveBackRisk` on every verdict). Every launch-time signal is bucketed by its empirically observed ranges, each bucket carries a fitted log-odds weight per head, and the fused sum passes through a sigmoid to yield a calibrated probability for each head. The promoted weights live in `oracle_model_versions` and `/api/cron/oracle-refit` refits and re-promotes them behind a gate that can refuse a candidate; `api/_lib/oracle/conviction-model.json` is the bootstrap a cold container scores with until it reads the active row (each bucket ships with its sample size and observed rate per head), and `scripts/oracle-fit.mjs` refreshes that bootstrap from the durable training snapshot (`oracle_training_set`). The whole model, labels and promotion gate included, is written up in [The Oracle model](oracle-model.md).-The honest numbers, measured on a time-split holdout (the newest 25 percent of labels, never seen in training): AUC 0.879 (the hand-tuned v1 engine measured 0.627 on the same window), 62.5 percent of coins in the top decile of score were good against an 11.7 percent base rate, and the Prime tier observed 72.7 percent good.+The honest numbers. v2, measured on a time-split holdout (the newest 25 percent of labels, never seen in training): AUC 0.879 (the hand-tuned v1 engine measured 0.627 on the same window), 62.5 percent of coins in the top decile of score were good against an 11.7 percent base rate, and the Prime tier observed 72.7 percent good. v3, held out on 74,211 launches it never saw: win AUC 0.840, rug AUC 0.918, moon AUC 0.892. The live reading is always at `/api/oracle/model?view=card`.The fit corrected several v1 beliefs that were backwards at the 90-second observation window:@@ -51,7 +51,7 @@ The four pillars remain as the presentation layer: every feature belongs to WHOEach feature below is bucketed and carries fitted weights in `conviction-model.json`. The observed good-rates quoted are from the training set at first fit; the shipped JSON is always the source of truth.-**WHO (pedigree)**: the creator's launch record (`creator_record`: first launch 1.9x base; any prior graduation 1.5x; 5+ launches with none graduated 0.26x), dev buy size, and whether the dev sold inside the observation window. On top of the fitted features sits the smart-money overlay (below).+**WHO (pedigree)**: the creator's launch record (`creator_record`: first launch 1.9x base; any prior graduation 1.5x; 5+ launches with none graduated 0.26x), dev buy size, whether the dev sold inside the observation window, and (since v3) the count of proven smart-money wallets buying in the window, fitted directly. The expert priors the model cannot fit sit on top (below).**HOW (structure)**: organic-demand score (below 0.2: 0.11x base; 0.8+: 5.1x, the single strongest signal), bundle score, snipe ratio, coordination score, buy-timing entropy, and top-1/top-10 holder concentration with their empirically non-monotone buckets.@@ -61,7 +61,7 @@ Each feature below is bucketed and carries fitted weights in `conviction-model.j### The smart-money overlay-Proven and flagged wallets are too rare to fit statistically (998 proven wallets platform-wide against 288k judged), but when they do appear they are the highest-fidelity evidence there is, so they adjust the fused log-odds as documented expert priors: proven wallets in the book add up to +0.75 log-odds (about a 2.1x odds bump), a 40-percent-plus proven share of buy volume adds +0.3, each flagged rugger/dumper wallet subtracts 0.45 (up to three), and smart money already exiting half its position subtracts 0.7. A wallet counts as proven if labelled `smart_money`/`kol` or scoring 70+; since 2026-08-09 a wallet also earns `smart_money` at 8-plus judged coins with a 35-percent-plus win rate, a sustained ~3x edge over the market, validated against holdout outcomes (coins with 3 or more such wallets buying early were good 95 percent of the time).+Under v2, proven wallets were too rare to fit statistically, so they adjusted the fused log-odds as hand-set expert priors (+0.35 to +0.75 log-odds for proven wallets in the book, +0.3 for a 40-percent-plus proven share of buy volume). v3 fits `smart_money_count` directly (two or three proven wallets buying inside the window observed a 55 percent survivable-win rate and zero rugs across 351 samples), and when the active model carries that feature the overlay's smart-money and creator-history terms stand down automatically, so the same wallets are never counted twice. What survives in the overlay is evidence the training set has no column for: each flagged rugger/dumper wallet subtracts 0.45 (up to three), smart money already exiting half its position subtracts 0.7 (a quarter: 0.35), and the serial-rugger ceiling below. A wallet counts as proven if labelled `smart_money`/`kol` or scoring 70+; since 2026-08-09 a wallet also earns `smart_money` at 8-plus judged coins with a 35-percent-plus win rate, a sustained ~3x edge over the market.### One cap survives: the serial rugger@@ -72,27 +72,28 @@ v1 had seven different hard ceilings. The outcome data supported exactly one, soThe fusion is a sum in log-odds space, then a sigmoid, then a fixed monotone map onto the public 0-100 ladder:```-z = intercept + sum(fitted bucket weights) + smart-money overlay-p = 1 / (1 + e^(-z)) # calibrated P(graduated or 3x+ ATH)-score = piecewise-linear map of p # anchors: 5% -> 34, 12% -> 56, 30% -> 72, 55% -> 86+z_head = intercept_head + sum(fitted bucket weights for that head) + expert priors the model cannot fit+p_head = 1 / (1 + e^(-z_head)) # one calibrated probability per head: win, rug, moon+score = piecewise-linear map of p_win # anchors: 5% -> 34, 12% -> 56, 25% -> 72, 45% -> 86score = min(score, 45 if serial-rugger creator)+rugRisk = 100 * p_rug; upside = 100 * p_moon; giveBackRisk = 100 * (1 - p_win / p_moon)```-The tier ladder is unchanged in public shape, but each boundary now states a measured probability, and production has since graded it. The rates below are the live reading over the 61,916 scored coins the market had resolved as of 2026-08-14, measured against the event the score actually predicts (graduates, or peaks at 3x or more), not against the stricter holder-honest win:+The tier ladder is unchanged in public shape, but each boundary states a measured probability of the `win` event (the coin runs and a first-sight holder is still up), and every fit grades it on launches it never saw. The rates below are the v3 bootstrap's holdout (74,211 launches, 3.2 percent base rate); the model refits on a clock, so the live table is `/api/oracle/model?view=card`:-| Tier | Score | Claims | Observed in production | n | vs base |+| Tier | Score | Claims | Observed on holdout | n | vs base || --- | --- | --- | --- | --- | --- |-| **Prime** | 86 and up | P at least 55 percent | 68.4 percent | 1,032 | 6.5x |-| **Strong** | 72 to 85 | P at least 30 percent | 31.8 percent | 968 | 3.0x |-| **Lean** | 56 to 71 | P at least 12 percent | 20.7 percent | 3,717 | 2.0x |-| **Watch** | 34 to 55 | P at least 5 percent | 12.0 percent | 11,876 | 1.1x |-| **Avoid** | below 34 | P under 5 percent | 7.5 percent | 44,323 | 0.7x |+| **Prime** | 86 and up | P at least 45 percent | 47.6 percent | 267 | 15.0x |+| **Strong** | 72 to 85 | P at least 25 percent | 40.3 percent | 852 | 12.7x |+| **Lean** | 56 to 71 | P at least 12 percent | 23.4 percent | 1,418 | 7.4x |+| **Watch** | 34 to 55 | P at least 5 percent | 10.7 percent | 2,725 | 3.4x |+| **Avoid** | below 34 | P under 5 percent | 1.8 percent | 68,949 | 0.6x |-Monotone, separated, and honest at every rung, which is why the ladder stays where it is. Every tier clears the probability it claims. The ladder lives in one place, `TIERS` and `SCORE_ANCHORS` in `api/_lib/oracle/conviction.js`, so the boundaries the API returns and the ones the UI paints can never disagree.+Monotone, separated, and honest at every rung, which is why the ladder stays where it is. Every tier clears the probability it claims, and the promotion gate refuses any refit whose populated bands stop earning at least 70 percent of what they claim. The ladder lives in one place, `TIERS` and `SCORE_ANCHORS` in `api/_lib/oracle/conviction.js` (the anchors come from the active model's `tier_probability_anchors`), so the boundaries the API returns and the ones the UI paints can never disagree.Only prime and strong are act signals. A conviction engine that likes everything is a hype engine.-Every verdict also carries compact badges the UI renders as pills: `smart-money` (three or more proven wallets in), `structure-flag` (a strongly negative fitted structure bucket), `pedigree-flag` (the rugger cap fired), `news` (riding a live story), `momentum` (that pillar alone would reach prime, subscore 86 plus), and `thin-data` (most model features unobserved). There is deliberately no `prime` badge: the card paints the tier beside the score already, so it only ever restated the pill next to it, and a badge every top card carries is decoration rather than signal. The same reasoning moved `momentum` up from 72, where it fired on 93 percent of the live feed.+Every verdict also carries compact badges the UI renders as pills: `smart-money` (three or more proven wallets in), `structure-flag` (a strongly negative fitted structure bucket), `pedigree-flag` (the rugger cap fired), `news` (riding a live story), `momentum` (that pillar alone would reach prime, subscore 86 plus), `thin-data` (most model features unobserved), `rug-risk` (the rug head at 60 percent or more), and `give-back` (give-back risk at 70 percent or more on a coin with at least 25 percent upside: a likely run that is likely to be handed straight back). There is deliberately no `prime` badge: the card paints the tier beside the score already, so it only ever restated the pill next to it, and a badge every top card carries is decoration rather than signal. The same reasoning moved `momentum` up from 72, where it fired on 93 percent of the live feed.And every verdict ships its reasons in plain language ordered by evidence strength, each quoting the observed outcome rate for its bucket. Each reason carries three fields beside the sentence, so a surface can render the evidence without parsing English back apart:@@ -100,25 +101,23 @@ And every verdict ships its reasons in plain language ordered by evidence streng| --- | --- | --- || `text` | `40+ early buyers: 80% of similar launches worked (6.8x base rate)` | The full sentence || `subject` | `40+ early buyers` | What the model saw, in trader units |-| `rate` | `80` | Percent of that bucket's training launches that were good |+| `rate` | `80` | Percent of that bucket's training launches that won, on the head the score anchors on || `lift` | `6.8` | How many times the base rate that is |`subject` is phrased per fitted bucket rather than printed from the model's own labels: "40+ early buyers", not "unique_buyers >=40". You never get a bare number, and you never get a raw one either.### The holder's number: `hitRateFor(score)`-The score ranks the odds of a *run*, judged independently of a later collapse (see PREDICTED_EVENT above). That is the right target for a ranking and the wrong one for someone deciding whether to hold, so every verdict and every feed row also carries the stricter measurement:+A score claims a probability; a holder wants to know how often that claim came true. So every verdict and every feed row also carries the measured rate behind the score:```-hit_rate fraction of resolved coins in this score band that graduated- or ran 2x or more WITHOUT ever rugging-hit_rate_lift how many times the market's own base rate that is-hit_rate_n how many resolved coins the band's rate was measured over+hit_rate fraction of held-out launches in this probability band that+ won (ran, and a first-sight holder was still up)+hit_rate_lift how many times the holdout's base rate that is+hit_rate_n how many held-out launches the band's rate was measured over```-It comes from `api/_lib/oracle/conviction-calibration.json`, an isotonic (pool-adjacent-violators) fit of the realized win rate per 10-point score band over every coin Oracle scored that the market has since resolved. At the 2026-08-14 fit: 61,916 coins, 5.4 percent base rate, and a top band (90 to 100) that held a clean 2x 26.3 percent of the time, 4.8x base. Isotonic rather than raw per-band rates because a band that dips below its neighbour on 500 samples is noise, and a ladder that steps backwards is worse than no ladder.--Refit it with `node scripts/oracle-calibrate.mjs --write`. It reads the production database when `DATABASE_URL` is set and the live `/api/oracle/backtest` endpoint otherwise (the endpoint runs the same aggregation server-side), then prints the rungs the data can actually tell apart so the tier boundaries can be checked against them. Both numbers are real and they answer different questions; the rule is that any surface showing one has to say which one it is showing.+Since v3 it comes from the active model's own holdout reliability curve, shipped with the weights (`holdout.win.reliability` in the model document): `hitRateFor(score)` converts the score back to the probability it claims, finds the reliability band that probability falls in (the bands follow the tier anchors, `0.45-1` for Prime and so on), and returns that band's observed rate, its sample size, and the holdout base rate. Reading the model's own holdout rather than a separate hand-generated file means the published rate is always the one that exact model earned on launches it had never seen, and it can never drift out of sync with the weights. The earlier `api/_lib/oracle/conviction-calibration.json` (an isotonic fit of realized production win rates per 10-point band, built on the SOL-price-dependent rug flag) is no longer read by the engine; `scripts/oracle-calibrate.mjs` still fits and prints those production rungs for checking tier boundaries against realized outcomes. Both numbers are real and they answer different questions; the rule is that any surface showing one has to say which one it is showing.## Anatomy of a score@@ -190,12 +189,12 @@ A score you cannot audit is an opinion. Oracle grades itself in public, and the**Outcome grading.** Once the data brain labels a coin's ground truth (graduated, rugged, ATH multiple), every agent action on that coin is settled: did the conviction call pay off, what was the peak multiple, what was the realized PnL. A scored coin is a win if it graduated, or reached a 2 times or greater ATH multiple without rugging and without marking below half of entry; a loss if it rugged, marked below 0.5 times, or peaked below 1.2 times — loss conditions outrank a peak-based win, because a 2× wick on a position that then went to zero was exit liquidity, not a win; flat in between. Realized PnL is marked to market as `size · (current_mc / entry_mc − 1)`. This turns the action ledger into an honest win-rate record.-**Two questions, never conflated.** Grading has to say which question it answers, because there are two and they have different answers. The **trained event** (`PREDICTED_EVENT` in `api/_lib/oracle/conviction.js`, id `spike_or_graduate`) is what the model was fitted on and what the score claims: the coin graduates, or peaks at 3x or more above its market cap at first sight. A later collapse does not undo a hit; conviction ranks the odds of a run, not the odds of a safe hold. The **holder-honest win** is the stricter, rug-aware definition in the paragraph above, and it is the right number for someone actually holding. Every surface that shows a realized rate now states which of the two it is, and the backtest ships both side by side. Presenting one as the other is what made a working engine read as a broken one.+**Two questions, never conflated.** Grading has to say which question it answers, because there are two and they have different answers. The **trained event** (`PREDICTED_EVENT` in `api/_lib/oracle/conviction.js`) is what the score head was fitted on and what the score claims. Under v3 that is id `runs_and_holds`: the coin graduates or peaks at 3x or more, AND is still worth at least what it cost at first sight, so a coin that spiked 3x and then collapsed is not a hit. (A v2 document scores on id `spike_or_graduate`, where a later collapse does not undo a hit; the engine normalises either model shape and reports which event it is predicting.) The **holder-honest win** is the rug-aware definition in the paragraph above, judged on realized production outcomes rather than the training label, and it is the right number for someone actually holding. Every surface that shows a realized rate now states which of the two it is, and the backtest ships both side by side. Presenting one as the other is what made a working engine read as a broken one.**The backtest** at `/api/oracle/backtest` joins what the engine scored against what actually happened and returns hit-rate stats per tier. Only coins with a resolved outcome count; open positions are excluded. This is the honest answer to "does it actually work," updated continuously. It publishes:- **Win rate by tier**, with a 95 percent Wilson confidence interval, for both definitions (`ci` on the holder-honest win, `spike_ci` on the trained event).-- **A calibration ladder** in bands of 10. The band's `predicted` is the sample-weighted mean of the probability each score in it actually claims, computed with `probabilityFromScore()`. This matters: the 0-100 score line is **not** a percentage (86 claims P=0.55, 34 claims P=0.05), and every table we shipped before 2026-08-14 read `score/100` as the claim, overstating the engine's own confidence by up to 4x and making a calibrated ranking look wildly overconfident. Bands are assembled from a per-score aggregate rather than a band midpoint, so the claim tracks where the coins actually sit.+- **A calibration ladder** in bands of 10. The band's `predicted` is the sample-weighted mean of the probability each score in it actually claims, computed with `probabilityFromScore()`. This matters: the 0-100 score line is **not** a percentage (86 claims P=0.45, 34 claims P=0.05), and every table we shipped before 2026-08-14 read `score/100` as the claim, overstating the engine's own confidence by up to 4x and making a calibrated ranking look wildly overconfident. Bands are assembled from a per-score aggregate rather than a band midpoint, so the claim tracks where the coins actually sit.- **A Brier score** (`brier_of` names the event, the trained one), computed per exact score against its own claimed probability rather than against a band midpoint, so it is exact. Lower is better; 0.25 is a coin flip.- **The edge multiple**, prime's rate over the base rate, and a monotonicity check. The ladder check counts an inversion only when two bands' 95 percent intervals are **disjoint**: a visible dip inside overlapping intervals is sampling noise, and the previous check both tolerated real inversions and reported `monotonic: true` over them.@@ -203,7 +202,7 @@ During a database outage the endpoint answers `503` rather than an empty record,That rule is the whole Oracle read surface, not one endpoint. `/api/oracle/feed`, `/categories`, `/agent-stats`, `/follow`, `/movers`, `/signal`, `/stats`, `/history`, and the `/social` ingest all separate a connectivity failure from an ordinary SQL fault: the first propagates as `503` with a `Retry-After` and is never cached, the second still degrades to the documented empty answer. The distinction matters because these responses get CDN-cached for 60 to 120 seconds, so a blip lasting seconds used to pin "nothing is moving", "nobody is armed", or "no plays right now" on the product for minutes after the database recovered. `/api/oracle/og` follows the same rule in its own shape: a card built from a failed read still renders (a social scraper needs an image back), but it is served `no-store` so the next scrape re-reads a recovered database instead of caching "Not yet scored" on a Prime coin for 15 minutes. The contract is pinned in `tests/oracle/api-db-outage.test.js`.-**The realized-hit-rate calibration.** The fitted model answers "what fraction of launches like this one spike or graduate". A user reading a card wants "of the coins Oracle already scored at 99, how many actually won". Nothing reconciled those two, so a card reading conviction 99 quoted a training-label probability above 95 percent for a band that realized 26 percent. `scripts/oracle-calibrate.mjs` closes the gap: it measures the realized rug-aware win rate per score band over resolved production coins, smooths it into a monotone ladder with pool-adjacent-violators (isotonic regression), and writes `api/_lib/oracle/conviction-calibration.json`. `hitRateFor()` then serves that realized rate next to every score, and the public tier boundaries sit on the plateaus this fit exposes. Run it bare to fit and report, `--write` to update the shipped JSON. It reads the production database when `DATABASE_URL` is set and otherwise the live `/api/oracle/backtest`, which runs the same aggregation server-side, so neither path invents a number.+**The realized-hit-rate calibration.** The fitted model answers "what fraction of launches like this one spike or graduate". A user reading a card wants "of the coins Oracle already scored at 99, how many actually won". Nothing reconciled those two, so a card reading conviction 99 quoted a training-label probability above 95 percent for a band that realized 26 percent. `scripts/oracle-calibrate.mjs` measures that: the realized rug-aware win rate per score band over resolved production coins, smoothed into a monotone ladder with pool-adjacent-violators (isotonic regression) and written to `api/_lib/oracle/conviction-calibration.json`, so the public tier boundaries can be checked against the plateaus it exposes. Since v3 the rate printed next to every score (`hitRateFor()`) comes from the active model's own holdout instead of that file, because the file's win definition was built on the SOL-price-dependent rug flag. Run the script bare to fit and report, `--write` to update the JSON. It reads the production database when `DATABASE_URL` is set and otherwise the live `/api/oracle/backtest`, which runs the same aggregation server-side, so neither path invents a number.**A third question: what the fleet actually banked.** `/api/cron/oracle-calibrate` (Cloud Scheduler) joins conviction to the fleet's *realized PnL* on mints it really traded, buckets by conviction band, and writes `oracle_calibration`. A win here is a positive realized PnL on a real fill, which is neither the trained event nor the site's rug-aware win: exit timing belongs to the fleet, so a gap between this table and `/api/oracle/backtest` is expected rather than a bug. Each band carries a bounded `correction_factor` (observed over claimed, clamped to 0.7-1.3, and pinned at 1.0 until the band has enough real trades). That factor is deliberately **not** written back onto the canonical `oracle_conviction` score: the calibration is measured against that score, so mutating it would feed into its own measurement and oscillate. It is exposed at `GET /api/oracle/calibration` and applied where it belongs, in the sniper optimizer's Rule O, which tunes each arm's entry threshold toward the band that realized wins.@@ -231,7 +230,7 @@ This is where the engine earns its keep. One score, many consumers.**The coin pages.** Every Oracle coin page (`/oracle/coin/<mint>`) renders in the markets-hub design, the same editorial system as `/coin/bitcoin`: breadcrumbs, a coin header with the live price and 24h/7d change chips, a conviction card with the score dial and four pillar bars, and stacked full-width sections. It fuses conviction with a live market intel aggregator that fans out to six real sources in parallel: DexScreener, the pump.fun API, GeckoTerminal, GoPlus, Birdeye, and CoinGecko. Price, liquidity, FDV, bonding curve progress, holder count, top ten concentration, mint and freeze authority, all in one view, every number traced to a live upstream. Each source is isolated, so one being down degrades that slice to null instead of failing the page. A Launch Intelligence section brings the Coin Radar engine's first-90-seconds read onto the same page: quality score, organic versus bundle, risk flags, the full signal breakdown, smart-money buyers, and the top-trader ledger. It also shows the who-is-in breakdown: every early wallet labeled by archetype and track record. That trader-classification surface is what the product is built around. The price chart keeps the TradingView-grade DexScreener candles embed alongside a native line view and an agent-trades view that plots every three.ws agent buy and sell on the series.-**What the verdict card says out loud.** A big dial reading 100 next to a chart that already collapsed is not a wrong score, it is an unlabelled one, so the conviction card carries two lines the dial cannot say by itself. Directly under the score, the odds line quotes the band's realized rug-aware rate instead of the score: "26% of calls in the 90-100 band have won (n=792), 4.8x the 5% a random launch wins", followed by when the call was made relative to the coin first surfacing ("Scored 54s after this coin surfaced") and the one sentence that resolves the whole confusion, that the score ranks the odds of a 3x run or graduation and not the odds of a safe hold. Below it, once the market has resolved the coin, a **Since the call** strip states the ground truth in the order a holder reads it: peak multiple, whether it graduated or rugged, and what it is worth now ("peak 6.7x · rugged · now $2.2K"). Both lines are rendered server-side in `api/oracle-share.js` and refilled by `public/oracle-coin.js`, so a link pasted into a chat shows them in the preview rather than a bare triumphant number; the share description carries the same clause ("since: ran 6.7x, then rugged"). The drawer's one-line take leads with the result for the same reason: "It ran to 6.7x and then rugged." before it repeats what Oracle called. On the feed at `/oracle`, each card carries the compact version of that strip as an outcome chip next to its odds chip, so a resolved coin never sits in the board looking like a live call.+**What the verdict card says out loud.** A big dial reading 100 next to a chart that already collapsed is not a wrong score, it is an unlabelled one, so the conviction card carries two lines the dial cannot say by itself. Directly under the score, the odds line quotes the measured rate behind the score instead of the score itself, from `hitRateFor()`: "48% of calls in the 0.45-1 band have won (n=267), 15.0x the 3% a random launch wins" (the band is the probability band the score claims, and the rate is what the active model's holdout observed there), followed by when the call was made relative to the coin first surfacing ("Scored 54s after this coin surfaced") and the one sentence that resolves the whole confusion, that the score ranks the odds of a 3x run or graduation and not the odds of a safe hold. Below it, once the market has resolved the coin, a **Since the call** strip states the ground truth in the order a holder reads it: peak multiple, whether it graduated or rugged, and what it is worth now ("peak 6.7x · rugged · now $2.2K"). Both lines are rendered server-side in `api/oracle-share.js` (a GET-only surface; when pump.fun does not answer, the coin's identity, symbol, name, image, market cap and graduation state, comes from DexScreener's pair listing so the card still names the coin) and refilled by `public/oracle-coin.js`, so a link pasted into a chat shows them in the preview rather than a bare triumphant number; the share description carries the same clause ("since: ran 6.7x, then rugged"). The drawer's one-line take leads with the result for the same reason: "It ran to 6.7x and then rugged." before it repeats what Oracle called. On the feed at `/oracle`, each card carries the compact version of that strip as an outcome chip next to its odds chip, so a resolved coin never sits in the board looking like a live call.## The x402 layer: intel with a price tag@@ -315,7 +314,7 @@ GET https://three.ws/api/oracle/trades?mint=<mint>- Score time series at `/api/oracle/history`, biggest conviction moves at `/api/oracle/movers`, accuracy stats at `/api/oracle/backtest`, proven calls at `/api/oracle/wins`, agent rankings at `/api/oracle/leaderboard`.- Global KPIs, per-category intel, symbol search, a single agent's record, and the global action feed at `/api/oracle/stats`, `/categories`, `/search`, `/agent-stats`, and `/activity`.- Realized calibration per conviction band at `/api/oracle/calibration`: the fleet's actual win rate from real fills, next to what the band predicted, plus the bounded correction factor the scorer applies.-- A dynamic 1200x630 OpenGraph conviction card (SVG) for sharing a coin at `/api/oracle/og`.+- A dynamic 1200x630 OpenGraph conviction card (SVG) for sharing a coin at `/api/oracle/og`. Its live market cap reads pump.fun first (with one retry, honouring `Retry-After`) and falls through to the shared multi-source market reader (Birdeye, DexScreener, GeckoTerminal) when pump.fun does not answer.The write endpoints. Two are auth-scoped to the agent's owner: `GET·POST /api/oracle/watch` reads or arms an agent's watch config with server-side validation clamping every limit, and `POST /api/oracle/test-alert` sends a test alert. The clamps only ever move a number toward safety: a size above the ceiling is lowered, but arming `mode: "live"` with a `per_trade_sol` under the 0.001 SOL floor, or a `max_daily_sol` smaller than one trade, is a 400 rather than a silent round-up into real spending. Simulate runs keep the forgiving clamps. Two are public and IP rate-limited instead: `POST·DELETE /api/oracle/follow` subscribes a Telegram chat to an agent's signals (the chat id the caller supplies is the identity, so there is no session to scope to), and `POST /api/oracle/social` ingests tweets to additively boost virality (never downgrades an LLM read).@@ -355,16 +354,16 @@ Every coin watched sharpens the priors. Every graded outcome tunes the calibrati## PhD appendix: Oracle as a calibrated scoring classifier-Let a launch be a feature vector `x`. Since v2 (2026-08-09), Oracle is a bucketed logistic model: each feature `j` is discretized by fixed empirical bin edges into a one-hot `b_j(x)`, each bin carries a fitted weight `w_{j,b}`, and+Let a launch be a feature vector `x`. Since v2 (2026-08-09), Oracle is a bucketed logistic model: each feature `j` is discretized by fixed empirical bin edges into a one-hot `b_j(x)`, and since v3 (2026-08-28) each bin carries one fitted weight `w^h_{j,b}` per head `h ∈ {win, rug, moon}` over the same design matrix:```-z(x) = w_0 + Σ_j w_{j, b_j(x)} + o(x) # o(x): the smart-money overlay (documented priors)-p(x) = σ(z(x)) = 1 / (1 + e^(−z(x))) # calibrated P(good | x)-s(x) = min( m(p(x)), c(x) ) # m: fixed monotone piecewise-linear map to [0,100]- # c: 45 iff serial-rugger creator, else 100+z_h(x) = w^h_0 + Σ_j w^h_{j, b_j(x)} + o(x) # o(x): expert priors the model cannot fit+p_h(x) = σ(z_h(x)) = 1 / (1 + e^(−z_h(x))) # calibrated P(h | x)+s(x) = min( m(p_win(x)), c(x) ) # m: fixed monotone piecewise-linear map to [0,100]+ # c: 45 iff serial-rugger creator, else 100```-with `good = graduated ∨ ATH ≥ 3×`, fitted by SGD on the labeled outcome set (L2-regularized, deterministic seed, time-ordered rows; `scripts/oracle-fit.mjs`). `m` is anchored so the public tier boundaries land on fixed probabilities (34 ↦ 0.05, 56 ↦ 0.12, 72 ↦ 0.30, 86 ↦ 0.55). Evaluation is a strict temporal split: train on the oldest 75 percent, report AUC, precision-at-depth, and per-band reliability on the newest 25 percent. Calibration measures the gap between `p(x)` and reality out of sample.+with `hold = ATH_multiple × (last_mc / ath_mc)` (both dollar figures from one reading, so the SOL price cancels), `moon = graduated ∨ ATH ≥ 3×`, `rug = ¬graduated ∧ hold ≤ 0.5`, `win = moon ∧ hold ≥ 1`, fitted by SGD on the labeled outcome set (L2-regularized, deterministic seed, time-ordered rows, label rule version 2 only; `api/_lib/oracle/fit.js`, shared by `scripts/oracle-fit.mjs` and the refit cron). Each fitted weight is then shrunk toward zero by `n / (n + 200)`, `n` being the rows behind its bucket, so a 34-row bucket cannot reverse a verdict on its own. `m` is anchored so the public tier boundaries land on fixed probabilities of `win` (34 ↦ 0.05, 56 ↦ 0.12, 72 ↦ 0.25, 86 ↦ 0.45). Evaluation is a strict temporal split: train on the oldest 75 percent, report AUC, precision-at-depth, and per-band reliability on the newest 25 percent, for every head. Calibration measures the gap between `p(x)` and reality out of sample.The calibration objects:@@ -373,7 +372,7 @@ The calibration objects:- **Wilson interval**: for `w` wins in `n` resolved coins, the 95 percent Wilson score interval (z = 1.96, z² = 3.8416) is `centre = (p + z²/2n) / (1 + z²/n)` and `margin = z·√((p(1−p) + z²/4n) / n) / (1 + z²/n)` with `p = w/n`. Unlike the normal approximation `p ± z·√(p(1−p)/n)`, it stays inside [0,1], doesn't collapse to zero width at p=0 or p=1, and behaves correctly for the small `n` that young backtests have. It is the difference between an honest "we don't know yet" and a dishonest "0 percent ± 0 percent."- **Monotonicity and edge**: require `ŷ` non-decreasing in the score bin (within tolerance); define edge multiple `= P(win | prime) / P(win | any)` and lift as the difference, both reported with their CIs.-The improvement path, formally. v2 delivered the first two upgrades the v1 appendix promised: the weights are now fitted by maximizing regularized log-likelihood on resolved outcomes, and the published score is a fixed monotone map of a calibrated probability. What remains open, in order of expected value: (1) refit cadence, ideally automated once the labeled set's growth is stable, with a champion/challenger holdout gate so a refit never silently regresses; (2) interaction terms or shallow trees over the same buckets, since the current model is additive and the strongest observed patterns (concentration crossed with buyer count) are plausibly interactive; (3) fitting the smart-money overlay once the widened proven-wallet ledger accumulates enough judged appearances; (4) survival-style labels (time-to-rug) instead of the binary good, so the engine can price exit windows and not just entries.+The improvement path, formally. v2 delivered the first two upgrades the v1 appendix promised: the weights are fitted by maximizing regularized log-likelihood on resolved outcomes, and the published score is a fixed monotone map of a calibrated probability. v3 delivered two more: an automated refit (`/api/cron/oracle-refit`) behind a champion/challenger holdout gate (a candidate ships only if every epoch ran, the scoring head's AUC is at least 0.70 and beats the incumbent by at least 0.004, no other head fell by more than 0.01, no more than three features were lost, and every populated band still earns 70 percent of what it claims; refused candidates are kept in `oracle_model_versions` with the reason), and the smart-money evidence fitted as a feature instead of an overlay. What remains open, in order of expected value: (1) interaction terms or shallow trees over the same buckets, since the model is additive and the strongest observed patterns (concentration crossed with buyer count) are plausibly interactive; (2) survival-style labels (time-to-rug) instead of the binary heads, so the engine can price exit windows and not just entries.References and further reading. Wilson (1927), *Probable inference, the law of succession, and statistical inference*. Brier (1950), *Verification of forecasts expressed in terms of probability*. Platt (1999), probabilistic outputs for SVMs (Platt scaling). Zadrozny and Elkan (2002), isotonic calibration. Niculescu-Mizil and Caruana (2005), *Predicting good probabilities with supervised learning*.diff --git a/docs/overlay-audit.md b/docs/overlay-audit.mdindex fceeacbbf..6bfdc01b5 100644--- a/docs/overlay-audit.md+++ b/docs/overlay-audit.md@@ -161,4 +161,4 @@ only worth calling from a test.- [`tests/e2e/mobile-helper-overlays.spec.js`](../tests/e2e/mobile-helper-overlays.spec.js): the phone-width geometry, measured in a real browser- `npm run audit:mobile-touch`: touch-target sizes, the other half of "can I actually hit this"- `npm run audit:a11y`: keyboard and screen-reader coverage on the top pages-- `npm run snapshot`: the daily full-page visual record of every route+- `npm run snapshot`: the daily full-page visual record of every public route (`--authed` replays the `audit:web:login` session and widens it to the signed-in pages, writing to `reports/ui-shots/` instead of `snapshots/`)diff --git a/docs/pay-skills-listing.md b/docs/pay-skills-listing.mdindex a70d00abe..a6910c33d 100644--- a/docs/pay-skills-listing.md+++ b/docs/pay-skills-listing.md@@ -4,7 +4,7 @@**Discovery:** https://three.ws/.well-known/x402.json**OpenAPI:** https://three.ws/openapi.json**MCP:** https://three.ws/api/mcp-**Networks:** Base mainnet (USDC), Arbitrum One (USDC, model-check + mint-to-mesh only), Solana mainnet (USDC)+**Networks:** Solana mainnet (USDC, leads every accepts list), Base mainnet (USDC), Arbitrum One (USDC, model-check only)**Protocol:** x402 v2 (HTTP 402 Payment Required)## Overview@@ -12,7 +12,9 @@three.ws is an agent-first 3D model platform. Paid REST endpoints cover glTF/GLB modelvalidation, Solana token visualization, Pump.fun agent analytics, on-chain identityverification, and a Claude-backed growth-analysis power. All endpoints settle in USDC-on Base / Arbitrum / Solana mainnet. The MCP server exposes the same surface as+on Solana mainnet, with Base (and Arbitrum for model-check) as the alternative EVM+rails; Solana is the first accept in every 402 challenge, so a client that takes+the first accept settles there. The MCP server exposes the same surface asJSON-RPC tools.## Paid Endpoints@@ -25,7 +27,7 @@ are the source of truth and match what the 402 challenges advertise; verify with|---|---|---|---|| `/api/mcp` | POST | $0.001 | MCP 2025-06-18 Streamable HTTP — 3D model tools + Solana agent data as JSON-RPC 2.0 || `/api/x402/model-check` | GET | $0.001 | Fetch a glTF/GLB from a URL, return vertex/triangle counts, materials, textures, animations, extensions, and optimization hints. CDP-Bazaar-cataloged. |-| `/api/x402/mint-to-mesh` | GET | $0.001 | Pass a Solana SPL mint, get a binary glTF (GLB) cube themed for that token (color + texture derived from on-chain metadata). CDP-Bazaar-cataloged. |+| `/api/x402/mint-to-mesh` | GET | $0.001 | Pass a Solana SPL mint, get a binary glTF (GLB) cube themed for that token (color + texture derived from on-chain metadata: the Token-2022 metadata extension when the mint carries one, else the Metaplex PDA). CDP-Bazaar-cataloged. || `/api/x402/symbol-availability` | GET | $0.001 | Pre-launch ticker collision check against three.ws's pump.fun mint index; returns exact and trigram-similar matches || `/api/x402/skill-marketplace` | GET | $0.001 | List active skill listings and prices across all three.ws agents; filter by skill name to find the cheapest provider || `/api/x402/permit2-paid-demo` | GET | $0.001 | Permit2 + EIP-2612 gas-sponsoring demo (Base only). Forces the gasless Permit2 path for fresh wallets holding USDC but zero ETH. Listed only when CDP credentials are configured. |diff --git a/docs/play-hardening.md b/docs/play-hardening.mdindex eeaef42c1..892f587ee 100644--- a/docs/play-hardening.md+++ b/docs/play-hardening.md@@ -77,7 +77,7 @@ The app bundle is not on screen yet while the boot loader is up, so the loader h- `name` is capped at 28 characters and `symbol` at 12, cut on a word boundary.- Anything unexpected throws into a `catch` that leaves the generic loader exactly as it shipped.-The art has a designed failure path in both places it appears. In the loader, a monogram sits under the `<img>` and the image only fades in on `load`; an `error` removes the `<img>` and leaves the monogram. In the world, the HUD banner's `.cc-coin-img` does the same against `.cc-coin-mono` ([src/game/coincommunities-ui.js](../src/game/coincommunities-ui.js)). The 3D totem and jumbotron already degraded to text-only on a failed `TextureLoader` fetch. This matters on venue wifi, where the IPFS gateway behind `/api/img` is the single most likely thing to fail while everything else about the world works.+The art has a designed failure path in both places it appears. In the loader, a monogram sits under the `<img>` and the image only fades in on `load`; an `error` removes the `<img>` and leaves the monogram. In the world, the HUD banner's `.cc-coin-img` does the same against `.cc-coin-mono` ([src/game/coincommunities-ui.js](../src/game/coincommunities-ui.js)). The 3D totem and jumbotron already degraded to text-only on a failed `TextureLoader` fetch. This matters on venue wifi, where the IPFS gateway behind `/api/img` is the single most likely thing to fail while everything else about the world works. A single gateway is also no longer the only try: `uriCandidates()` in [src/ipfs.js](../src/ipfs.js) expands an `ipfs://` source, or a URL that already names one gateway, into one candidate per gateway in preference order, and each fetch is bounded at 8 s, so one rate-limited gateway degrades to the next rather than to the monogram.The loader also sets a provisional `document.title` from the link and stashes the original in `documentElement.dataset.lobbyTitle`; `_setTabTitle()` in [src/game/coincommunities.js](../src/game/coincommunities.js) replaces it with the resolved coin on entry and restores the stashed original on leave, so the two writers never fight and the localised title is never re-spelled in JS.@@ -237,6 +237,11 @@ npx vitest run tests/play-deeplink-safety.test.js tests/play-deeplink-identity.t# coin art and GLBs, a dead auth gate, an ad blocker, a total API outage.npm run audit:play-failures # local dev serverBASE_URL=https://three.ws npm run audit:play-failures+# A scenario the harness itself broke (a host transport reset, a starved+# browser) is retried up to ATTEMPTS times (default 4) with a growing backoff+# and reported NOT RUN if it never runs, never counted as a /play defect; the+# sweep abandons itself if the origin under test stops answering. Authed+# scenarios use AUDIT_EMAIL / AUDIT_PASSWORD (see docs/ops/page-audit.md).# Everything else that touches the surface.npx vitest run tests/play-gate.test.js tests/play-pass.test.js \diff --git a/docs/procedural-animation.md b/docs/procedural-animation.mdindex 87a228ba4..963aa3a0b 100644--- a/docs/procedural-animation.md+++ b/docs/procedural-animation.md@@ -120,7 +120,7 @@ Bone lengths are preserved exactly; the solve only ever rotates.| Surface | Layer | Where ||---|---|---|| Corner walk companion | Look-at (cursor gaze) | [`walk-sdk/src/companion.js`](../walk-sdk/src/companion.js) `_updateGaze()` |-| The walkaround world (`/walk`) | Foot planting on terrain | [`src/walk.js`](../src/walk.js) `rebuildFootPlant()` |+| The walkaround world (`/walk`) | Foot planting on terrain | [`src/walk.js`](../src/walk.js) `rebuildFootPlant()` (in AR mode the ground callback returns the flat `GROUND_Y`, so the layer stands down) || `/walk` NPCs | Look-at (they watch the player) | [`src/walk-npcs.js`](../src/walk-npcs.js) `_updateGaze()` || Agent avatars (`AgentAvatar`) | Look-at (`setLookTarget`, `LOOK_AT`) | [`src/agent-avatar.js`](../src/agent-avatar.js) `_applyLookTarget()` || `<agent-3d>` web component | Look-at (`lookAt()` public API) | [`src/runtime/scene.js`](../src/runtime/scene.js) `lookAt()` |@@ -154,6 +154,8 @@ The gaze is a **standing state**, not a one-off pose write: it re-applies afterEvery NPC watches the player within 14 m — wider than the 4 m greeting range, because noticing someone happens long before greeting them. A wanderer can glance over without breaking stride, since the gaze is an overlay on the walk cycle rather than a replacement for it. Past the clamp the layer releases rather than pinning the head, so an NPC the player has walked behind simply returns to its clip.+The NPC gaze report (`gazeReport(target)` on the object `createWalkNpcs()` returns) lists each NPC's `dist`, `alignment` (null when the rig exposes no head chain), `tracking` (true while a headed rig is inside the 14 m gaze range), and `headYaw`, which is what the Playwright checks read to prove a gaze actually moved a head.+---## Adding a layerdiff --git a/docs/pump-claims-channel.md b/docs/pump-claims-channel.mdindex 8db65e6ef..1c126a46c 100644--- a/docs/pump-claims-channel.md+++ b/docs/pump-claims-channel.md@@ -98,8 +98,10 @@ State lives in `app_settings` under `pump_claims_push_telegram`:Cloud Run request deadline is shorter than a full paced run) resumes at thenext claim instead of repeating delivered ones.- **A DB lock** (`pump_claims_push_lock`, 240s TTL) stops overlapping ticks from- double-posting. Every outbound request is bounded well under that TTL, which- is what keeps the lock's guarantee true.+ double-posting. Every outbound request is bounded well under that TTL (each+ Telegram `sendMessage` goes through the shared `fetchUpstream` with a 10 s+ deadline and at most two attempts), which is what keeps the lock's guarantee+ true.- **All message fields are HTML-escaped.** Claim data is third-party on-chaindata; unescaped text could otherwise smuggle a clickable link posted under theplatform bot's identity.diff --git a/docs/pump-fun-mcp-edge.md b/docs/pump-fun-mcp-edge.mdindex 4e2758f1b..7db552ce5 100644--- a/docs/pump-fun-mcp-edge.md+++ b/docs/pump-fun-mcp-edge.md@@ -8,30 +8,38 @@ Mirror of the primary `/api/pump-fun-mcp` endpoint (served by the Cloud Run app| :--- | :--- || `workers/pump-fun-mcp/worker.js` | CF Workers fetch handler implementing the MCP Streamable HTTP transport || `workers/pump-fun-mcp/wrangler.toml` | Wrangler config (`name`, `main`, `compatibility_date`) |+| `workers/pump-fun-mcp/README.md` | Full config table and the verified run, build, and deploy commands || `src/pump/mcp-tools.js` | Shared tool registry imported by both the Cloud Run and Workers handlers |+| `tests/workers/pump-fun-mcp-worker.test.js` | Covers the worker's MCP surface (`npx vitest run tests/workers/pump-fun-mcp-worker.test.js`) |## Deploy```shcd workers/pump-fun-mcp-npx wrangler deploy+npx wrangler@4 deploy```+`wrangler` is not a repo dependency, so it is invoked through `npx`.+## Secrets-Set the following with `wrangler secret put <NAME>`:+Set the following with `npx wrangler@4 secret put <NAME>` (or `--var NAME:VALUE` for a local `wrangler dev` run). Everything is optional:| Name | Required | Description || :--- | :--- | :--- |-| `SOLANA_RPC_URL` | No | Mainnet RPC endpoint (defaults to public endpoint) |-| `SOLANA_RPC_URL_DEVNET` | No | Devnet RPC endpoint (defaults to public endpoint) |+| `SOLANA_RPC_URL` | No | Primary mainnet RPC endpoint (defaults to the public endpoint) |+| `SOLANA_RPC_FALLBACKS` | No | Comma-separated mainnet failover endpoints, tried in order after the primary (same var name the three.ws deployment uses) |+| `SOLANA_RPC_URL_DEVNET` | No | Primary devnet RPC endpoint (defaults to the public endpoint) |+| `SOLANA_RPC_FALLBACKS_DEVNET` | No | Comma-separated devnet failover endpoints || `PUMPFUN_BOT_URL` | No | Upstream indexer MCP endpoint; indexer-backed tools return -32004 without it || `PUMPFUN_BOT_TOKEN` | No | Bearer token for the indexer endpoint |+Every on-chain tool walks the configured chain (primary, then each fallback) until one endpoint answers; the public endpoint is used only when nothing is configured, never as a silent downgrade. A tool-level verdict (invalid mint, account genuinely absent) propagates immediately instead of burning the chain, and a provider that is down, rate-limiting, or blocking the egress IP surfaces as `-32004`. `get_token_details` reads name, symbol, and URI from the Token-2022 `TokenMetadata` extension for Token-2022 mints (what pump.fun launches today) and falls back to the legacy Metaplex metadata PDA otherwise.+## Local dev```sh-npx wrangler dev workers/pump-fun-mcp/worker.js --local+npx wrangler@4 dev workers/pump-fun-mcp/worker.js --local# Test tools/list:curl -s http://localhost:8787 \-H 'content-type: application/json' \diff --git a/docs/pumpfun-program/UPSTREAM-pumpswap-virtual-quote-reserves.md b/docs/pumpfun-program/UPSTREAM-pumpswap-virtual-quote-reserves.mdindex f1eaa4e60..d231f443e 100644--- a/docs/pumpfun-program/UPSTREAM-pumpswap-virtual-quote-reserves.md+++ b/docs/pumpfun-program/UPSTREAM-pumpswap-virtual-quote-reserves.md@@ -175,6 +175,8 @@ limit).A `0` returned by any impact helper means "unknown", never "safe".+An RPC outage is kept distinct from an exhausted pool. When the vault and mint accounts behind a pool cannot be read because the Solana RPC lane is down, `getAmmPoolState` throws a retryable `rpc_unavailable` error (HTTP 503 with a `Retry-After`) instead of a reserve figure, and `api/agents/solana-trade.js` answers `503 rpc_unavailable`; a depth refusal is only ever issued from reserves that were actually read.+Regression coverage lives in[`tests/agent-sniper-amm-exit.test.js`](../../tests/agent-sniper-amm-exit.test.js)and [`tests/pump-swap-quote.test.js`](../../tests/pump-swap-quote.test.js): thediff --git a/docs/remix.md b/docs/remix.mdindex 8f03bfd78..5fff42770 100644--- a/docs/remix.md+++ b/docs/remix.md@@ -70,6 +70,13 @@ an iteration is a normal owned creation: gallery-listed, downloadable, andeligible to publish as remixable. It carries no payment surface of its own —iteration itself stays free.+`/api/forge` holds the connection open while a saturated generator queues the+job, so an accept can legitimately take minutes. `/api/forge-iterate` therefore+waits up to `FORGE_ITERATE_SUBMIT_MS` (default 60000) for it, and when that+window runs out it answers the way the generator itself would, `429 busy` with+`retryAfter: 20`, rather than a `504` that both iterate UIs used to read as a+wording problem and answer with "rephrase your instruction".+## Publish a model as remixableYou must own the creation (same `x-forge-client` that generated it). Only finished@@ -165,6 +172,14 @@ Response (after settlement):no payout wallet, or the royalty is below the 0.01 USDC dust floor, `paid` is`false` with an honest `reason` — never a fake pending.+When the source belongs to a signed-in creator (anonymous `forge_creations`+rows have no `user_id`), a settled remix also publishes a `remix` event to that+creator's notification feed, folding "you were remixed" and the royalty outcome+into one line, and awards the first-remix-received badge once. Both are+fire-and-forget and never delay the response. A validation failure (bad source+id, empty instruction) is answered before settlement with the error's own+status and code, so the buyer is never charged for a request that could not run.+### Split math + capsPure and unit-tested (`api/_lib/remix-royalty.js`,diff --git a/docs/reputation.md b/docs/reputation.mdindex 54d326e8a..76e065adc 100644--- a/docs/reputation.md+++ b/docs/reputation.md@@ -74,6 +74,8 @@ The `ReputationPanel` class ([src/erc8004/reputation-panel.js](../src/erc8004/reRecent vouches are loaded by querying `FeedbackSubmitted` event logs for the last ~50,000 blocks (~7 days on most L2s). If the RPC rejects the log query (common on free-tier endpoints), the panel degrades gracefully — it still shows the aggregate stats but omits the individual review list.+Reads go through `readProvider(chainId)` from [src/erc8004/chain-meta.js](../src/erc8004/chain-meta.js): every keyless public node listed for the chain becomes a pinned provider and they are combined in an ethers `FallbackProvider` with quorum 1, so the first healthy node answers and a stalled or rate-limited one is passed over after four seconds instead of blanking the panel. The USD figure printed beside a stake amount comes from `getEthPriceUsd()` ([src/shared/usd-price.js](../src/shared/usd-price.js)), which walks four price feeds with per-provider cooldowns; a throttled feed leaves the ETH amount in place and only drops the USD hint.+### Full reputation dashboardThe `ReputationDashboard` class ([src/reputation-ui.js](../src/reputation-ui.js)) is used on the standalone [/reputation](https://three.ws/reputation) page. It shows:@@ -81,7 +83,9 @@ The `ReputationDashboard` class ([src/reputation-ui.js](../src/reputation-ui.js)- Review count, average rating, time since last review- Up to 10 recent reviews with inline transaction links- A submit form for leaving a new review (wallet connection handled inline)-- Optimistic updates: your review appears immediately as "Pending" while the transaction confirms, then is replaced with the confirmed on-chain data+- Optimistic updates: your review appears immediately as "Pending" while the transaction confirms, then is replaced with the confirmed on-chain data. If a confirmation poll fails, the page says so ("Could not confirm your review on-chain; refresh to check.") rather than leaving the pending row looking stuck.++The dashboard reads through `getEvmProvider(chainId)` from [src/shared/evm-rpc-fallback.js](../src/shared/evm-rpc-fallback.js): the same-origin `/api/evm-rpc?chainId=N` proxy first (which inherits the server's keyed and curated RPC failover), then the chain's keyless public hosts, combined into one `FallbackProvider`. There is no per-chain RPC URL hardcoded in the dashboard any more; one dead public endpoint no longer reads as "chain unsupported".### Via the SDK@@ -184,6 +188,8 @@ Contract addresses are the same on every supported EVM chain (CREATE2 determinis| Mainnet (Base, Arbitrum, Optimism, Ethereum, Polygon, and more) | `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63` || Testnet (Base Sepolia, Arbitrum Sepolia, Optimism Sepolia, and more) | `0x8004B663056A597Dffe9eCcC1965A193B7388713` |+One caveat, recorded in the comments of `abi.js`: the canonical addresses run the ERC-8004 reference implementation, not the three.ws source above. An `eth_call` sweep on 2026-08-15 found that deployment answering `readFeedback` / `getClients` on Base and Base Sepolia and reverting on every selector in `contracts/src/ReputationRegistry.sol` (`submitFeedback`, `getReputation`, `getFeedbackRange`, and the stake functions). The ABI and SDK helpers on this page match the three.ws source, so use them against an instance you deploy from `contracts/src` yourself; against the canonical addresses those calls revert.+---## Reputation in agent discoverydiff --git a/docs/risk-acknowledgment.md b/docs/risk-acknowledgment.mdindex 80d3fa427..7d5137d9f 100644--- a/docs/risk-acknowledgment.md+++ b/docs/risk-acknowledgment.md@@ -23,12 +23,20 @@ simply doesn't run; everything else on the platform keeps working.older version no longer count.- **Recorded server-side.** On accept, the client fires`POST /api/legal/risk-ack` ([`api/legal/risk-ack.js`](../api/legal/risk-ack.js)),- which writes a `risk-ack-accept` row into `audit_log` — user id when signed+ which writes a `risk-ack-accept` row into `audit_log`: user id when signedin (null otherwise), disclosure version, the feature context, path, IP, and- user agent. The `audit-log-cleanup` cron prunes `audit_log` at 365 days but- exempts `risk-ack-accept` (and `tos-accept`) rows, so acceptance records- persist indefinitely. The write is fire-and-forget: a failed network call- never blocks the user's accepted state.+ user agent. The handler awaits that write and answers+ `200 { ok: true, recorded }`, where `recorded` says whether the row actually+ landed; a dropped write still answers 200 because the user did accept. It+ imports `RISK_ACK_VERSION` from the client gate and rejects any `version`+ outside `1..RISK_ACK_VERSION` with `400 invalid_version`, so nobody can+ record acceptance of a revision that does not exist yet; an unreadable body+ gets its real cause (`413 payload_too_large`, `415 unsupported_media_type`,+ or `400 bad_request`) instead of a version complaint. The+ `audit-log-cleanup` cron prunes `audit_log` at 365 days but exempts+ `risk-ack-accept` (and `tos-accept`) rows, so acceptance records persist+ indefinitely. The client's call is fire-and-forget (`keepalive`, errors+ swallowed): a failed network call never blocks the user's accepted state.- **Devnet stays friction-free.** Surfaces that know their network only gatewhen it isn't `devnet`. Simulation modes (e.g. Oracle arm's simulate mode)are never gated.diff --git a/docs/robinhood-chain-markets.md b/docs/robinhood-chain-markets.mdindex 6c9013917..13f66b75a 100644--- a/docs/robinhood-chain-markets.md+++ b/docs/robinhood-chain-markets.md@@ -49,7 +49,7 @@ Free, keyless, real data only:| Endpoint | Returns || --- | --- || `GET /api/v1/robinhood/chain` | Block height, gas, tx/address counts, chain TVL + 90-day history |-| `GET /api/v1/robinhood/stocks` | Every Stock Token: NAV, DEX price, premium, volume, liquidity (`?q=`, `?sort=`) |+| `GET /api/v1/robinhood/stocks` | Every Stock Token: NAV, DEX price, premium, volume, liquidity (`?q=`; `sort`: `symbol` \| `volume` \| `liquidity` \| `premium` \| `price`; `dir`: `asc` \| `desc`, numeric columns default highest-first, symbol A-Z; rows with no value for the column sort last either way) || `GET /api/v1/robinhood/stocks-detail?symbol=AAPL` | One Stock Token in depth: NAV history, all DEX pairs, holders, transfers, links || `GET /api/v1/robinhood/coins?category=meme` | Memecoin screener (`category`: `meme` \| `stocks-ecosystem` \| `ecosystem`; `sort`: `market_cap` \| `volume` \| `gainers` \| `losers`) || `GET /api/v1/robinhood/coins-detail?address=0x…` | One coin: pools, market stats, holders, transfers, links |@@ -61,7 +61,7 @@ Paid via x402 ($0.002 USDC, Base or Solana):| --- | --- || `GET /api/x402/robinhood-portfolio?address=0x…` | Multiplier-correct Stock Token portfolio: every held symbol's true position (raw balance × ERC-8056 `uiMultiplier`) priced at the live Chainlink NAV, plus a total USD value |-Every response carries `source` and `asOf` fields. A miss is a structured error, never a bare 500.+Every response carries `source` and `asOf` fields. A miss is a structured error, never a bare 500. An unknown `sort` (or `category`) falls back to the default instead of 400ing a screener read, and the response echoes the `sort` (and `dir`) that actually ran, never the caller's unknown value.### Why the multiplier mattersdiff --git a/docs/security.md b/docs/security.mdindex bf793e428..dc7611fc6 100644--- a/docs/security.md+++ b/docs/security.md@@ -237,7 +237,7 @@ The `skill-trust` attribute controls which skill URLs the element will load:Skills declare the permissions they need. Users must explicitly grant each permission before a skill can use it. The permission types (memory read/write, network, transaction signing) are independently grantable. An installed skill cannot escalate beyond its declared and granted permissions.-Delegation validation is enforced before any redemption: `isDelegationValid({ hash, chainId })` from [src/permissions/toolkit.js](../src/permissions/toolkit.js) checks the on-chain `disabledDelegations` mapping, expiry, and EIP-712 signature recovery. An invalid or revoked delegation renders as inactive — it cannot be redeemed.+Delegation validation is enforced before any redemption: `isDelegationValid({ hash, chainId, rpcUrl, delegation })` from [src/permissions/toolkit.js](../src/permissions/toolkit.js) checks the on-chain `disabledDelegations` mapping, expiry, and EIP-712 signature recovery, reaching the chain through the pinned `rpcUrl` (or `RPC_URL_<chainId>`) first and then the shared EVM fallback providers. It has three outcomes, not two: `valid: true`, `valid: false` with a reason (`delegation_revoked`, expiry, a bad signature), or `valid: null` with `reason: 'rpc_unavailable'` when no provider could be reached. An invalid or revoked delegation renders as inactive: it cannot be redeemed. An unreachable chain is not evidence of revocation; a caller that treats `null` as `false` is choosing fail-closed deliberately.### Supply chain for skills@@ -273,11 +273,15 @@ Requests through the `/api/chat` proxy are subject to the content policies of whServer code that fetches user-supplied URLs (GLB validation, manifest pinning, avatar imports) goes through [api/_lib/ssrf-guard.js](../api/_lib/ssrf-guard.js) rather than raw `fetch`. `assertSafePublicUrl()` rejects non-HTTPS schemes and resolves the hostname up front, refusing private, loopback, link-local, CGNAT, and cloud-metadata addresses. `fetchSafePublicUrl()` validates DNS then fetches (acceptable where the response is only displayed); `fetchSafePublicUrlPinned()` additionally pins the TCP connection to the validated IP so a DNS rebind between check and connect cannot redirect the request into the internal network. Both re-validate every redirect hop and enforce a streaming byte cap (`MaxBytesExceededError`) so an unbounded body cannot exhaust memory.+### Fault injection is token-gated++Every `/api` response carries an `x-brownout` header (plus `x-brownout-trace` when a trace was recorded) naming where its data came from. `wrap()` in [api/_lib/http.js](../api/_lib/http.js) writes it for every handler, so a client can tell a degraded, last-good answer from a live one. The matching `x-brownout-chaos` request header lets a prover make named upstreams misbehave for that one request only, running the real handler, the real provider ladder, and the real cache tiers. It is gated three ways in [api/_lib/brownout/chaos.js](../api/_lib/brownout/chaos.js), and every gate must pass: `BROWNOUT_CHAOS_TOKEN` must be set and match (constant-time compare; unset means chaos is off everywhere, including locally), a money path is refused outright no matter who holds the token (a request carrying an x402 payment header, or addressed to a settle, withdraw, or transfer route), and only read-shaped requests qualify (GET/HEAD, or a POST that is a declared read). A refused directive is reported in `x-brownout-chaos-status` rather than silently ignored.+---## Rate limiting-Limits return `429 Too Many Requests` with a `Retry-After` header on breach. Money-moving and credential buckets are enforced through shared Upstash Redis so they hold across every instance; a few very hot read buckets (including the MCP limiters) are deliberately per-instance (`local: true` in [api/_lib/rate-limit.js](../api/_lib/rate-limit.js)) to keep Redis command volume down, and the credential buckets degrade to in-memory limiting rather than failing closed if Redis is unreachable.+Limits return `429 Too Many Requests` with a `Retry-After` header on breach. Money-moving and credential buckets are enforced through shared Upstash Redis so they hold across every instance; a few very hot read buckets (including the MCP limiters) are deliberately per-instance (`local: true` in [api/_lib/rate-limit.js](../api/_lib/rate-limit.js)) to keep Redis command volume down. When Redis cannot answer, the money and credential buckets degrade onto a durable Postgres counter (`rate_limit_counters`) rather than failing closed, and the login and registration buckets fall back one step further to per-instance memory if Postgres is down too, so an infrastructure outage never locks everyone out (the full table is in [docs/ops/redis.md](./ops/redis.md)).| Endpoint class | Limit ||----------------|-------|diff --git a/docs/security/SECURITY_AUDIT.md b/docs/security/SECURITY_AUDIT.mdindex 9dcbb515c..dd1474e80 100644--- a/docs/security/SECURITY_AUDIT.md+++ b/docs/security/SECURITY_AUDIT.md@@ -175,7 +175,12 @@ sessions would brick every wallet.**Remediation:** dedicated `WALLET_ENCRYPTION_KEY` independent of `JWT_SECRET`,random per-record salt stored with ciphertext, dual-read during migration soexisting records keep decrypting. **Status: fixed (dual-read; new writes use the-dedicated key).**+dedicated key).** Since then: `WALLET_ENCRYPTION_KEY_PREVIOUS` keeps retired keys+readable through a rotation, production refuses to encrypt or decrypt under the+`JWT_SECRET` fallback at all (fail-closed when the dedicated key is missing or+short), and as of 2026-08-11 an unset `JWT_SECRET` only drops the legacy decrypt+candidate instead of breaking decryption of records written under the dedicated+key.### H9 — USD daily spend cap is read-then-write (TOCTOU)`api/_lib/agent-trade-guards.js:409-421,471-482`; enforced in@@ -208,7 +213,12 @@ by any attacker → UI-redress on wallet/trade/launch actions.**Remediation:** global default `frame-ancestors 'self'` + `X-Frame-Options:SAMEORIGIN`; keep explicit `*` only on genuine embed/OG/widget routes.-**Status: fixed.**+**Status: fixed.** _Current shape:_ the global route's CSP is `frame-ancestors+'self'` plus the IBM and Seismic partner origins (`https://ibm.com`,+`https://*.ibm.com`, `https://*.seismic.com`) for their embeds, and+`X-Frame-Options: SAMEORIGIN` rides on the auth, wallet, and dashboard route+group rather than the global route, since that header cannot express the partner+allowlist.### H12 — CSP `script-src` allows `'unsafe-inline'` and `'unsafe-eval'``vercel.json:202,209`. Neutralizes CSP's primary XSS mitigation; wide CDN@@ -342,7 +352,10 @@ read-only assets. **Status: fixed (audited + migrated authenticated handlers).**through `enforceSpendLimit`. **Status: fixed.**- **M12 — buyer spending-cap trusts payee-supplied decimals/name**`api/_lib/x402-spending-price.js:86-107`. Derive decimals/asset from the- on-chain mint, not payee `extra`. **Status: fixed.**+ on-chain mint, not payee `extra`. **Status: fixed** (a trusted asset registry+ keyed by the on-chain mint/contract address is authoritative for the decimals+ and stablecoin peg of the dominant x402 assets; an unknown asset falls back to+ the payee's values with decimals clamped to a sane range).- **M13 — triggerSkillPayment EVM spend bypasses custody cap**`api/_lib/agent-wallet.js:222-316`. Route through `enforceSpendLimit`; validate`author_wallet` shape. **Status: fixed.**diff --git a/docs/security/review-2026-06-24.md b/docs/security/review-2026-06-24.mdindex 04fde65cc..0cbaafb1d 100644--- a/docs/security/review-2026-06-24.md+++ b/docs/security/review-2026-06-24.md@@ -293,10 +293,20 @@ nosniff`, `referrer-policy: strict-origin-when-cross-origin`, a restrictive`'unsafe-inline'`/`'unsafe-eval'` — the nonce migration remains **tracked** (H12,prior audit). No header regression.+_Present-day status:_ the global `(.*)` route carries HSTS, nosniff,+referrer-policy, the permissions-policy, and CSP `frame-ancestors 'self'` plus+the IBM and Seismic partner origins; `x-frame-options: SAMEORIGIN` is set only+on the auth, wallet, and dashboard route group, not globally. `'unsafe-inline'`+no longer reaches a browser: `server/csp-hashes.mjs` rewrites `script-src` on+every HTML response to the SHA-256 hashes of that page's own inline scripts (H12+in the prior audit records how). `'unsafe-eval'` remains and is still tracked.+## Prior-fix regression check (spot-verified, intact)- SSRF guards on on-chain/URL fetches: `api/_lib/onchain.js` (`fetchSafePublicUrlPinned`),- `api/erc8004/register-confirm.js` (`fetchSafePublicUrl`) — present.+ `api/erc8004/register-confirm.js` (`fetchSafePublicUrlPinned` with a 2 MiB byte+ cap since 2026-08-06, so a client-supplied metadata URL can neither rebind DNS+ between check and connect nor stream an unbounded body): present.- Avatar IDOR: `api/avatar/optimize.js` and `api/avatar/video-generate.js`resolve avatars with the visibility/owner filter — present.- CORS never combines wildcard origin with credentials; cookies remaindiff --git a/docs/seed-quality.md b/docs/seed-quality.mdindex 72c16b2f0..6f1e368f1 100644--- a/docs/seed-quality.md+++ b/docs/seed-quality.md@@ -136,6 +136,12 @@ Retries surface as `gate_retry` entries in the tick's `gate_results`, with a`gate_retries` count on the response, so a lane that keeps blipping is visiblewithout reading the table.+Every read the gate makes is bounded so one slow host cannot stall the rest of+the tick: a lane's public GLB URL is fetched through the shared `fetchUpstream`+(30 s deadline, two attempts, and a non-2xx is a gate throw rather than an error+page handed to the GLB parser as mesh bytes), and the in-process Vertex judge+call carries a 45 s deadline with no retry.+## Rejects are kept, not deletedA reject is copied (never moved, so the creator's forge history stays coherent)diff --git a/docs/selfie-to-avatar.md b/docs/selfie-to-avatar.mdindex 869cdf92b..66e55a109 100644--- a/docs/selfie-to-avatar.md+++ b/docs/selfie-to-avatar.md@@ -13,18 +13,18 @@ Every other surface on three.ws (agents, the marketplace, Play worlds, talking-a## How it works-The client half lives in three modules the page imports on demand: [`src/selfie-capture.js`](../src/selfie-capture.js) (camera and upload UI), [`src/selfie-refine.js`](../src/selfie-refine.js) (`assessPhoto` / `refineSelfie`), and [`src/selfie-pipeline.js`](../src/selfie-pipeline.js) (the bridge to the backend). A fourth module, [`src/face-quality.js`](../src/face-quality.js), runs a live 468-point face mesh for framing feedback. Every quality threshold those modules apply lives in one shared, unit-tested module, [`src/selfie-gates.js`](../src/selfie-gates.js): each number is traced in its header comment to a real reconstruction-pipeline failure mode (the worker's no-face rejection, the 35-degree morph-yaw ceiling, provider blur failures, the dim/backlit band from the robustness benchmark), so the client rejects a shot for the same reasons the backend would.+The client half lives in three modules the page imports on demand: [`src/selfie-capture.js`](../src/selfie-capture.js) (camera and upload UI), [`src/selfie-refine.js`](../src/selfie-refine.js) (`assessPhoto` / `refineSelfie`), and [`src/selfie-pipeline.js`](../src/selfie-pipeline.js) (the bridge to the backend). A fourth module, [`src/face-quality.js`](../src/face-quality.js), runs a live 468-point face mesh for framing feedback. All three MediaPipe consumers (face mesh, segmenter, face detector) load `@mediapipe/tasks-vision` from our own bundle and resolve the WASM runtime and model files through [`src/shared/mediapipe-assets.js`](../src/shared/mediapipe-assets.js), which serves the vendored copy under `public/vendor/mediapipe/` first and only then falls back to a CDN, so a blocked `cdn.jsdelivr.net` no longer disables the scanner. Every quality threshold those modules apply lives in one shared, unit-tested module, [`src/selfie-gates.js`](../src/selfie-gates.js): each number is traced in its header comment to a real reconstruction-pipeline failure mode (the worker's no-face rejection, the 35-degree morph-yaw ceiling, provider blur failures, the dim/backlit band from the robustness benchmark), so the client rejects a shot for the same reasons the backend would.Two of those numbers are measured rather than reasoned about. The blur floor (`BLUR_STDDEV_MIN`) is calibrated against six real portrait photographs framed as 720x1280 phone selfies and scored through the module's own math, sharp versus the reconstruction worker's exact `robustness.py` degradations: sharp faces read 22.8 to 39.4, a Gaussian blur of radius `longestEdge/220` reads 10.6 to 15.7, and a radius-10 smear reads 6.3 to 9.4. The floor sits at 12, in the empty band between the blurred and sharp populations. And because a blown-out face *raises* Laplacian response instead of lowering it, and averages back into the accepted band, neither the blur nor the mean-luma gate can see window glare on its own: `grayFaceStats` also reports `clippedFrac`, the share of the face crop pinned to near-white, gated separately by `CLIPPED_FRAC_MAX`.-1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, luminance, and highlight clipping, and only unlocks the shutter when a face is found; the hint line names the single most actionable fix ("Face the camera straight on.", "Hold steady. The image is blurry.", "Too dark. Find better light.", "Too bright. Move out of direct light or turn away from the window.") until every gate passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file.+1. **Capture, in the browser.** `getUserMedia({ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } } })` opens the front camera. A real-time wireframe overlay tracks head pose, yaw, centering, blur, luminance, and highlight clipping, and only unlocks the shutter when a face is found; the hint line names the single most actionable fix ("Face the camera straight on.", "Hold steady. The image is blurry.", "Too dark. Find better light.", "Too bright. Move out of direct light or turn away from the window.") until every gate passes. A 3-2-1 countdown fires, then `shoot()` draws the current video frame to a canvas and calls `canvas.toBlob(blob, 'image/jpeg', 0.92)`. This is a **single still**, not a video scan. Camera support is feature-detected; if none exists, the shutter is disabled and an "Upload instead" path takes any image file. A photo shared into three.ws from the Android share sheet (the Seeker app or any installed PWA) is POSTed to `/create/share`, parked by `public/share-target-sw.js`, and lands here with `?shared=1`; the capture page reads those files once (`src/shared/share-target.js`), fills the frontal slot and then left and right, and strips the param so a reload does not look like a fresh share.2. **Review the still.** The countdown leaves ~3 seconds for motion blur, a head turn, or a lighting change to land in the actual capture, so the frozen still is re-scored (`checkImageQuality`) against the same gates before you accept it. The review screen shows per-gate chips plus a verdict line; only a missing face disables "Use this" (mirroring the worker's one hard input rejection), everything else is a warning you can accept.3. **Optional side angles.** Under an "Add side angles" disclosure you can capture two extra stills (`left`, `right`, turned ~45 degrees). They raise fidelity and the ETA, but only the frontal is required. Confirmed shots (and the style choice) are mirrored to `sessionStorage`, so a refresh or accidental back-swipe mid-capture restores every slot instead of starting over; the build phase has its own resume rail (`selfie:pendingJobId`).4. **Refine, in the browser.** `assessPhoto` gates the frontal (no face is the only hard block; blur, illustration, or a distant subject are non-fatal warnings). `refineSelfie` isolates the subject from its background and reframes to a clean head-and-shoulders square, rendered at 1024x1024 with JPEG quality 0.92 ([`src/selfie-refine.js`](../src/selfie-refine.js)). The refined frontal is previewed so you see exactly what the engine sees.-5. **Submit.** The pipeline ([`src/selfie-pipeline.js`](../src/selfie-pipeline.js)) downscales each photo to a 1024px longest edge at JPEG quality 0.88, POSTs them as data URIs to `/api/avatars/reconstruct`, and gets back a `jobId`.+5. **Submit.** The pipeline ([`src/selfie-pipeline.js`](../src/selfie-pipeline.js)) downscales each photo to a 1024px longest edge at JPEG quality 0.88, POSTs them as data URIs to `/api/avatars/reconstruct`, and gets back a `jobId`. Before any GPU work starts the handler pre-flights the caller's avatar library against its plan ceiling (`assertAvatarSlotAvailable`) and refuses a full library with `402 plan_limit`, so nobody waits ninety seconds for a mesh that could never be saved.6. **Reconstruct, server-side.** The reconstruct handler (`api/avatars/_actions.js`) selects a provider through [`api/_lib/regen-provider.js`](../api/_lib/regen-provider.js). The production lane is **GCP**: it POSTs `{ images, body_type }` to the Cloud Run service behind `GCP_RECONSTRUCTION_URL`, today the [`workers/avatar-reconstruction/`](../workers/avatar-reconstruction/) FastAPI app deployed as `avatar-reconstruction`. (The multi-backend [`workers/avatar-pipeline-controller/`](../workers/avatar-pipeline-controller/) speaks the identical contract and can take over that env var, but is not deployed today.) That pipeline (`face_texture_transfer_v2`) uses **MediaPipe FaceLandmarker** (468 landmarks, Apache-2.0) to transfer your face texture and geometry onto a fixed-topology, pre-rigged Wolf3D/Ready-Player-Me-style humanoid template carrying a Mixamo-compatible skeleton, 52 ARKit blendshapes, and 15 visemes. Full engine detail is in [avatar-reconstruction.md](./avatar-reconstruction.md).7. **Auto-rig fallback.** The template is born rigged. If a generic mesh comes back unrigged and a rig model is configured, `reconstruct-finalize.js` chains a `rerig` job (the `model-rig` worker, `workers/rig`) and moves the job through a `rigging` status before surfacing the avatar. If rigging is impossible it delivers the static mesh tagged `unrigged` rather than nothing.-8. **Poll and finish.** The client polls `GET /api/avatars/regenerate-status?jobId=...` every ~3 seconds (backing off on errors). On `status: 'done'` it fetches the finished avatar from `GET /api/avatars/:id` and shows it in a `<model-viewer>`. The poll uses the adapter for the provider recorded on the job row, not whichever provider currently leads the precedence order, because the stored job id is provider-shaped and only that backend can read it.+8. **Poll and finish.** The client polls `GET /api/avatars/regenerate-status?jobId=...` every ~3 seconds (backing off on errors). On `status: 'done'` it fetches the finished avatar from `GET /api/avatars/:id` and shows it in a `<model-viewer>`. A `done` job with no `resultAvatarId` means the server's materialize stage threw after the mesh was generated; that stage re-runs on every poll, so the client looks again up to three more times before treating it as a failure. If the materialization lost the quota race (another avatar landed while this one was generating), the server ends the job as `failed` with caller-facing copy rather than leaving it stranded at `done`. The poll uses the adapter for the provider recorded on the job row, not whichever provider currently leads the precedence order, because the stored job id is provider-shaped and only that backend can read it.9. **Register and mint.** Materializing the avatar also registers it in the Forge store (`forge_creations`, `path: 'reconstruct'`) so galleries, share and embed pages, and provenance treat a capture like any other creation, and fires a best-effort [draft agent identity mint](./draft-agent-mint.md): a Metaplex Core asset on Solana, with an ERC-8004 registration behind its own flag. Both are best-effort by design: the avatar is already delivered, so neither can fail the job.10. **Backstop for a closed tab.** The browser poll is what drives finalization, so closing the tab mid-build would otherwise strand the job even though the worker finished. [`api/cron/reconstruct-sweep.js`](../api/cron/reconstruct-sweep.js) runs the same finalize stages server-side every few minutes, so an abandoned capture still lands in your library. It rescues jobs up to 30 days old, and fails anything older with an honest reason rather than leaving it open forever.@@ -79,7 +79,7 @@ Request body: `name` (1-120, required), `photos` (1-6 image URLs or data URIs) *- **Quality gating.** Only a frontal with no detectable face hard-blocks. Blur, illustrations, or multiple faces are surfaced as warnings you can proceed past.- **Error handling.** Camera denial distinguishes `NotAllowedError` ("Camera access was denied... use Upload instead") from other failures. Job failures map to friendly messages (no face, content-safety flag, blur, service unavailable, timeout, out-of-memory). Poll tolerates up to 5 consecutive network errors with backoff before "Lost connection to the avatar engine." Rate limits (`429`) start a 60-second cooldown with a live countdown. Pending jobs resume across reloads.- **Output.** glTF 2.0 GLB with a Mixamo-standard humanoid rig, 52 ARKit blendshapes, and 15 visemes. Private avatars return a short-lived signed `url`; `model_url` is the public CDN URL once you make it public.-- **Error copy.** The worker classifies a failure as either the caller's input or a service fault. An input rejection ("no face detected in any of the provided photos") is relayed verbatim so the client can name the fix; a service fault is masked into neutral retry copy, because its raw text can carry a vendor name or an operator-only correlation id. Your visibility choice rides along to the Forge store, so a private capture never surfaces in a public gallery.+- **Error copy.** The worker classifies a failure as either the caller's input or a service fault. An input rejection ("no face detected in any of the provided photos") or a plan refusal is relayed verbatim, and the status response carries `errorKind: 'input'` so the client shows that text as-is instead of rewriting an unrecognised message into generic "try a clearer photo" advice; a service fault is masked into neutral retry copy, because its raw text can carry a vendor name or an operator-only correlation id. Your visibility choice rides along to the Forge store, so a private capture never surfaces in a public gallery.## Relateddiff --git a/docs/shared-utilities.md b/docs/shared-utilities.mdindex ffc24549f..f82959d56 100644--- a/docs/shared-utilities.md+++ b/docs/shared-utilities.md@@ -181,6 +181,21 @@ EVM RPC do not go through here: `api/_lib/solana/connection.js` andproviders (with per-provider parsers) use `fetchFirst` from`src/shared/failover-fetch.js` instead.+Because every third-party call in `api/` passes through one of these three+(`fetchUpstream`, `fetchFirst`, or the Solana connection), they are also where+[Brownout](./brownout.md) hooks in. Each attempt is recorded against the+current request (`recordSource` from `api/_lib/brownout/`), and a `lastGood`+hit records itself as `tier: 'stale'` with its age, which is what lets the+response carry the `x-brownout` / `x-brownout-trace` headers saying which rung+answered and how fresh it was. The same seam honours a declared fault+(`faultFor(name)`): an `x-brownout-chaos` directive raises the fault in the+shape of the real failure, from inside the same `try` the genuine outage would+land in, so retries, `Retry-After` handling, cooldowns and the breaker all see+it exactly as they would see the outage. `failover-fetch.js` and+`connection.js` are isomorphic and load the brownout module lazily on the+server only (the specifier is parked on `globalThis` so Rollup cannot fold it+into the CDN bundle); in a browser both hooks are inert.+### `api/_lib/cache.js`: `cacheWrapLastGood````js@@ -346,7 +361,10 @@ of a provider result URL that only exists at runtime. Three exemptions there,each for a call that cannot hang or is already bounded elsewhere: a `data:` URL(no socket), a client snippet quoted as a string (it runs in a browser), and awrapper that spreads its caller's `init` (the deadline is the caller's, and a-second one would silently shorten it).+second one would silently shorten it). Two shapes are never counted as calls at+all: a `fetch(` that sits inside a string literal (a usage example shipped as+data in an API response), and a member call such as `client.fetch(...)`, which+is somebody else's method rather than the global `fetch`.The checker reads each call's real extent by balancing parentheses rather thanscanning a fixed window, because `signal` is conventionally the last key of andiff --git a/docs/signals.md b/docs/signals.mdindex 2c753d68a..692a78b3b 100644--- a/docs/signals.md+++ b/docs/signals.md@@ -64,7 +64,7 @@ curl -s https://three.ws/api/signals/subscribe \}'```-The feed's numeric `feed_id` comes from the marketplace read; the subscription's network is inherited from the feed, so you do not pass one.+The feed's numeric `feed_id` comes from the marketplace read; the subscription's network is inherited from the feed, so you do not pass one. `feed_id` and a subscription `id` must be numeric row ids: anything else is refused with `400 invalid_feed` / `400 invalid_id` before any query runs. The live SSE stream (`GET /api/signals/stream`) likewise takes its network from the feed it streams, not from a query parameter.Go live within your caps, then instantly kill if needed:diff --git a/docs/sketchfab.md b/docs/sketchfab.mdindex 181def29e..440a24ebb 100644--- a/docs/sketchfab.md+++ b/docs/sketchfab.md@@ -30,8 +30,9 @@ guard), when it was already uploaded, or when it failed three times.**Brand safety.** The official account never publishes firearms or explicitcontent, regardless of what the forge itself allows. A conservativeword-boundary denylist filters the selection query and re-checks before-upload, and the platform's NemoGuard content classifier runs as a second-layer. Blocked creations are parked in the ledger (`blocked`) and never+upload, and the NemoGuard content classifier in `api/_lib/publish-safety.js`+runs as a second, fail-open layer. Both are limits on what this account+publishes, not on what users may forge. Blocked creations are parked in the ledger (`blocked`) and neverre-picked. Refinement children are also excluded from the creator-validatedtier, since their prompts are instructions, not titles.@@ -39,7 +40,14 @@ tier, since their prompts are instructions, not titles.Every published model carries:-- **The generation prompt** at the top of the description, in quotes.+- **The generation prompt** at the top of the description, in quotes. The+ model's name is the prompt with a leading article stripped and clamped to+ Sketchfab's display limit; a creation whose stored prompt is a placeholder+ rather than a description (the image-to-3D path stores its route name,+ `image-to-3d`, as the prompt) is named from its forge category instead+ ("Forged Sci-Fi"), falling back to "3D Model" for the catch-all buckets, so+ a winning image-derived model never reaches the account titled after a+ route.- **AI disclosure**: the `ai-generated` tag plus a plain statement that themodel was AI-generated on the three.ws Forge. Sketchfab has no dedicatedAI-content field, so tag + statement is the correct marking.diff --git a/docs/smart-money.md b/docs/smart-money.mdindex 843376fdc..71eb95dcc 100644--- a/docs/smart-money.md+++ b/docs/smart-money.md@@ -16,7 +16,7 @@ The page is a self-contained module inside `pages/smart-money.html` that polls `The numbers are produced by a cron rollup (`api/cron/smart-money-rollup.js`) in three phases that write to `wallet_reputation`, `coin_smart_money`, and a `smart_money_scored` dedupe ledger:-**Phase A: judge and fold.** Six hours after launch, a coin's outcome is binary: present in `pumpfun_graduations` is a win, otherwise a dud. For the top 60 buyers of each judged coin, per-wallet deltas are folded into `wallet_reputation`. An entry counts as **early** when the wallet's first buy is within 180 seconds of the coin's first trade, and a **dump** when the wallet sold at least half of what it bought.+**Phase A: judge and fold.** Six hours after launch, a coin's outcome is binary: present in `pumpfun_graduations` is a win, otherwise a dud. Each run judges up to 400 coins, oldest first; the budget has to outrun the firehose (about 32k mints a day), because a coin that ages past the 14-day retention window unjudged is pruned and its buyers never fold into anyone's record. For the top 60 buyers of each judged coin, per-wallet deltas are folded into `wallet_reputation`. An entry counts as **early** when the wallet's first buy is within 180 seconds of the coin's first trade, and a **dump** when the wallet sold at least half of what it bought.**Phase B: recompute reputation.** For each touched wallet the score is:@@ -88,7 +88,8 @@ for (const c of conviction.slice(0, 5)) {- **Auth.** The read APIs are public and require no account. The rollup cron is Bearer-authenticated with `CRON_SECRET`.- **Rate limit.** 600 requests per minute per IP; over that returns 429.- **Warm-up window.** A coin is not judged until roughly 6 hours after launch, so a very fresh coin shows "not scored yet." The per-coin read deliberately returns `200 { found: false }` rather than a 404 for an unscored mint.-- **Empty and error states.** The feed, leaderboard, and watchlist each have designed empty copy ("No proven money on a fresh coin yet," "No wallets ranked yet"). A wallet with no history returns 404 and renders "No track record yet." A failed full refresh shows a stale-data reconnecting bar with a Retry button and escalates its message after repeated failures.+- **Input validation.** A `wallet` or `mint` that is not a base58 Solana address is refused at the boundary with `400 invalid_wallet` / `400 invalid_mint`, so "that is not an address" and "no track record yet" stay different answers. Every error on the route, the wallet 404 included, carries the shared `{ error, error_description }` shape.+- **Empty and error states.** The feed, leaderboard, and watchlist each have designed empty copy ("No proven money on a fresh coin yet," "No wallets ranked yet"). A wallet with no history returns 404 and renders "No track record yet." A failed full refresh shows a stale-data reconnecting bar with a Retry button and escalates its message after repeated failures. The watchlist tells a network failure apart from an honest "not on the radar": when every lookup fails to reach the API (or answers 5xx), the grid shows one "Couldn't reach the radar" panel with a Retry and keeps the saved list, and a single unreachable coin gets a "Couldn't load this one" card rather than being labelled unscored.- **Two engines, one name.** This page reads `/api/pump/smart-money` (the graduation-outcome rollup). A sibling endpoint, `/api/intel/smart-money`, is a distinct funder-cluster and sybil-detection graph used by other surfaces. They answer related questions from different tables; do not conflate them.## Relateddiff --git a/docs/social-layer.md b/docs/social-layer.mdindex 93a9d3a03..f92c7f7a7 100644--- a/docs/social-layer.md+++ b/docs/social-layer.md@@ -129,14 +129,29 @@ PUT /api/notifications/preferences → update itPreferences are a category × channel matrix([api/_lib/notify-prefs.js](../api/_lib/notify-prefs.js)): categories are-sales, purchases, social, IRL, market alerts, creations, and account &-security; channels are `in_app`, `push`, `email`, and `telegram`. Every-channel is a per-category toggle (`in_app` defaults on everywhere, and is-locked on for account & security so the bell record of security events never-goes silent), edited from the Notifications panel in `/dashboard/settings`+sales, purchases, social, IRL, market alerts, creations, companion+deliveries, knocks at your door, and account & security; channels are+`in_app`, `push`, `email`, `telegram`, and `avatar`. Every channel is a+per-category toggle (`in_app` defaults on everywhere, and is locked on for+account & security so the bell record of security events never goes silent),+edited from the Notifications panel in `/dashboard/settings`([src/dashboard-next/pages/settings.js](../src/dashboard-next/pages/settings.js)).Bell client: [src/notifications.js](../src/notifications.js).+The `avatar` channel is the corner companion walking on screen and saying the+notification out loud. It is delivered client-side: the bell hands its unread+inbox to [src/notification-herald.js](../src/notification-herald.js), which+owns every rule (the per-category preference, freshness, per-id dedupe, a+batch cap), and `GET /preferences` ships the server's `type_categories` map so+the browser gates on the same type-to-category table push and email use. It+defaults on only for the categories worth interrupting for (sales, creations,+companion, knock, account & security) and off for the rest. A click-through+from a spoken notification is tracked as `channel: "avatar"` on+`POST /api/notifications/track`. `PUT /preferences` is a merge, not a+replacement: a body carries only the keys being changed, omitting a key keeps+its stored value, and `telegram_chat_id` must be a numeric chat id (send+`null` or `""` to disconnect).+## Leaderboard, streaks, and badges: `/rankings`One leaderboard across every surface, plus daily streaks and badges.@@ -148,7 +163,11 @@ GET /api/leaderboard/unified?metric=creations&limit=50&offset=0`metric` is one of `creations`, `remixes_received`, `launches`, `followers`,`walk_distance` (limit 1..100, default 50). Sending the request with a sessionor Bearer token pins your own row into the response even when you are outside-the page window.+the page window. `remixes_received` counts only finished derivatives made by+someone else: both the parent and the child must be `status = 'done'`, and a+creator's own refines of their own model (which also write+`parent_creation_id`) never count, so nobody climbs that board by re-refining+their own work.The streak engine ([api/_lib/streaks.js](../api/_lib/streaks.js),`recordDailyActivity()`) is called from sign-in, forge saves, diorama saves,diff --git a/docs/solana-pumpfun.md b/docs/solana-pumpfun.mdindex 04193d519..46999f9f9 100644--- a/docs/solana-pumpfun.md+++ b/docs/solana-pumpfun.md@@ -71,11 +71,13 @@ SOLANA_RPC_URL_DEVNET=`PUMPFUN_BOT_URL` is an **optional enrichment layer**, not a hard dependency. When it's unset (the prod default), the `pumpfun-signals` cron still runs off the live WS-fed `pumpfun_graduations` table and the `pf:claims` / `pf:whales` / `pf:mints` Redis lanes — only the bot's richer claim intel (tier, GitHub account age) is skipped. The `op=claims` read proxy and watch skills soft-degrade to empty when the bot is absent. Solana agents that don't use it pay no cost.+The read proxy validates its request before that degrade, so the contract does not depend on the deployment's env: an unknown `op`, or `op=token` without `mint` / `op=creator` without `wallet`, is `400 validation_error` whether or not the bot is configured.+---## Skills-All registered through `registerPumpFunWatchSkills` in [src/agent-skills.js](../src/agent-skills.js).+All registered through `registerPumpFunWatchSkills` in [src/agent-skills.js](../src/agent-skills.js). The skills await their platform fetches inline in the agent's turn, so every one is bounded (8 s by default) and a stalled feed fails the skill instead of leaving the chat mid-reply forever.| Skill | MCP-exposed | Effect ||---|---|---|@@ -139,7 +141,7 @@ These are **off-chain** signals — flagged as such, not on-chain attestations.## Widget-The `pumpfun-feed` widget renders a stack of cards (claim or graduation) as an absolutely-positioned overlay on top of the 3D viewer. With `autoNarrate: true`, the avatar narrates each event through the protocol bus.+The `pumpfun-feed` widget renders a stack of cards (claim or graduation) as an absolutely-positioned overlay on top of the 3D viewer. With `autoNarrate: true`, the avatar narrates each event through the protocol bus. Each card's trading-terminal links come from the shared builder in [src/shared/trading-terminals.js](../src/shared/trading-terminals.js) (`terminalLinks(mint)` and `referralOffers()`), the same one the copy pages use, so adding or re-pointing a terminal is one change. The overlay carries no inline event handlers (a broken token image hides through the `data-fallback="hide"` hook), which is what keeps it inside the site's CSP.Studio config schema (validated in `widget-types.js`):diff --git a/docs/swarms.md b/docs/swarms.mdindex 77e29a91d..5332141d3 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -201,6 +201,7 @@ Every failure returns `{ error, error_description }` with a specific code rather| 403 | `below_threshold` | `kill` from a member holding under `kill_threshold_bps` || 415 | `bad_request` | A mutation sent without `Content-Type: application/json` || 429 | `rate_limited` | Over 30 mutations per minute for this user |+| 503 | `rpc_unavailable` | The treasury balance could not be read from Solana RPC, so `contribute` or `exit` refused to proceed rather than treat an unknown balance as zero; retry after the `Retry-After` window (15 seconds) || 404 | `not_found` | No such swarm || 404 | `agent_not_found` | No such agent || 404 | `not_member` | `exit` from an agent that is not an active member |diff --git a/docs/terminal.md b/docs/terminal.mdindex 2b4577f06..f6989e7a4 100644--- a/docs/terminal.md+++ b/docs/terminal.md@@ -18,6 +18,8 @@ The page mounts `mountMissionControl` from `src/mission-control/index.js` and la- **Focus (center).** The selected coin's identity and market state (`/api/pump/coin`), its candlestick chart (`/api/pump/price-history`, Birdeye with a GeckoTerminal fallback and a last-good-candles degrade), the live trade tape (`/api/pump/dex-trades` polled every 8s for graduated pairs the stream misses), the firewall verdict, and the smart-money read.- **Positions (right).** Your agent's open positions with streaming unrealized PnL over SSE (`/api/sniper/stream`, DB-polled every 1.5s), spot holdings (`/api/agents/:id/solana/holdings`, refreshed every 30s), and a one-tap quick exit.+Signed out, or signed in without an agent wallet, the cockpit stays fully readable: the feed, chart, security grid, and smart-money read all work, while the trade desk and the Positions pane say exactly what unlocks trading (sign in, or create an agent wallet) and the Positions connection pill reads idle instead of reconnecting. Token art is served through the same-origin `/api/img` proxy because the public IPFS gateways most launches use refuse direct browser requests. The top bar also hosts the language picker: on phones the site-wide floating picker would otherwise cover the Positions tab of the bottom pane switcher.+Each row in the feed is enriched on demand by `enrich.js`, which fans out three cached reads per mint: intel (`/api/pump/intel?mint=`), the Trade Safety Firewall (`/api/pump/safety?mint=&amount=`, which runs an SPL authority audit plus an on-chain simulated buy then sell round-trip and returns `allow` / `warn` / `block`), and smart money (`/api/intel/smart-money?mint=`). Failures cache `null` and mark the field unavailable rather than retry-storming or faking a value.Every SSE endpoint self-closes about every 90 seconds by design; `realtime.js` treats an `event: close` as normal and fast-reconnects, with exponential backoff only on real errors.@@ -45,7 +47,7 @@ The filter bar (state in `store.js`) narrows the feed by source, free-text query## Firewall, MEV, and trading from your agent wallet-Trading is the guarded path, and the client checks are only a fast gate: the server is the real authority. `POST /api/agents/:id/solana/trade` is owner-only (session or bearer auth, then agent-ownership verification) and, for a real execute, requires a single-use `x-csrf-token` and an `idempotency_key`. A `{ preview: true }` call returns a live quote and moves no funds. On execute the server runs a fixed enforcement order: fresh quote, kill switch, per-trade cap, daily budget, spend-limit enforcement, price-impact breaker, then the Trade Safety Firewall (`assessTradeSafety`; a `block` returns HTTP 422 `firewall_blocked`), then SOL headroom, then it claims the idempotency slot and submits through the MEV engine (`submitProtected` with `tipMode 'off'`: dynamic compute budget from a real simulation and a Helius priority-fee estimate on a protected single-tx send; the engine's Jito bundle-with-tip route exists but is not used by this endpoint). The agent's key is decrypted only at signing time via `recoverSolanaAgentKeypair`, and every attempt is audit-logged. A retried idempotency key never double-spends; a previously failed key returns 409. The firewall thresholds live in `api/_lib/trade-firewall.js`: block at score 45 and below, warn at 70 and below, with a fatal check (a dead sell leg or no venue) forcing `block` regardless of score.+Trading is the guarded path, and the client checks are only a fast gate: the server is the real authority. `POST /api/agents/:id/solana/trade` is owner-only (session or bearer auth, then agent-ownership verification) and, for a real execute, requires a single-use `x-csrf-token` and an `idempotency_key`. A `{ preview: true }` call returns a live quote, moves no funds, and surfaces any guard that would reject the execute as a warning instead of a rejection. On execute the server runs a fixed enforcement order: fresh quote (a pump.fun mayhem-mode coin is refused here with HTTP 422 `mayhem_blocked`, on preview and execute alike), kill switch, per-trade cap, daily budget, spend-limit enforcement, price-impact breaker, then the Trade Safety Firewall on buys only (`assessTradeSafety`; a `block` returns HTTP 422 `firewall_blocked`; a sell brings SOL inward and skips it), then SOL headroom, then it claims the idempotency slot and submits through the MEV engine (`submitProtected` with `tipMode 'off'`: dynamic compute budget from a real simulation and a Helius priority-fee estimate on a protected single-tx send; the engine's Jito bundle-with-tip route exists but is not used by this endpoint). The agent's key is decrypted only at signing time via `recoverSolanaAgentKeypair`, and every attempt is audit-logged. A retried idempotency key never double-spends; a previously failed key returns 409. The firewall thresholds live in `api/_lib/trade-firewall.js`: block at score 45 and below, warn at 70 and below, with a fatal check (a dead sell leg or no venue) forcing `block` regardless of score.Express mode (`trade.js`): the first trade always shows a confirm modal; accepting sets a per-agent express flag so later orders execute instantly. `x` toggles it back off.diff --git a/docs/three-thesis.md b/docs/three-thesis.mdindex 7af763083..59a2b461d 100644--- a/docs/three-thesis.md+++ b/docs/three-thesis.md@@ -36,7 +36,7 @@## 1. The one-paragraph version-Most tokens are a story looking for a product. $THREE is the reverse: it is the coin of a shipping, open-source, revenue-generating platform that gives AI agents a 3D body, an on-chain identity, a wallet, and a way to get paid. The platform (three.ws) has published 2,673 changelog entries in about four months, exposes 723 public pages, ships 70 npm packages and 36 MCP servers, and runs a live pay-per-call economy (x402) with over one million individually priced datapoints. The token is wired into that machine at every level: hold-to-access tiers create standing demand, a 20% discount on plans and premium passes creates spend demand, a policy that commits 50% of platform revenue to market buybacks creates buy-side pressure, a micro-buy loop turns every settled x402 call into a small $THREE purchase, and on-chain agent deploys route their fee to the buyback wallet. Supply is never destroyed by the platform; instead the treasury buys. The token trades on MEXC, LBank, KCEX, Bybit Alpha, KuCoin Alpha, and every major Solana DEX, is Jupiter-verified, Phantom-verified, and a verified project on pump.fun. It is a real product's real coin, and the product is one of the more complete agent-economy stacks in the open-source world.+Most tokens are a story looking for a product. $THREE is the reverse: it is the coin of a shipping, open-source, revenue-generating platform that gives AI agents a 3D body, an on-chain identity, a wallet, and a way to get paid. The platform (three.ws) has published 2,738 changelog entries in about four and a half months, exposes 761 public pages, ships 89 npm packages and 39 MCP servers, and runs a live pay-per-call economy (x402) with over one million individually priced datapoints. The token is wired into that machine at every level: hold-to-access tiers create standing demand, a 20% discount on plans and premium passes creates spend demand, a policy that commits 50% of platform revenue to market buybacks creates buy-side pressure, a micro-buy loop turns every settled x402 call into a small $THREE purchase, and on-chain agent deploys route their fee to the buyback wallet. Supply is never destroyed by the platform; instead the treasury buys. The token trades on MEXC, LBank, KCEX, Bybit Alpha, KuCoin Alpha, and every major Solana DEX, is Jupiter-verified, Phantom-verified, and a verified project on pump.fun. It is a real product's real coin, and the product is one of the more complete agent-economy stacks in the open-source world.The thesis is not "number go up." The thesis is: **if agents become economic actors, they need bodies, identities, wallets, and rails, and three.ws has shipped all four with $THREE in the middle.**@@ -65,7 +65,7 @@ On top of those five, the platform layers an entire agent economy:- **A multiplayer world (`/play`)** with a strictly separated in-game currency and a $THREE cosmetics boutique.- **An MCP endpoint** at `https://three.ws/api/mcp` behind a full OAuth 2.1 authorization server, so any MCP-capable AI client can drive the platform.-Infrastructure: a single Google Cloud Run container serves the frontend, the route table, and every API handler; Neon Postgres, Cloudflare R2, and Upstash Redis behind it; a self-hosted Cloud Run GPU fleet (L4s plus one RTX PRO 6000 Blackwell) for text-to-3D, rigging, and motion; roughly 76 Cloud Scheduler crons keep the economy ticking.+Infrastructure: a single Google Cloud Run container serves the frontend, the route table, and every API handler; Neon Postgres, Cloudflare R2, and Upstash Redis behind it; a self-hosted Cloud Run GPU fleet (L4s plus one RTX PRO 6000 Blackwell) for text-to-3D, rigging, and motion; 110 Cloud Scheduler crons (the `crons` array in `vercel.json`) keep the economy ticking.The point of listing all of this: **$THREE is not attached to a landing page.** It is attached to a system with dozens of live, wired, money-moving surfaces.@@ -73,18 +73,18 @@ The point of listing all of this: **$THREE is not attached to a landing page.**## 3. The scale of what has been built-Numbers measured directly from the repository on 2026-08-25:+Numbers measured directly from the repository on 2026-09-01 (the external figures, such as GitHub, npm downloads, registry counts, and settlement totals, are as of 2026-08-25):| Dimension | Figure ||---|---|-| Public pages (`data/pages.json`) | **723** across 10 sections (Crypto 137, Build 59, Learn 373, Main 52, Labs 22, Blog 39, and more) |-| Changelog entries (`data/changelog.json`) | **2,673**, dated 2026-04-15 to 2026-08-24 |-| Changelog tag mix | fix 1,190 · improvement 1,075 · feature 991 · infra 320 · docs 225 · security 216 · sdk 166 |-| npm packages published under @three-ws | **101** (42 of them MCP servers, 6,225 downloads in the last 30 days); 70 live under `packages/` in this repo |-| Root `package.json` | 257 scripts, 139 dependencies, version 1.5.2 |+| Public pages (`data/pages.json`) | **761** across 10 sections (Crypto 137, Build 69, Learn 397, Main 56, Labs 22, Blog 39, and more) |+| Changelog entries (`data/changelog.json`) | **2,738**, dated 2026-04-15 to 2026-09-01 |+| Changelog tag mix | fix 1,219 · improvement 1,107 · feature 1,016 · infra 330 · docs 234 · security 218 · sdk 182 |+| npm packages published under @three-ws | **101** (42 of them MCP servers, 6,225 downloads in the last 30 days); 89 live under `packages/` in this repo |+| Root `package.json` | 277 scripts, 142 dependencies, version 1.5.2 || MCP servers in the official registry | **72** under `io.github.nirholas` (including `three-token-mcp`, `threews-3d-studio`, `threews-pumpfun`, `x402-mcp`, `agora-mcp`, `metaplex-agent`) || Docs mentioning $THREE | 89 markdown files |-| Cloud Scheduler crons | ~76 |+| Cloud Scheduler crons | 110 || Crypto news archive | **660,000+ articles** from September 2017 onward, 192 publisher feeds in 18 languages || DeFi pools indexed | ~15,000 live pools || Individually priced x402 datapoints | **1,000,000+** at $0.0005 each |@@ -206,7 +206,7 @@ The fee rides inside the same transaction that creates the asset, so a failed de### 5.11 The Rider pass-`api/_lib/rider.js`: `REQUIRED_AMOUNT = 8000` $THREE. Granted two ways: by holding, or by paying 8,000 $THREE into the rider vault (recorded by a Helius webhook), so a payer who later sells is not revoked. Both sources are honored by `GET /api/rider/check`.+`api/_lib/rider.js`: `REQUIRED_AMOUNT = 8000` $THREE. Granted two ways: by holding, or by paying 8,000 $THREE into the rider vault (recorded by a Helius webhook), so a payer who later sells is not revoked. Both sources are honored by `GET /api/rider/check`. The verdict is cached per wallet for ten minutes whenever both sources answered, so an RPC outage mid-session returns the wallet's last verdict marked stale (`x-rider-stale: 1`) instead of refusing the gate; a wallet never checked before gets a typed `503 rpc_unavailable` with `Retry-After`.### 5.12 x402 rail acceptance@@ -528,7 +528,7 @@ If buybacks never turn on, perks never activate, or revenue does not grow, the t## 17. Summary of the bull case-1. **A real, shipping, open-source product** with 725 pages, 101 npm packages, 72 MCP servers in the official registry, 4,519 priced x402 endpoints with 110,416 on-chain settlements, and 2,674 changelog entries in four months. The code is public and every mechanic in this document can be read. The week-by-week record is in [The First 19 Weeks](./the-first-19-weeks.md).+1. **A real, shipping, open-source product** with 761 pages, 101 npm packages, 72 MCP servers in the official registry, 4,519 priced x402 endpoints with 110,416 on-chain settlements, and 2,738 changelog entries in four and a half months. The code is public and every mechanic in this document can be read. The week-by-week record is in [The First 19 Weeks](./the-first-19-weeks.md).2. **A complete agent-economy stack**: bodies (3D avatars), identities (ERC-8004 and Metaplex Core), wallets (custodial with a single spend-policy boundary), rails (x402 with a self-hosted Solana facilitator), trust (cross-chain reputation and identity verification), and markets (skills, assets, labor, bounties, vaults).3. **The token is wired into every layer**: hold-to-access tiers, 20% discounts on plans and passes, marketplace-only currency, labor and bounty escrow, game cosmetics, gated embeds, holder worlds, rider passes, deploy-fee waivers, x402 acceptance, and one-signature allowances.4. **Three simultaneous demand vectors**: standing demand from holding, spend demand from discounts, and buy-side demand from a published 50%-of-revenue buyback commitment plus a per-call micro-buy loop. The platform never sells and never burns.diff --git a/docs/trading-copilot.md b/docs/trading-copilot.mdindex 9c5f1be46..46163724f 100644--- a/docs/trading-copilot.md+++ b/docs/trading-copilot.md@@ -54,8 +54,10 @@ Arrow keys move through the menu, `Enter`/`Tab` selects, `Esc` closes.always visible and exact.- **Copy / Regenerate** — hover any reply to copy it or re-run the last turn.- **Stop** — the send button becomes a stop button while a reply streams.-- **Voice** — 🎙 dictates your message (browser `SpeechRecognition`); 🔊 speaks replies- in the agent's configured voice (ElevenLabs, with a browser-speech fallback).+- **Voice**: 🎙 dictates your message (browser `SpeechRecognition`); 🔊 speaks replies+ in the agent's configured voice (ElevenLabs, with a browser-speech fallback). The+ request names the agent, so an owner-cloned voice on the owner's saved ElevenLabs key+ plays here too instead of silently degrading to browser speech.- **Persistence** — the conversation, its data cards, and the executed-action log aresaved per wallet + network in `localStorage` and restored when you return. Live tradeproposals are intentionally **not** persisted, so a reload never resurrects a@@ -75,10 +77,16 @@ The model is **read-and-propose only**. It cannot sign, and it cannot bypass a g**structured proposal**, never executed on the server.3. The browser **re-quotes it live** and, only on your confirmation, calls the existingguarded endpoints:- - `POST /api/agents/:id/solana/trade` — enforces the spend guards+ - `POST /api/agents/:id/solana/trade`: enforces the spend guards([`api/_lib/agent-trade-guards.js`](../api/_lib/agent-trade-guards.js)), therug/honeypot firewall ([`api/_lib/trade-firewall.js`](../api/_lib/trade-firewall.js)),- and the custody audit (`agent_custody_events`).+ and the custody audit (`agent_custody_events`). The guards fail closed: a caller that+ passes neither pre-read limits nor the agent's `meta` gets the policy read from the+ agent's own row (a deleted agent has no policy and its spend is refused), and the+ ledger also meters a `per_counterparty_daily_usd` ceiling on what one agent can send+ to a single destination per day. The copilot's risk-limits card edits the per-trade+ cap, daily budget, max price impact, and kill switch; the counterparty cap is set+ from the wallet hub.- `PUT /api/agents/:id/trade/limits` — patches guardrails by key.A conversation can therefore never bypass a spend cap, the kill switch, or the firewall.@@ -102,13 +110,16 @@ SSE events:| `done` | `{ reply, proposals, citations }` | final reply || `error` | `{ code, message }` | turn failed |-The provider chain is free-first and OpenAI-compatible (Groq → OpenRouter, including any-`OPENROUTER_FALLBACK_KEYS` → NVIDIA, with paid OpenAI as the backstop), so the copilot-works without any paid key. Whenever the GCP project is configured, a keyless,-credits-billed **Vertex Gemini** rung is appended unconditionally as the final anchor,-so the chain always ends on a provider that cannot be evicted by a dead key. A 15s heartbeat-keeps the stream alive across slow tool rounds; the client aborts a genuinely dead stream-and offers Retry rather than hanging.+The provider chain is free-first and OpenAI-compatible, shared with the built-in chat+agent loop in [`api/_lib/llm-tool-chain.js`](../api/_lib/llm-tool-chain.js): Groq →+Cerebras → OpenRouter (including any `OPENROUTER_FALLBACK_KEYS`) → NVIDIA → SambaNova →+Mistral → Z.ai → Gemini (API key), with paid OpenAI as the backstop, each rung present+only when its key is set, so the copilot works without any paid key. Whenever the GCP+project is configured, a keyless, credits-billed **Vertex Gemini** rung is appended+unconditionally as the final anchor, so the chain always ends on a provider that cannot+be evicted by a dead key. Each round has a 45s deadline and fails over to the next rung on+any transport or non-2xx error. A 15s heartbeat keeps the stream alive across slow tool+rounds; the client aborts a genuinely dead stream and offers Retry rather than hanging.## $THREE@@ -125,6 +136,7 @@ plumbing — and never suggests, shills, or names another token on its own initi| Client mount (chat UI, cards, slash, persistence, voice) | [`src/agent-copilot.js`](../src/agent-copilot.js) || Wallet-hub tab wrapper | [`src/agent-wallet-hub/tabs/copilot.js`](../src/agent-wallet-hub/tabs/copilot.js) || Server (tool loop, SSE, proposals) | [`api/agents/copilot.js`](../api/agents/copilot.js) |+| Provider chain + streamed tool-call reader (shared with the chat agent loop) | [`api/_lib/llm-tool-chain.js`](../api/_lib/llm-tool-chain.js) || Markdown renderer | [`src/md.js`](../src/md.js) || UI contract tests | [`tests/agent-copilot-ui.test.js`](../tests/agent-copilot-ui.test.js) |diff --git a/docs/trading-experiment.md b/docs/trading-experiment.mdindex 50d07b0d6..4388d54a4 100644--- a/docs/trading-experiment.md+++ b/docs/trading-experiment.md@@ -240,11 +240,12 @@ is still fail-closed: unproven is never treated as safe.`isMayhemMode` lives on the pump.fun bonding curve, not the new-mint firehose, soit's read from the curve (one cached read per mint) and checked as **gate 0** in-`executeBuy` — before any throttle, wallet decrypt, or position row — so it covers+`executeBuy` (before any throttle, wallet decrypt, or position row) so it covers**every** trigger path (new_mint, intel, alpha, first_claim, radar, swarm). On by-default (`SNIPER_MAYHEM_FILTER=0` disables; `SNIPER_MAYHEM_STRICT=1` also skips-when the curve can't be read). A Mayhem mint is skipped with reason-`mayhem_excluded`.+default (`SNIPER_MAYHEM_FILTER=0` disables). A Mayhem mint is skipped with reason+`mayhem_excluded`. The gate also fails closed by default: a curve that still can't+be read after the RPC-chain retries is skipped with reason `mayhem_unknown`, and+`SNIPER_MAYHEM_STRICT=0` restores allow-on-unknown.## Funding it from the UIdiff --git a/docs/trading-surfaces.md b/docs/trading-surfaces.mdindex 2947dca8c..e6652d16c 100644--- a/docs/trading-surfaces.md+++ b/docs/trading-surfaces.md@@ -22,7 +22,7 @@ On top of that base layer:- **Oracle conviction** ([the conviction engine](oracle.md)) enriches coins across all five surfaces with its 0–100 fused score and tier.- **Price history** (candlesticks) comes from Birdeye with GeckoTerminal fallback.-- **Live trades** stream over server-sent events from `/api/pump/trades-stream` (PumpPortal websocket, relayed).+- **Live trades** stream over server-sent events from `/api/pump/trades-stream` (PumpPortal websocket, relayed). PumpPortal gates per-coin trade subscriptions behind an API key funded with at least 0.02 SOL; when it refuses one, the socket stays open and simply never delivers, so the relay forwards that refusal as an SSE `notice` event and the tape shows a degraded state instead of a lit "live" lamp over an empty panel. A malformed `mint` is refused up front with `400 invalid_mint`.- **Smart-money pedigree** comes from the proven-wallet ledger (`/api/intel/smart-money`).One naming trap for API users: `/radar` is served by `api/pump/coin-intel.js` and `/coin-intel` is served by `api/pump/intel.js`. The names look swapped; they are two distinct read models over the same engine.@@ -50,11 +50,11 @@ Four tabs:3. **Smart-Money Traders** — the cross-coin trader board.4. **What it learned** — the learned per-signal weights and outcome distribution. The engine grades its own predictions against real outcomes and shows you the weights it arrived at.-If the engine is still warming up (fresh deploy, empty tables), the page says so honestly instead of rendering blanks. Public, no account, refreshes every 15 seconds.+If the engine is still warming up (fresh deploy, empty tables), the page says so honestly instead of rendering blanks. Public, no account, refreshes every 15 seconds. A caller mistake is answered as one, never as an outage: an unknown `view`, a non-base58 `mint`, or a `minQuality` outside 0-100 gets a `400` (`invalid_view`, `invalid_mint`, `invalid_min_quality`) rather than the "warming up" state. The feed's `q` search runs in SQL over the whole observed feed, and a `verdict` filter (derived after the row is shaped) scans up to 600 recent rows before slicing to the requested page, so `?verdict=strong` on a busy feed no longer answers with the one strong coin that happened to sit on page one. The `traders` and `learning` views are whole-history aggregates and are edge-cached for 5 minutes; the feed stays on a 5-second cache.## Live Trade Feed — /trades-The proof stream. The left rail is a public feed of closed positions where a platform agent turned a meaningful profit — realized PnL, hold time, exit reason, transaction signatures, Oracle context, and how many copiers followed the trade. Filter by time window (1h → all-time) and minimum PnL. $THREE is pinned at the top of the rail.+The proof stream. The left rail is a public feed of closed positions where a platform agent turned a meaningful profit: realized PnL, hold time, exit reason, transaction signatures, Oracle context, and how many copiers followed the trade. Filter by time window (1h → all-time) and minimum PnL (`min_pnl_pct`, default 10). $THREE is pinned at the top of the rail. Each row's `multiple` is derived from the position's cumulative realized percentage rather than exit over entry, because a position that took initials first rewrites its cost basis and books only the closing leg's proceeds. Pages walk a `cursor` (an ISO 8601 timestamp; anything else is a `400 validation_error`) ordered by close time then position id, so two exits sharing a timestamp cannot reorder between pages.Click any trade (or paste any mint) and the center pane becomes a full analytics workstation for that coin:@@ -116,10 +116,13 @@ All read endpoints are public and IP rate-limited:# Radar list + market pulsecurl 'https://three.ws/api/pump/coin-intel?stats=1'-# Intel engine: scored feed, leaderboard, learned weights, one coin-curl 'https://three.ws/api/pump/intel?view=feed&limit=10'+# Intel engine: scored feed, leaderboard, learned weights, cross-coin traders, one coin+curl 'https://three.ws/api/pump/intel?view=feed&limit=10' # views: feed | leaderboard | learning | traderscurl 'https://three.ws/api/pump/intel?mint=<MINT>'+# Proven-wallet pedigree for one coin, or one wallet's reputation (both base58-validated)+curl 'https://three.ws/api/intel/smart-money?mint=<MINT>'+# Winning-trade feedcurl 'https://three.ws/api/trades/feed'diff --git a/docs/tutorials/claim-threews-name.md b/docs/tutorials/claim-threews-name.mdindex 4a799210d..9fa12871e 100644--- a/docs/tutorials/claim-threews-name.md+++ b/docs/tutorials/claim-threews-name.md@@ -120,7 +120,7 @@ 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`.+3. Confirms nobody has claimed it through three.ws and nobody owns it on-chain, otherwise `409 conflict`. Unlike the availability check, this on-chain lookup is a hard gate: if Solana RPC cannot answer, the mint stops with a retryable `503 upstream_unavailable` instead of attempting a transaction that would burn rent and fail.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`.@@ -170,6 +170,8 @@ const { data } = await r.json();`/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.+Add `&domains=1` to either direction (`?name=` or `?address=`) to also get the owner's full `.sol` holdings: the envelope gains `all_domains`, `favorite_domain`, and `domains_truncated`. It is opt-in because it costs two extra calls to the Bonfida index, and it is best-effort, so an index outage returns the plain envelope rather than an error.+**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.---@@ -277,6 +279,7 @@ Either way, the USDC lands in the wallet your `nich.threews.sol` points at — t- **`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.+- **`503 upstream_unavailable` on mint**: the pre-mint on-chain ownership check could not reach Solana RPC. Nothing was minted; retry in a moment.- **`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.diff --git a/docs/tutorials/pay-for-x402-service.md b/docs/tutorials/pay-for-x402-service.mdindex 5304b5ef5..fd2b32025 100644--- a/docs/tutorials/pay-for-x402-service.md+++ b/docs/tutorials/pay-for-x402-service.md@@ -222,7 +222,8 @@ If the result looks wrong but you were charged, note: x402 has **single-shot, no- **"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.+- **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. When the chain is unreadable and nothing is cached, `/api/x402-checkout?action=prepare` answers a typed `503 rpc_unavailable` with a `Retry-After: 15` header instead of an opaque 500; the agent-wallet path (`POST /api/x402-pay`) returns the same code with a note that no funds were transferred.+- **"The Solana wallet component could not be loaded"**: the Solana path fetches `@solana/web3.js` on demand from esm.sh, then jsdelivr and unpkg for the same pinned version, each under a deadline. All three failing means the host page's Content-Security-Policy is blocking third-party modules; the message names the hosts it tried and steers you to a Base wallet, which needs no third-party code.- **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.diff --git a/docs/tutorials/self-host-agent-backend.md b/docs/tutorials/self-host-agent-backend.mdindex 2f1867343..bd2878b04 100644--- a/docs/tutorials/self-host-agent-backend.md+++ b/docs/tutorials/self-host-agent-backend.md@@ -226,6 +226,8 @@ curl http://localhost:3000/api/healthzYou should get a JSON body starting `{"status":"ok","service":"3d-agent",...}`, with `uptime`, the resolved `version`, and a per-subsystem readiness block (`x402`, mail, and so on). Anything other than `"status":"ok"` names the subsystem that is unhappy.+Look at the response headers too. Every handler that goes through `wrap()` in `api/_lib/http.js` stamps its response with `x-brownout` (and `x-brownout-trace` when an upstream was involved), saying which provider or cache tier answered and how fresh the data is; the same seam honours an `x-brownout-chaos` directive for reproducing an outage on demand. Both are documented in [Brownout](../brownout.md), and neither needs any configuration on your fork.+Now open `http://localhost:3000` in a browser. You should land on the platform's home page. Click into the editor — drag any GLB onto it — confirm the avatar loads. Open DevTools → Console. **There should be no red errors.** If there are, the most common causes:- Database tables missing → re-run the schema in Step 3@@ -351,7 +353,7 @@ Up to this point, anyone embedding an agent from your platform is loading the bu**1. The embed generator derives its URL from the page origin.** The "Copy embed" output is built by `src/editor/publish.js`, which emits `` `${origin}/dist-lib/agent-3d.js` `` from the origin the dashboard is running on. Once your fork is served from `agent.yourcompany.com`, every copied snippet already points at your domain — no build constant to set.-**2. The bundle itself self-locates.** The element derives its API base from the script's own URL (`new URL(import.meta.url).origin`, see `src/element.js:123`), falling back to the page origin, and can be overridden per element with the `api-base` attribute. A third party who pastes your embed on `their-site.com` will have the script fetch agents from *your* domain, not theirs, and you can move infrastructure later without breaking existing embeds.+**2. The bundle itself self-locates.** The element derives its API base from the script's own URL (`new URL(import.meta.url).origin`, the `apiBase` resolution in `src/element.js`), falling back to the page origin, and can be overridden per element with the `api-base` attribute. A third party who pastes your embed on `their-site.com` will have the script fetch agents from *your* domain, not theirs, and you can move infrastructure later without breaking existing embeds.Verify with a smoke test: create a static HTML file and paste your embed:@@ -374,24 +376,26 @@ Open it in a browser. The agent should load and chat correctly. Check the Networ## Step 12 — Hardening: CORS-`api/_lib/http.js` exposes a `cors()` helper used by every paid route. The default policy is permissive (`Access-Control-Allow-Origin: *`) because the platform is designed to be embedded from anywhere. That's the right call for the public CDN script and for x402 endpoints (anyone with a wallet should be able to pay you).+`api/_lib/http.js` exposes a `cors()` helper that every route calls first. Its default policy is an allowlist, not a wildcard: with no `origins` option it reflects the request origin only when it is your `APP_ORIGIN`, one of the partner origins pinned in `isAllowedOrigin()` (x402scan, agentic.market, `*.ibm.com` and its Seismic CMS gateway), or `localhost` outside production. Any other origin gets no `access-control-allow-origin` header at all, so a session-cookie route is safe cross-origin by default.-For **internal** routes that shouldn't be called cross-origin — admin actions, account routes, the dashboard API — tighten CORS to your domain:+Two ways to widen it, both explicit at the call site:```jsimport { cors } from '../_lib/http.js';-export default async function handler(req, res) {- if (cors(req, res, {- origin: 'https://agent.yourcompany.com',- methods: 'GET,POST,OPTIONS',- credentials: true,- })) return;- // ... handler-}+// Public, embeddable from anywhere: the CC0 object manifest, x402 endpoints+// (anyone with a wallet should be able to pay you), the CDN script.+if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;++// A named list. Strings match exactly; a RegExp matches a family of hosts.+if (cors(req, res, {+ origins: ['https://agent.yourcompany.com', /^https:\/\/[a-z0-9-]+\.yourcompany\.com$/],+ methods: 'GET,POST,OPTIONS',+ credentials: true,+})) return;```-Audit which routes are sensitive. A simple rule: anything that uses the session cookie (`api/auth/*`, `api/dashboard/*`, account-scoped writes) should restrict CORS to your domain.+`credentials: true` only takes effect on a matched, non-wildcard origin (the browser forbids cookies with `*`). On your fork the one thing to change is the partner list in `isAllowedOrigin()`: replace those pinned origins with the sites you actually embed on, and set `APP_ORIGIN` to your domain so the default reflects it.---diff --git a/docs/tutorials/share-your-agent.md b/docs/tutorials/share-your-agent.mdindex 35068371e..ef3eb4eb5 100644--- a/docs/tutorials/share-your-agent.md+++ b/docs/tutorials/share-your-agent.md@@ -22,7 +22,7 @@ Go to [https://three.ws/my-agents](https://three.ws/my-agents). Sign in if you'rYou see a grid of every agent you own. Click the agent you want to share. The agent's profile page opens at a URL of this shape:```-https://three.ws/agent/d94d2a50-86fa-4d2e-b87b-580f7517aa4c+https://three.ws/agents/d94d2a50-86fa-4d2e-b87b-580f7517aa4c```The `<id>` is your agent's permanent identifier: a UUID, assigned when the agent is first saved. Copy the full URL from the browser's address bar and it works forever.@@ -67,7 +67,7 @@ Both produce QR codes that work with every modern phone camera. For most uses, aIf you don't want to leave the documentation flow, you can generate a code in two seconds using an inline service. Open this URL in a new tab, replacing the encoded URL with your agent link:```-https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=https%3A%2F%2Fthree.ws%2Fagent%2FYOUR_AGENT_ID+https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=https%3A%2F%2Fthree.ws%2Fagents%2FYOUR_AGENT_ID```The page returns a 400x400 PNG of the QR code. Right-click → Save As to download it.@@ -75,7 +75,7 @@ The page returns a 400x400 PNG of the QR code. Right-click → Save As to downloFor an SVG (which scales infinitely without loss, important for print):```-https://api.qrserver.com/v1/create-qr-code/?size=400x400&format=svg&data=https%3A%2F%2Fthree.ws%2Fagent%2FYOUR_AGENT_ID+https://api.qrserver.com/v1/create-qr-code/?size=400x400&format=svg&data=https%3A%2F%2Fthree.ws%2Fagents%2FYOUR_AGENT_ID```### Sizing the QR code for real-world use@@ -109,17 +109,17 @@ three.ws builds those tags automatically. You do not configure anything for the### Share the `/share` URL, not the bare profile URL-The agent profile page at `/agent/<id>` is a JavaScript app. Its HTML carries the generic three.ws card, because at the moment a crawler fetches it, the page has not yet loaded which agent it is about. So the platform serves a second, server-rendered address purely for crawlers:+The agent profile page at `/agents/<id>` is a JavaScript app. Its HTML carries the generic three.ws card, because at the moment a crawler fetches it, the page has not yet loaded which agent it is about. So the platform serves a second, server-rendered address purely for crawlers:```-https://three.ws/agent/<id>/share+https://three.ws/agents/<id>/share```-That page is plain HTML with your agent's real meta baked into the `<head>`, and a redirect that sends a human straight on to `/agent/<id>`. A recipient who taps the link never sees it; the unfurler does. This is the URL the Share button copies, and the one to paste anywhere a preview matters.+That page is plain HTML with your agent's real meta baked into the `<head>`, and a redirect that sends a human straight on to `/agents/<id>`. The older singular form, `/agent/<id>/share`, serves the same page, so links already in the wild keep unfurling. A recipient who taps the link never sees it; the unfurler does. This is the URL the Share button copies, and the one to paste anywhere a preview matters.### What the previews contain-When a platform fetches `https://three.ws/agent/<id>/share`, it sees:+When a platform fetches `https://three.ws/agents/<id>/share`, it sees:- **og:title**: `<agent name> · 3D AI Agent · three.ws`, or `<agent name> · 3D AI Agent on <chain> · three.ws` when the agent has been deployed on-chain.- **og:description**: Your agent's description (first 120 characters), the chain it is deployed on if any, then `3D AI Agent on three.ws`.@@ -131,7 +131,7 @@ When a platform fetches `https://three.ws/agent/<id>/share`, it sees:Both image paths target the 1200x630 standard OG aspect.-There is also a wallet variant, `/agent/<id>/share?wallet=1`, which swaps the copy and the deep link over to the agent's wallet view and always uses the generated card (the card is what carries the wallet identity). Use it when the thing you are sharing is the agent's wallet rather than the agent.+There is also a wallet variant, `/agents/<id>/share?wallet=1`, which swaps the copy and the deep link over to the agent's wallet view and always uses the generated card (the card is what carries the wallet identity). Use it when the thing you are sharing is the agent's wallet rather than the agent.### Preview freshness@@ -151,7 +151,7 @@ Don't ship a link without testing the preview first. There are three levels of c**Read the tags yourself.** One command, no third party, no cache in the way:```bash-curl -s https://three.ws/agent/YOUR_AGENT_ID/share \+curl -s https://three.ws/agents/YOUR_AGENT_ID/share \| grep -o '<meta[^>]*og:[^>]*>'```@@ -165,7 +165,7 @@ You should see your agent's name in `og:title` and a real image URL in `og:imageIf a preview looks wrong, the causes in order of likelihood are:-- **You shared `/agent/<id>` instead of `/agent/<id>/share`.** That gets the generic three.ws card. This is by far the most common one.+- **You shared `/agents/<id>` instead of `/agents/<id>/share`.** That gets the generic three.ws card. This is by far the most common one.- **The agent's name or description is unset** → set them in the editor and re-check.- **The avatar is private**, so the card falls back to the generated SVG rather than your avatar's thumbnail → set the avatar's visibility to unlisted or public in the [avatar dashboard](/dashboard/avatars).- **A platform cached an old version** → use its debugger's re-scrape button.@@ -192,7 +192,7 @@ Each platform has its own conventions. Here is what works on each.A line of plain text at the bottom of your email signature is the most under-used share context for personal agents.```-Talk to my AI: https://three.ws/agent/YOUR_AGENT_ID/share+Talk to my AI: https://three.ws/agents/YOUR_AGENT_ID/share```The recipient sees the link and the email client unfurls a preview card if it supports OG (Gmail, Apple Mail, Outlook all do). For agents that represent you personally, this is a way to let every email recipient interact with your AI persona without an explicit invite.@@ -202,7 +202,7 @@ The recipient sees the link and the email client unfurls a preview card if it suA simple post with the URL works, but the engagement is higher if you give context:```-Built a 3D AI agent that knows my work. Ask it anything → https://three.ws/agent/YOUR_AGENT_ID/share+Built a 3D AI agent that knows my work. Ask it anything → https://three.ws/agents/YOUR_AGENT_ID/share```X expands the URL into a large image card. The agent's preview image shows. Don't add a screenshot — let the auto-preview do the work; otherwise the platform sometimes hides the card.@@ -214,7 +214,7 @@ LinkedIn's link unfurling is conservative. The post performs better if you write```I built a personal AI assistant that visitors can talk to instead of reading my "About me" page. It knows my work, my availability, and what I'm building right now.-Try it: https://three.ws/agent/YOUR_AGENT_ID/share+Try it: https://three.ws/agents/YOUR_AGENT_ID/share```LinkedIn shows the preview card below your post. Engagement is highest within the first few hours, so post during your network's morning timezone.@@ -249,7 +249,7 @@ [email protected] │ ▓▓▓▓▓▓▓▓▓▓▓ ││ │└─────────────────┘Talk to my AI:- three.ws/agent/...+ three.ws/agents/...```Include the short URL beneath the QR so people who can't scan in the moment can type it later.@@ -298,11 +298,11 @@ Your share strategy:1. **Embed on your portfolio site** — Following [Embed in 30 seconds](/tutorials/embed-in-30-seconds), you've added the one-line embed to the home page of your portfolio. Visitors can talk to Mara without leaving your site.-2. **Public link in your email signature.** At the bottom of every email you send: "Available 24/7 to chat about projects → https://three.ws/agent/<MARA_ID>/share". Recipients can talk to Mara even when you're asleep, and the mail client unfurls her card inline.+2. **Public link in your email signature.** At the bottom of every email you send: "Available 24/7 to chat about projects → https://three.ws/agents/<MARA_ID>/share". Recipients can talk to Mara even when you're asleep, and the mail client unfurls her card inline.3. **QR on the back of your business card** — At networking events, instead of "I'll email you next week", you say "Scan my card, ask Mara about my work, and book a call directly through her if it's a fit". The conversation happens on your terms, on her schedule.-4. **Social preview on launch posts** — Every quarter when you post a portfolio update on LinkedIn, you include the agent link. The auto-generated preview card shows Mara's 3D avatar with the title "Mara — Alex's UX consultant", which catches more attention than a plain text post.+4. **Social preview on launch posts.** Every quarter when you post a portfolio update on LinkedIn, you include the agent link. The auto-generated preview card shows Mara's 3D avatar under the title "Mara · 3D AI Agent · three.ws", with the first 120 characters of her description as the card text, which catches more attention than a plain text post.Each channel uses the right format for its medium. The underlying agent is one thing, maintained in one place, that you've defined once.@@ -333,9 +333,9 @@ So plan on the URL being reachable by anyone who has it. For genuinely internal## What you learned-- Every agent has a permanent public URL at `https://three.ws/agent/<id>`, where the id is a UUID+- Every agent has a permanent public URL at `https://three.ws/agents/<id>`, where the id is a UUID (the singular `/agent/<id>` form redirects there)- The URL is stable across body swaps, system prompt updates, and skill changes-- Rich previews come from `https://three.ws/agent/<id>/share`, a server-rendered page that carries the agent's real Open Graph, Twitter Card, and Farcaster Frame meta and forwards humans to the profile+- Rich previews come from `https://three.ws/agents/<id>/share`, a server-rendered page that carries the agent's real Open Graph, Twitter Card, and Farcaster Frame meta and forwards humans to the profile- The Share button on the profile page shows that card and copies the `/share` link for you- Nothing is pre-rendered and nothing needs purging: edits appear in new previews within minutes, and the stale copy you see is usually the sharing platform's own cache- A QR code generated from any standard service points to that URL for offline sharediff --git a/docs/tutorials/write-a-guard.md b/docs/tutorials/write-a-guard.mdindex 78c96033c..6604e106c 100644--- a/docs/tutorials/write-a-guard.md+++ b/docs/tutorials/write-a-guard.md@@ -14,6 +14,8 @@ We will build `check-fetch-timeouts`: a guard that refuses to build when serverThis is a real class of bug. A `fetch` with no timeout hangs until the platform's own limit kills it, so one slow upstream turns into stacked requests, then a cold pool, then a 502 on an endpoint that has nothing to do with the slow service. It is invisible in review because the line looks completely normal.+This guard has since shipped for real: [`scripts/check-fetch-timeouts.mjs`](../../scripts/check-fetch-timeouts.mjs) runs in the `gate` chain as `npm run check:fetch-timeouts`, is registered in `data/guards.json` with an `append` proof, and is covered by [`tests/check-fetch-timeouts.test.js`](../../tests/check-fetch-timeouts.test.js). The shipped version is stricter than the one built below (it balances parentheses to read each call's real extent, treats the shared bounded wrappers such as `fetchUpstream` as satisfying the rule, judges every `fetch` under `api/` whatever its URL, and skips a `fetch` that only appears inside a string). Follow the steps here to learn the shape, using a throwaway id such as `check-fetch-timeouts-tutorial` for the files you create, then read the shipped guard for the finished form.+---## Step 1: write the checkerdiff --git a/docs/ui-juice.md b/docs/ui-juice.mdindex 5ffae990b..6cb3656dc 100644--- a/docs/ui-juice.md+++ b/docs/ui-juice.md@@ -18,8 +18,13 @@ Three guarantees hold for every export:`public/tokens.css` (`--duration-*`, `--ease-*`). No raw millisecond literals.- **Reduced-motion-safe.** That token file zeroes every `--duration-*` under`@media (prefers-reduced-motion: reduce)`. `reducedMotion()` reads the computed- token, so each primitive lands on its correct final state with no animation —- automatically, with an explicit JS fallback path as belt-and-braces.+ token, so each primitive lands on its correct final state with no animation,+ automatically, with an explicit JS fallback path as belt-and-braces. The same+ media block also floors every animation and transition on the page to 1ms,+ whether or not it was authored through a token; only elements marked+ `data-motion="essential"` (or `.motion-keep`), `aria-busy` regions, progress+ bars, spinners and loaders keep their motion, because a frozen spinner reads as+ a hung page.- **Real values only.** These are transition helpers over real numbers/series.They never fabricate or sample inputs.@@ -47,6 +52,10 @@ and the ES module import. The classes the helpers attach all live under theAnimate a number between two real values via `requestAnimationFrame`, preservingthe caller's formatting. Cancels any in-flight count-up on the same element.Reduced motion → final value instantly. Stashes the target on `el.dataset.juiceVal`.+The clock starts from the first frame's own timestamp and progress is clamped to+`[0, 1]`, so no frame ever paints a value outside `[from, to]` (a `rAF` timestamp+behind `performance.now()` used to drive the easing negative and flash garbage+like "-42797%").```jscountUp(volEl, 1200, 1875, { format: (n) => '$' + Math.round(n).toLocaleString() });@@ -116,6 +125,11 @@ flip.play();### `liveDot(state?, opts?)` / `setLiveDot(el, state, label?)`Markup + in-place updater for an SSE status indicator mirroring the swarms`.sw-live` vocabulary. States: `live` | `connecting` | `idle` | `error`.+`setLiveDot` also keeps the state pinned: when the badge sits inside a+`data-i18n-html` line, the async translation pass rewrites that line from a+frozen snapshot of the original markup (badge included), so the helper watches+the container's child list and re-stamps the last requested state and label+whenever the markup around the badge is replaced.```jsheader.insertAdjacentHTML('beforeend', liveDot('connecting'));diff --git a/docs/ux-flows/01-onboarding-creation.md b/docs/ux-flows/01-onboarding-creation.mdindex 3bd22280c..62fe2002f 100644--- a/docs/ux-flows/01-onboarding-creation.md+++ b/docs/ux-flows/01-onboarding-creation.md@@ -17,12 +17,12 @@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.+ 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 `/agents/<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`.+- **Success state:** A real deployed agent + public widget, an embeddable `<script>` snippet, a live `/agents/<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).@@ -34,17 +34,18 @@- **Prerequisites / gates:** Anonymous-friendly for the base-avatar editor / template / studio / direct GLB upload (guest avatar staged in IndexedDB; auth deferred to `/create-review`). **Auth-gated paths:** the selfie card (`requireAuthForSelfie` → redirect `/login?next=/create/selfie`), the prompt card (redirect `/login?next=/create/prompt`), and the video card (redirect `/login?next=/create/video`). 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`. The page now opens with a four-card **intent hub**: "Build an AI agent" → `/create-agent`, "Make a 3D avatar" → `#avatar-options` (tagged "You're here"), "Generate a 3D model" → `/forge`, "Launch a token world" → `/launchpad`. The avatar method cards live below at `#avatar-options`.- 2. `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. The prompt card cycles 7 example prompts with a reduced-motion-aware typewriter (`#card-prompt-example`).- 3. (optional) If `?fork=<id>` present: `handleFork` runs immediately, POSTing `/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`.+ 2. `boot()` probes `/api/config` for the `videoAvatar` feature flag with three outcomes: off dims the video card with a "Coming soon" chip and CTA (keyboard activation gets the same explanation as a click), an unanswered probe keeps the card live and re-asks on activation, and on leaves it untouched. For signed-in users with avatars it loads `/api/avatars` (the `{ avatars }` envelope) to render a "Start from one of yours" remix strip; a thumbnail whose storage object expired falls back to the silhouette. The prompt card cycles 7 example prompts with a reduced-motion-aware typewriter (`#card-prompt-example`).+ 3. (optional) If `?fork=<id>` present: `handleFork` runs last, after every card is wired, POSTing `/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`. A remix that cannot load renders a persistent inline alert in `#create-alert-slot` ("That remix could not be loaded") with "Try the remix again" and "Start something new instead" (which drops `?fork=` from the URL), not a toast, so the visitor is never left on a page of cards wired to nothing.4. Choose a creation method card: **Customize a base avatar** (`card-default-editor` → `AvatarCreator.openDefaultEditor`), **Describe it to 3D** (`card-prompt` → `/create/prompt`, auth-gated), **Start with a template** (`card-customize` → `createFromTemplate`), **Scan yourself to 3D** (`card-selfie` → `/create/selfie`, auth-gated), **Talking avatar video** (`card-video-avatar` → `/create/video`, feature-flagged + auth-gated), **Living world (Cosmos)** (`card-cosmos` → `/cosmos`), **Upload your own GLB** (`card-upload-glb` → `#glb-input`), or **Avatar Studio (beta)** (`card-agent-studio` → `/create/studio`).5. (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`.6. (optional) Editor/Template path: the in-page `AvatarCreator` produces a GLB blob → `stageAndReview` → `/create-review`.7. (optional) Remix strip: click a saved avatar thumbnail → `handleFork(av.id)` (same fork path as step 3).+ 8. (optional) Android share-sheet handoff: a file shared into the installed app is POSTed to `/create/share`, parked in the Cache API by `public/share-target-sw.js`, and the visitor lands here with `?shared=glb` (a `.glb`, pulled back out through `src/shared/share-target.js` and fed into the upload path), `?shared=1` (a photo, handed on untouched to `/create/selfie?shared=1`), `?shared=nosw` (the worker was not installed yet; share again) or `?shared=error`. The read is one-shot, so a reload never re-attaches the file.- **Decision points / branches:** intent hub (agent wizard / avatar options / Forge / launchpad) vs direct card pick; fork vs fresh; eight creation method cards (base editor / prompt / template / selfie / video / Cosmos / upload / studio); 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). External avatar-platform 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).+- **Empty / error states:** `status-toast` for invalid GLB, quota-limit, a feature probe that could not reach three.ws, and a shared file that was not a `.glb`; fork failure uses the inline alert; video card carries a "Coming soon" chip when the flag is off; the boot blackout clears after 6 s even if `/api/auth/me` never answers (treated as signed out, the auth-gated cards re-check at `/login`); 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) + ~5 optional (fork, upload, editor produce, remix, shared file).---@@ -96,15 +97,15 @@- **Steps (N):**1. Land; `boot()` resolves auth. Signed out, the ship CTA relabels to "Sign in to ship <name> →" and a "no account needed to build" note (`#build-free-note`) unhides. A fresh guest draft (see below) or a guest-companion claim (`peekGuestAgent()` carries the companion's name in) can prefill the form.2. **Step 0 (Basics).** Enter name (required, ≤60), description (≤280), and tags (≤8, Enter/comma to add). (optional) Use the **"Build it for me"** AI box: type a one-line brief (or a chip / "✦ Surprise me") → POST `/api/agents/suggest-spec` → the returned spec fills the whole wizard and jumps to Review. Guests can generate too; the guest rate limit maps a 429 to a sign-in nudge. 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.+ 3. **Step 1, Model.** Choose a body via one of four tabs (a real ARIA tablist: arrow keys and Home/End move between them): **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; signed out it never fires the request and shows "Sign in to reuse an avatar you already made" with a Sign in button that saves the draft first), **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), and profile/system prompt (≤2000). (optional) Run the **onboarding interview** (`#interview-*`): answer any of the shared `INTERVIEW_QUESTIONS` in your own words → POST `/api/persona/interview` runs them through the platform LLM chain and writes the extracted paragraph into the profile field (editable), with tone tags rendered as chips; the structured result (traits, tone tags, vocabulary, answer provenance) rides in state until the agent exists. Click "Next" (soft tip if publishing without category+prompt).6. **Step 4, Voice.** Pick **Built-in voice** or **Clone your voice** (`data-voice` buttons). Choosing custom mounts `VoiceSetup` in `bind:'later'` mode: record or upload a short sample (validated in-browser, with inline BYOK ElevenLabs key entry via `PATCH /api/user/provider-keys`); the sample is held in memory and bound after create. Click "Next".7. **Step 5 (Review).** Editable summary grid (each row jumps back to its step). Toggle "Publish to marketplace" (`#f-publish`, default on). Click "Create" (or "Sign in to ship…" when signed out, which round-trips through `/login` and resumes here).8. `submit()`: (a) resolves the body to a real owned avatar, via `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 a custom voice sample is held → `voiceSetup.bindTo(agent.id)` clones it onto the new agent (non-fatal: a failure becomes a soft warning); (d) if publish opted-in AND category+prompt present → POST `/api/marketplace/agents/:id/publish`; (e) if the interview produced a result → POST `/api/agents/:id/persona/save` persists the structured persona with interview provenance (also best-effort).- 9. Success panel: "<name> is ready", 3D preview if public, and buttons: **Go live** (`/agent/<id>/wallet#activate`, primary; claims the on-chain welcome grant), Fund wallet (`/agent/<id>/wallet#deposit`), Open (`/agent/<id>`), Edit (`/agent/<id>/edit`), Widget Studio (`/studio?model=<avatar_model_url>`), and Give it a voice (`/voice`).+ 9. Success panel: "<name> is ready", 3D preview if public, and buttons: **Go live** (`/agents/<id>/wallet#activate`, primary; claims the on-chain welcome grant), Fund wallet (`/agents/<id>/wallet#deposit`), Open (`/agents/<id>`), Edit (`/agents/<id>/edit`), Widget Studio (`/studio?model=<avatar_model_url>`), and Give it a voice (`/voice`).- **Guest draft autosave:** every input change debounce-saves (600 ms) to `localStorage['threews:create-agent:draft']` once the form has real content, with a `beforeunload` flush; drafts expire after 7 days (`src/create-agent-draft.js`). A returning guest resumes on the exact saved step with "Resumed your saved draft. [Start fresh]". A picked upload `File` cannot survive navigation: the draft marks it lost, downgrades the model to "Add later", and asks the user to re-attach on the model step. Creation stops the autosave so a shipped agent never resurrects as a draft.-- **Decision points / branches:** signed-in ship vs signed-out login round-trip (draft preserved); AI-generated spec vs manual form; model tab (starter/library/upload/skip); interviewed persona vs hand-typed prompt (a fresh AI-spec fill resets the interview so a new concept never inherits the previous voice); built-in voice vs cloned sample; 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); resume draft vs "Start fresh"; per-step jump-back via stepper pips and review "Edit" buttons.+- **Decision points / branches:** signed-in ship vs signed-out login round-trip (draft preserved); AI-generated spec vs manual form; model tab (starter/library/upload/skip); interviewed persona vs hand-typed prompt (a fresh AI-spec fill resets the interview so a new concept never inherits the previous voice); built-in voice vs cloned sample; 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); resume draft vs "Start fresh"; per-step jump-back via stepper pips (real buttons, so a completed step is a tab stop and the current one carries `aria-current`) and review "Edit" buttons.- **External calls / dependencies:** `getMe()` (account.js); `POST /api/agents/suggest-spec` (AI spec generator); `POST /api/persona/interview` (interview extraction); `GET /api/avatars` (library tab); `saveRemoteGlbToAccount` (account.js → presign + R2 upload + commit); `POST /api/agents`; `POST /api/agents/:id/voice/clone` (via `VoiceSetup.bindTo`) + `PATCH /api/user/provider-keys` (BYOK key); `POST /api/marketplace/agents/:id/publish`; `POST /api/agents/:id/persona/save`.- **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 go-live/fund/view/edit/embed.- **Empty / error states:** 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; guest generate 429 → "That's the guest generation limit. Sign in to keep going, or fill the form in by hand."; publish, voice-bind, and persona-save failures are non-fatal (soft warning, agent still created); submit failure re-enables the form with an error message; lost upload on draft resume → re-attach prompt.@@ -115,17 +116,17 @@### 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.+- **Prerequisites / gates:** **Auth required**: the submit endpoint returns 401 → page redirects to `/login` with `next=/create/prompt?prompt=<text>`, so the typed prompt survives the round trip through the `?prompt=` deep link (also enforced upstream by `/create`). No wallet/$THREE gate.- **Steps (N):**1. Land on the **compose** step; type a text prompt (3 to 600 chars; live counter), or dictate it: a mic button (`src/voice/prompt-dictation.js`, browser SpeechRecognition with an NVIDIA Riva fallback) mounts next to the textarea only when the browser can dictate. (optional) Click an example chip to fill the prompt; around July 4 (July 1-5, viewer local time) seasonal preset chips are injected via `src/shared/festive-presets.js`. A `?prompt=<text>` deep-link prefills the composer (no auto-submit).- 2. Click "Generate" (or Cmd/Ctrl+Enter). `start()` → switches to the **building** step, starts the elapsed clock, sets progress to 8%. Escape (or the cancel button) aborts the build back to compose.+ 2. Click "Generate" (or Cmd/Ctrl+Enter). `start()` → switches to the **building** step, starts the elapsed clock, sets progress to 8%. Escape (or the cancel button) aborts the build back to compose; Cancel is gated on the building step rather than on an in-flight request, so it still works after a failure. Every build claims a run token, and a cancelled or superseded run can no longer write to the screen (starting a second build no longer lets the abandoned poll drop the old avatar onto the done screen).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 (using the owner's presigned URL for private avatars), 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.-- **Decision points / branches:** compose vs building vs done; typed vs dictated prompt; success vs failure (`mapSubmitError`/`friendlyJobError` map codes to human messages: rate-limited, unconfigured→suggest selfie, no-face, NSFW, timeout, OOM); cancel mid-build; 401 mid-flow → login redirect; "Make another" resets to compose.+- **Decision points / branches:** compose vs building vs done; typed vs dictated prompt; success vs failure (`submitError`/`jobError` build an `ApiError` carrying human copy plus whether retrying can help: rate-limited quotes the server's `retry_after`, unconfigured and needs-BYOK suggest the selfie scanner without a retry, a full library (402 `plan_limit`, or a job that lost the race mid-build) links to `/dashboard` and `/pricing` without a retry, no-face, NSFW, timeout, OOM); cancel mid-build; 401 mid-flow → login redirect carrying the prompt; "Make another" resets to compose (bound once at module scope).- **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.+- **Empty / error states:** Compose: inline `#compose-error` if prompt < 3 chars. Building: the screen stops claiming work is in flight (orb frozen, bar muted, phase line and Cancel hidden) and `#build-error` offers "Edit prompt" always, "Try again" only for a retryable failure (held as a "Try again in Ns" countdown while a Retry-After runs), and the dashboard / pricing links for a full library; a fetch-level failure says the engine could not be reached rather than "something went wrong"; 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).---@@ -137,17 +138,17 @@- **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). The live shutter gate and the still-photo check now judge frames through one shared threshold module (`src/selfie-gates.js`), and a blocked shutter surfaces the grader's retake reason in the capture UI (poor lighting, off-angle) instead of silently refusing to fire. Each added frontal photo is also quality-assessed on-device (`src/selfie-refine.js` `assessPhoto`), surfacing `#quality-notice` warnings (blurry / drawing / no face) before the user waits out a full build. The page also cross-links `/image-to-3d` for object (non-face) photos.+ 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). The live shutter gate and the still-photo check now judge frames through one shared threshold module (`src/selfie-gates.js`), and a blocked shutter surfaces the grader's retake reason in the capture UI (poor lighting, off-angle) instead of silently refusing to fire. Lighting is graded before blur (a dark frame trips both, and light is the root cause), a blown-out face is caught by the share of clipped pixels as well as mean luma (the badge reads "Blown out" and the hint says to move out of direct light), and the live blur floor is a measured 12 (Laplacian stddev on the 64px crop; the old 3.5 never fired on a real photograph). Photos shared from the Android share sheet arrive with `?shared=1` and fill frontal, then left and right, in order. Each added frontal photo is also quality-assessed on-device (`src/selfie-refine.js` `assessPhoto`), surfacing `#quality-notice` warnings (blurry / drawing / no face) before the user waits out a full build. The page also cross-links `/image-to-3d` for object (non-face) photos.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).+ 6. `pollUntilDone` polls `GET /api/avatars/regenerate-status?jobId=...` (1.5s first, then 3s w/ backoff, 8 to 10 min timeout), dispatching `selfie:progress` labels (mesh → geometry → rigging → finishing). A `done` job with no `resultAvatarId` (the server's materialize stage lost a transient race) is polled up to three more times before it is treated as final, and a failure whose `errorKind` is `input` is relayed in the server's own words when no local mapping matches, so "your library is full" is never rewritten as "try a clearer photo".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: "Open my avatar" (`#done-save-btn`, optional PATCH name → `/avatars/<id>`), "List on marketplace" (`#done-list-btn`, PATCH name + visibility public → `/marketplace/avatars/<id>`), "Customize in editor" (`#done-editor-btn` → `/avatars/<id>/edit`), or "Not quite right? Try again" (`#done-regen-btn`, reset to capture).- **Abandoned jobs finish server-side (platform mode):** the browser poll is no longer the only engine. `api/cron/reconstruct-sweep.js` (every 5 min) picks up open reconstruct jobs quiet for over 3 minutes and runs the same finalize stages, so closing the tab mid-build still lands the avatar in the user's library (30-day rescue window). BYOK jobs stay browser-driven (the server has no user key).- **Decision points / branches:** platform vs BYOK mode (key step or not); camera vs upload; frontal-only vs +side angles; photo quality warnings vs proceed; 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.+- **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 tasks-vision for the client face check (bundled from the npm dependency; `src/shared/mediapipe-assets.js` serves the WASM runtime and the face landmarker model from the vendored copy under `public/vendor/mediapipe` first and a CDN second, and fetches the segmenter and face-detector models from Google's bucket under a deadline, so capture survives a blocked CDN); 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.+- **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; the error banner scrolls into view on first appearance so a tap on the sticky submit bar from higher up the page never fails silently; 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).---@@ -155,33 +156,33 @@### Talking Avatar Video: `/create/video`- **Source:** `pages/create/video.html` + `src/create-video.js` (imports `src/account.js` for `apiFetch`; the page also loads `src/wallet-auth.js` inline for the sign-in button)- **Entry point:** The "Talking avatar video" card on `/create` (`card-video-avatar`), which is both feature-flagged and auth-gated there. Also reachable from the Video capability tile on `/create-review` and directly by URL.-- **Prerequisites / gates:** **Auth required.** `boot()` fetches `/api/auth/me` first and `location.replace('/login?next=/create/video')` on a non-OK response or a missing user, before anything renders. **Feature-flagged upstream:** `/create` greys the card out when `/api/config` reports `videoAvatar` off. **Quota:** the generate endpoint returns `402 free_trial_used` after the one free video. No wallet/$THREE gate.+- **Prerequisites / gates:** **Auth required.** `boot()` fetches `/api/auth/me` first and `location.replace('/login?next=/create/video')` on a non-OK response or a missing user, before anything renders. **Feature-flagged upstream:** `/create` greys the card out when `/api/config` reports `videoAvatar` off. **Quota:** the generate endpoint returns `402 free_trial_used` after the one free video. **Renderer probe:** `GET /api/avatar/video-generate` answers `{ available, reason, free_generations }`; when the GPU worker is unconfigured the page shows a "Video rendering is offline" banner (pointing at `/avatar-studio` and `/create/prompt`) and keeps Generate disabled with the hint "Generation is paused while the renderer is offline.", and a 503 from the real POST flips the same state. No wallet/$THREE gate.- **Steps (N):**- 1. Land; `loadAvatars()` fetches `GET /api/avatars` and fills the avatar strip, auto-selecting the first one. With no owned avatars it falls back to a single "Default" thumbnail backed by `/avatars/default.glb`, so the page is never empty.+ 1. Land; `loadAvatars()` fetches `GET /api/avatars` and fills the avatar strip, auto-selecting the first one. With no owned avatars the strip shows "No avatars yet. Make one and it shows up here, ready to speak." with a "Create an avatar" link, and a failed list shows "We could not load your avatars" with Retry (a failure is never rendered as an empty library); in both cases the stage shows `/avatars/default.glb` as decoration only, never as a generation source. The viewer starts with no `src`, so the login redirect cannot abort a model download mid-flight.2. Pick an avatar from the strip (click, or Enter/Space; each thumb is a real `role="button"` with an aria-label). Private avatars come back from the list endpoint with no CDN URL, so `selectAvatar` lazily resolves a short-lived signed URL from `GET /api/avatars/:id` and guards against the user switching avatars mid-await. The pick renders in the `model-viewer` stage.- 3. Add audio: drag-drop onto `#audio-drop` or pick a file. A non-audio drop is rejected with a toast. The chosen filename shows with a clear button. "Generate" stays disabled until both an avatar and an audio file are present.+ 3. Add audio: drag-drop onto `#audio-drop` or pick a file. A non-audio drop is rejected with a toast. The chosen filename shows with its duration and size, an inline `<audio>` preview and a clear button; drops are accepted by MIME type or by extension. "Generate" stays disabled until both an avatar and an audio file are present, and the `#generate-hint` line under it always says what is still missing ("Pick an avatar to generate.", "Add an audio clip to generate.") or, once ready, roughly how many 3.72 s clips the audio will render into.4. (optional) Type a direction prompt in `#prompt-input` to steer the render.5. Click "Generate". `uploadAudio` requests `POST /api/avatar/presign-audio` (declaring `bytes`, capped at 64 MB) and PUTs the file to R2. A failed presign is reported as an error: there is no data-URI fallback, since `video-generate` only accepts an https three.ws-hosted `audio_url`.- 6. `POST /api/avatar/video-generate` `{ image_url, audio_url, avatar_id, prompt }` returns `{ job_id }`.- 7. `pollJob` polls `GET /api/avatar/video-status?job_id=…` every 5 s with a 20-minute deadline. The status endpoint reports `progress` plus the worker's planned `segments` count and measured `audio_seconds`, so the label names the work ("Rendering N clips… X%", one 3.72 s clip per segment) instead of a bare percent. Transient non-2xx and network errors are swallowed and retried until the deadline.+ 6. `POST /api/avatar/video-generate` `{ audio_url, avatar_id, prompt }` returns `{ job_id }`. The server resolves `avatar_id` to a real reference image (the stored thumbnail, else a cached portrait render through the `/api/avatar/render` pipeline), so the browser never sends an `image_url`; it used to send the GLB, which the worker wrote into its reference image and failed on minutes later.+ 7. `pollJob` polls `GET /api/avatar/video-status?job_id=…` every 5 s with a 20-minute deadline. The status endpoint reports `progress` plus the worker's planned `segments` count and measured `audio_seconds`, so the label names the work ("Rendering N clips… X%", one 3.72 s clip per segment) instead of a bare percent. Transient non-2xx and network errors are retried, but six in a row (30 s) stop the poll with "Lost contact with the render job", and a `failed` job relays the worker's own error text.8. On `status: 'done'`: the returned `video_url` loads into the result `<video>` with a Download link and a "Make another" button that resets to idle.-- **Decision points / branches:** signed-in vs redirect to login; owned avatars vs the default-avatar fallback; public (CDN URL) vs private (signed-URL resolve) avatar; presign success vs presign failure (413 too-large / 429 rate-limit / generic, each with its own message; no data-URI fallback exists); prompt vs no prompt; done vs failed vs 20-minute timeout; `402 free_trial_used` retargets the retry button to "Upgrade plan" pointing at `/dashboard`.-- **External calls / dependencies:** `GET /api/auth/me`; `GET /api/avatars`; `GET /api/avatars/:id` (signed GLB URL); `POST /api/avatar/presign-audio` + R2 PUT; `POST /api/avatar/video-generate`; `GET /api/avatar/video-status`. Rendering runs on the talking-head worker, not in the browser.+- **Decision points / branches:** signed-in vs redirect to login; renderer available vs offline (banner, Generate disabled); owned avatars vs the empty-strip note vs a failed list with Retry; public (CDN URL) vs private (signed-URL resolve) avatar; presign success vs presign failure (413 too-large / 429 rate-limit / generic, each with its own message; no data-URI fallback exists); prompt vs no prompt; done vs failed vs 20-minute timeout; `402 free_trial_used` retargets the retry button to "Upgrade plan" pointing at `/dashboard`.+- **External calls / dependencies:** `GET /api/auth/me`; `GET /api/avatar/video-generate` (availability probe); `GET /api/avatars`; `GET /api/avatars/:id` (signed GLB URL); `POST /api/avatar/presign-audio` + R2 PUT; `POST /api/avatar/video-generate`; `GET /api/avatar/video-status`. Rendering runs on the talking-head worker, not in the browser; both worker calls go through the shared upstream breaker (a submit is never retried, a status read is).- **Success state:** A downloadable lip-synced talking-head clip of the user's own avatar, playable in-page, with a one-click path to generate another.-- **Empty / error states:** No avatars falls back to the default thumbnail rather than an empty strip. An avatar whose model cannot be resolved toasts "Could not load this avatar's 3D model. Pick another one." and leaves Generate disabled. Audio upload failure, job-start failure, worker failure, and the 20-minute timeout each render in `#error-area` with a retry that returns to idle. Free-trial exhaustion swaps retry for an upgrade link.+- **Empty / error states:** No avatars shows the create-one note; a failed avatar list shows a retryable error; the offline banner covers an unconfigured renderer. An avatar whose model cannot be resolved toasts "Could not load this avatar's 3D model. Pick another one." and leaves Generate disabled. Audio upload failure, job-start failure, worker failure, and the 20-minute timeout each render in `#error-area` with a retry that returns to idle. Free-trial exhaustion swaps retry for an upgrade link.- **Step count:** 4 required (pick avatar → add audio → generate → poll to done) + ~2 optional (direction prompt, download / make another).----### Agent Editor: `/agent/<id>/edit` (and the retired `/agent/new`)-- **Source:** `pages/agent-edit.html` + `src/agent-edit.js` (vercel route `/agent/<id>/edit` → `/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:** "Edit" buttons on agent profiles and the create-agent success panel. **`/agent/new` no longer serves this editor:** the bare route 301s to `/create-agent`, and `/agent/new?avatar_id=` / `?avatar_glb=` rewrites to `create-agent.html`, where `applyAvatarHandoff()` pre-seeds the wizard's model step (marketplace "Start an agent with this avatar" now lands in the wizard).+### Agent Editor: `/agents/<id>/edit` (and the retired `/agent/new`)+- **Source:** `pages/agent-edit.html` + `src/agent-edit.js` (vercel routes the canonical `/agents/<id>/edit` and the legacy `/agent/<id>/edit` both → `/agent-edit.html`, and the module accepts either path segment; 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:** "Edit" buttons on agent profiles and the create-agent success panel. **`/agent/new` no longer serves this editor:** the bare route 301s to `/create-agent`, and `/agent/new?avatar_id=` / `?avatar_glb=` rewrites to `create-agent.html`, where `applyAvatarHandoff()` pre-seeds the wizard's model step (marketplace "Start an agent with this avatar" now lands in the wizard). Autopilot receipts link here as `/agents/<id>/edit?tab=knowledge#mem-<memoryId>`: the cited memory is highlighted and scrolled into view once the list renders, and the `?tab=` section scroll stands down for it.- **Prerequisites / gates:** **Auth required.** Loading an agent you don't own (or with no session) hits a 401, which stashes `login_redirect` and redirects to `/login`. No $THREE gate.- **Steps (N):**- 1. Navigate to `/agent/<id>/edit`; `loadAgent()` fetches `GET /api/agents/:id` and the full editor renders (`render()`): identity (name/description), 3D body (starter/library picker/upload via `avatar-gallery-picker.js` + `AvatarCreator`), skills, animations, **gesture slots** (per-agent bindings for the fixed gesture vocabulary, saved via `#anim-slots-save`, previewable on `/gestures`), voice, wallet chip, and the embed/manifest panels.+ 1. Navigate to `/agents/<id>/edit`; `loadAgent()` fetches `GET /api/agents/:id` and the full editor renders (`render()`): identity (name/description), 3D body (starter/library picker/upload via `avatar-gallery-picker.js` + `AvatarCreator`), skills, animations, **gesture slots** (per-agent bindings for the fixed gesture vocabulary, saved via `#anim-slots-save`, previewable on `/gestures`), voice, wallet chip, and the embed/manifest panels. The wallet panel reads balances from `GET /api/portfolio/summary` (`{ usd, native, tokens }` per wallet), sends through `POST /api/portfolio/send` with `asset: 'native'` or the USDC mint and the typed decimal amount (echoing the returned `tx_hash`), and the Fund modal's deposit QR tries qrserver then quickchart before hiding the image behind the copyable address. The Social tab hides Connect X with a stated reason when X OAuth is not configured on the deployment (`?x=unconfigured` after a bounced connect). Embed and manifest panels emit the canonical `/agents/<id>` URLs.2. Edit any field → changes persist through the same verified endpoints (PUT `/api/agents/:id`, animations endpoint, etc.).- **Decision points / branches:** existing agent (URL id) vs the retired new-draft path (bare `/agent/new` now redirects to the `/create-agent` wizard before this page ever loads); signed-out → login; gesture overrides set vs cleared.-- **External calls / dependencies:** `GET /api/agents/:id`; `PUT /api/agents/:id`; `PUT /api/agents/:id/animations`; `GET /api/agents/:id/manifest`; avatar APIs via `saveRemoteGlbToAccount` / gallery picker.+- **External calls / dependencies:** `GET /api/agents/:id`; `PUT /api/agents/:id`; `PUT /api/agents/:id/animations`; `GET /api/agents/:id/manifest`; `GET /api/portfolio/summary`; `POST /api/portfolio/send`; `GET /api/auth/x/connect?agent_id=` (redirect); avatar APIs via `saveRemoteGlbToAccount` / gallery picker.- **Success state:** The agent loaded into the full editor for fine-grained configuration, with saves confirmed inline (e.g. "Saved N gesture overrides.").- **Empty / error states:** `showError(...)` for load failures; 401 → login redirect with return.- **Step count:** 1 required (navigate → editor); the editor itself is open-ended.@@ -238,7 +239,7 @@### 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`).+- **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), and the route checks identity before configuration, so a signed-out caller gets a 401 rather than a reading of the server's ElevenLabs setup. 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).@@ -246,11 +247,11 @@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.+ 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. A lane that goes down mid-session drops its voices from the picker (a lane-down error re-reads the catalog), an unavailable lane's pill stays legible with a greyed billing badge so it never reads as live, and Space toggles record/stop only when focus is not on a control.- **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. There is no free platform TTS lane: each clip is billed to the caller's own ElevenLabs key (BYOK, sent as `x-eleven-key` or saved via provider keys) or metered against the prepaid credit wallet, with an R2 cache absorbing repeats; the `x-tts-billing` response header reports which lane served the call, and the playground surfaces the per-clip cost. 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.+- **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, and an unknown `voiceId` comes back as a 400 `validation_error` naming the voice (ElevenLabs' 400/404 is the caller's fault, not a 502).- **Step count:** 4 required (record → stop → name → clone) + ~3 optional (cycle script, re-record, playground speak/sample).---@@ -259,6 +260,6 @@- `/start`, `/create`, `/create-agent`, `/import/rpm`, `/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`.- `/create-review` → `create-review.html`, `/create/next` → `create-next.html`, `/create/video` → `create/video.html`, `/create/studio` → `avatar-studio.html` (the studio surface itself is documented in cluster 04).-- `/agent/new` → **301 to `/create-agent`** (or a rewrite to `create-agent.html` when the URL carries `?avatar_id=`/`?avatar_glb=`); the existing-agent editor lives at `/agent/<uuid>/edit` → `agent-edit.html`.+- `/agent/new` → **301 to `/create-agent`** (or a rewrite to `create-agent.html` when the URL carries `?avatar_id=`/`?avatar_glb=`); the existing-agent editor lives at `/agents/<uuid>/edit` → `agent-edit.html` (canonical; the legacy `/agent/<uuid>/edit` still rewrites there, while the bare `/agent/<uuid>` 301s to `/agents/<uuid>`).- `/scan` is a **route-level 301** to `/create/selfie` (`pages/scan.html` no longer exists; the 301 drops query params).- `/features/scan` is a **static landing page** with no flow logic; its CTAs link straight to `/create/selfie`.diff --git a/docs/ux-flows/02-forge-text-to-3d.md b/docs/ux-flows/02-forge-text-to-3d.mdindex 39e1ac361..7181765a3 100644--- a/docs/ux-flows/02-forge-text-to-3d.md+++ b/docs/ux-flows/02-forge-text-to-3d.md@@ -3,7 +3,7 @@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` + 19 sibling `forge-*` modules).+- `/forge` → `pages/forge.html` (loads `src/forge.js` + 25 sibling `forge-*` modules).- `/image-to-3d` → `pages/forge.html` (same app; lands with the photos tab preselected and its own document title; `?mode=image` on any forge URL does the same).- `/forge-max` → `pages/forge.html` (same app; lands with the High tier pinned and "Forge Max" header copy; `?tier=draft|standard|high` presets the selector on any forge URL).- `/forge/share/<id>` → `api/forge-share.js` (SSR page that bakes OG/Twitter/Farcaster preview meta for crawlers, then JS-redirects browsers to `/forge?share=<id>`, which opens the creation in the viewer).@@ -33,10 +33,10 @@ Routing facts (from `vercel.json`):- **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.+ 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 with a "↻ More ideas" swap. The static chip labels in `forge.html` are written at the generator's 64-character cap ("a low-poly red fox sitting upright, matte fur, soft studio light", etc.) and carry no `data-i18n`; on every JS visit `forge-prompt-studio.js` swaps them for generated prompts (`generateForgeChipSet`) whose combined width never exceeds the labels they replace, so the flex-wrapped row cannot gain a line and shift the page.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.+ 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 show a red dot, are disabled, and carry the reason in the tooltip; a legend under the picker decodes both dots and the FREE/key pills.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`.@@ -81,17 +81,17 @@ Routing facts (from `vercel.json`):- 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`.- **Photoreal reference-image path (the realism lever):** the final mesh reads as real only if the reference image the reconstructor sees is a photoreal, single-subject, plain-seamless-background, evenly-lit photograph. Two pieces drive that:- `POST /api/forge-enhance` (director): rewrites the raw prompt into one centered real-world subject with material + surface micro-detail + neutral studio-lighting cues. It classifies the subject (person / animal / vehicle / food / object) and returns a `subject`-aware `negative_prompt` targeting that class's failure modes (hands/faces for people, wheel-count/panel symmetry for vehicles, plastic-replica sheen for food). It prefers a Vertex Gemini rewrite (GCP credits) and falls through to the free-first LLM chain automatically, so it never hard-depends on Vertex. Response schema is unchanged apart from the additive `subject` field.- - `api/_lib/forge-reference-image.js` → `generateReferenceImage(directedPrompt, { aspectRatio, negativePrompt?, seed, skipNim })`: generates the reconstruction reference image on the Vertex Gemini 2.5 Flash Image lane (`imageConfig.imageSize:"2K"`), tuned as a plain-background studio photo, with the director's negatives folded in as natural-language avoidance. Automatic fallthrough to the existing provider chain (`textToImage`: NIM FLUX free → Vertex Imagen → Replicate), returning `{ imageUrl, model, lane }` (generated base64 output is persisted through the shared `image-persist` lib). The same directed prompt + aspect + negatives within 24h reuses its cached reference set instead of re-spending a Vertex generation. When `negativePrompt` is omitted it derives subject-aware negatives from the prompt itself, so a caller gets them for free. `api/forge.js` imports it on the text→3D path (dynamic import with `textToImage` as the fallback).+ - `api/_lib/forge-reference-image.js` → `generateReferenceImage(directedPrompt, { aspectRatio, negativePrompt?, seed, skipNim })`: generates the reconstruction reference image on the Vertex Gemini 2.5 Flash Image lane (`imageConfig.imageSize:"2K"`), tuned as a plain-background studio photo, with the director's negatives folded in as natural-language avoidance. Automatic fallthrough to the existing provider chain (`textToImage`: NIM FLUX free → Vertex Imagen → Replicate), returning `{ imageUrl, model, lane }` (generated base64 output is persisted through the shared `image-persist` lib). The same directed prompt + aspect + negatives within 24h reuses its cached reference set instead of re-spending a Vertex generation. When `negativePrompt` is omitted it derives subject-aware negatives from the prompt itself, so a caller gets them for free. `api/forge.js` imports it on the text→3D path (dynamic import with `textToImage` as the fallback). The whole reference step (the Vertex lane, its QA score and corrective retry, and the fallthrough ladder) runs under one shared budget, `TEXT_TO_IMAGE_BUDGET_MS` (default 60 s), so a stalled image provider can no longer hold a submit open for minutes before a job exists. Separately from the client-side Enhance button, `api/forge.js` runs its own art-director rewrite on every text prompt by default (send `director: false` to skip it; it fails soft to the raw prompt).- 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.+ - **Unconfigured** (`#state-unconfigured`): only for the `unconfigured` error (no 3D engine reachable: none of `NVIDIA_API_KEY`, `HF_TOKEN`, or `REPLICATE_API_TOKEN` set); it names the env vars to set and offers no retry.- **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.+ - `429`/limiter-unavailable, and any other `503` (`generation_unavailable`: a worker still warming or a free lane that shed the request): the recoverable countdown state carrying the server's own message and `retry_after` (20 s when absent) + 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.+ - Payment errors: `payment_invalid` / `payment_expired` re-offer Pay; `payment_already_used` clears the stale proof; a settle call that cannot be reached after the $THREE transfer already confirmed surfaces `settle_unreachable` with the transaction signature, so the payment is reconciled rather than sent twice.- 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) + ~16 optional (surprise/enhance, tier/engine/aspect choices, refine-tier, refine-local, iterate, stylize, restyle-materials, rig, optimize, game-ready, export, reel, embed, AR, share/cinema/compare/compose/segment/verdict/category).@@ -117,9 +117,9 @@ Routing facts (from `vercel.json`):### 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.+- **Source:** `pages/create-prompt.html` + `src/create-prompt.js`. The page has a real light theme (`:root[data-theme='light']`) with AA-contrast secondary copy in both themes. **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.+- **Prerequisites / gates:** **Sign-in required** ("Sign-in required" chip). A `401` on submit or poll redirects to `/login?next=/create/prompt?prompt=<typed prompt>`, so the words already typed come back with the user. 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. A `?prompt=` query param pre-fills the composer (remix/copy-prompt deep links; nothing auto-submits). 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).@@ -128,14 +128,14 @@ Routing facts (from `vercel.json`):- **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.+- **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. Each failure carries a `retryable` flag that decides which recovery buttons render: a full avatar library (`402`/`plan_limit`, also detected when a job loses the race mid-build) drops "Try again" and links to `/dashboard` (delete one) and `/pricing` (upgrade); an unconfigured engine drops it too; a `429` quotes the server's `Retry-After` and holds the retry button for exactly that long. On failure the orb, progress bar and phase line freeze and Cancel goes away; the error box (`role="alert"`) is the only live control. Cancel stays live for the whole building step, and every run holds a monotonic token so a cancelled build can never paint its late result over a newer one. 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`). The template also loads `/live-steps.js` (runnable ```` ```live ```` blocks: real API calls rendered inline) and `/tutorial-figures.js` (resolves `figure:` directives in the markdown into captured media, live 3D viewers, and a keyboard-navigable lightbox).+- **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`). The template also loads `/live-steps.js` (runnable ```` ```live ```` blocks: real API calls rendered inline) and `/tutorial-figures.js` (resolves `figure:` directives in the markdown into captured media, live 3D viewers, and a keyboard-navigable lightbox). Relative links in the markdown resolve against `docs/tutorials/<slug>.md`: sibling tutorials go to `/tutorials/<slug>`, other docs to `/docs/<name>` (with `#section` preserved), and repo-only docs (`docs/internal`, `docs/ops`, `docs/security`) or cited source files open on GitHub.- **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):**diff --git a/docs/ux-flows/03-3d-editing-viewer.md b/docs/ux-flows/03-3d-editing-viewer.mdindex 1fd1a624a..8c1975562 100644--- a/docs/ux-flows/03-3d-editing-viewer.md+++ b/docs/ux-flows/03-3d-editing-viewer.md@@ -10,10 +10,10 @@ Routing summary (from `vite.config.js`):| `/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` |+| `/app` | `pages/app-next.html` (the Next shell; `pages/app.html`, the classic shell, serves `/app-classic`, `/deploy`, `/showcase`) | `src/app.js` → `src/viewer.js`, `src/editor/index.js`, `src/validator.js`, plus `src/app-next-overlay.js` on the Next shell || `/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) |+| `/avatar-artifact` | `pages/avatar-artifact.html` | `src/avatar-artifact.js` (bundled three.js; agent avatar, allowlisted GLB, or procedural portrait) |---@@ -46,11 +46,11 @@ Routing summary (from `vite.config.js`):### 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).+- **Entry point:** `<script type="module" src="/src/scene-compose.js">` (compose.html:445). 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).+ 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?source=avatar&only3d=1&limit=24`, with eight shimmering `.gsk` placeholder tiles while it loads (`openAvatarModal`, scene-compose.js:1171-1260); 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.@@ -62,9 +62,9 @@ Routing summary (from `vite.config.js`):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.+- **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` plus `?scope=community&limit=24` (your forged creations and the community strip, rendered behind six `.gsk` skeleton tiles until they answer, scene-compose.js:1444-1472); `GET /api/explore?source=avatar&only3d=1&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".+- **Empty / error states:** Empty hierarchy → "No objects" with the hint "load an avatar or forge an item." (scene-compose.js:734). Forge errors → red banner via `showForgeError` (auto-hides 6s); timeout → "Generation timed out. Try again." Avatar browse empty → "No public avatars are available yet." with a "Create one →" link to `/create`; browse fetch failure → "Could not load avatars: …" with a Retry button 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).---@@ -87,7 +87,7 @@ Routing summary (from `vite.config.js`):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).+- **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`; a priced clip you do not own answers `paywalled` with no tracks rather than a 404, and a private one still 404s); `POST /api/animations/thumbnail` (admits a full-size poster PNG; an oversized one is a typed `413 too_large`); 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).@@ -96,34 +96,34 @@ Routing summary (from `vite.config.js`):### 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).+- **Entry point:** `public/validation/index.html` (module at line 1206) 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:33-52). The three tabs are a roving-tabindex tablist: Arrow keys, Home and End move between them (`switchTab`, validation-page.js:53-70).- **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).+ 1. Arrive at `/validation`. Three tabs: **Validate**, **Inspect**, **Records** (default `validate`, restored from `#validate|#inspect|#records`).+ 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) (`loadFile` / `loadUrl`, validation-page.js:145-176; each remembers `lastSource` so a failure card's Retry can rerun it).+ 3. `_run(bytes, name)` fires both analyses in parallel (validation-page.js:177-243): 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).+ 5. **Inspect tab** renders glTF-Transform stats + optimization suggestions (`InspectReport`).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).+ 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:283-300; validation-ui.js). The submit modal traps focus, closes on Escape or a scrim click, and returns focus to the control that opened it.+ 9. **Records tab** (independent): enter agent id + chain id (or arrive via `?agent=&chain=`), **Load** past validation records (`getLatestValidation`; Enter in either input also loads, and IPFS report URIs resolve through the shared gateway list in `src/ipfs.js`), or **Submit** a new report by dropping/picking a report JSON file (validation-ui.js; the empty Records state carries its own "Submit a Validation" button).- **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` (validationRequest + validationResponse) / `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).+- **Success state:** Status line "<name> · <size> · no issues found" (or "· N issues found", summed across errors, warnings, infos and hints; validation-page.js:226-241); 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. Every failure renders a designed `.result-error` card (title, raw detail, what to try next, and a Retry that reruns the last input via `retryLast`; `errorCard`, validation-page.js:245-282): an unreadable file → "<name> could not be read" in both panels (`_failBoth`); a fetch error → "Could not fetch <name>" with CORS hints (the host must send `Access-Control-Allow-Origin`; download and drop the file instead); a validator failure → "<name> is not valid glTF"; an inspector failure → "Could not inspect <name>". The status line flips to its failed style and **Pin & sign** is disabled again. 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).+- **Source:** `pages/app-next.html` (the Next shell served at `/app`), `pages/app.html` (the classic shell at `/app-classic`, `/deploy`, `/showcase`), `src/app.js`, `src/app-next-overlay.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-next.html:59, followed by `/src/app-next-overlay.js`, which re-skins the same app with the Next chrome; app.html:57 loads the identical module for the classic shell). `_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`, app.js:647-662); on the classic shell that CSS (`public/style.css`) overlays the `.auth-gate` card ("Your agent lives here") and hides the agent sidebar + dat.GUI editor for anonymous/pending users, while the Next shell's overlay header shows a "Sign in to save" primary CTA that routes to `/login?next=/app` (`src/app-next-overlay.js`); `getMe()` (`GET /api/auth/me`) reconciles to the real state. 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).+ 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. Framing reads the rig's facing off its canonicalized shoulder, arm or leg bones (`src/viewer/facing.js`) so the camera seats in front of the face whether the rig was authored facing +Z or -Z; a model with no readable rig keeps the legacy +Z seat.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. When an agent is loaded, its per-slot gesture overrides (`meta.edits.animations`, written by `PUT /api/agents/:id/animations` with `animationSlots`) are applied via `setAnimationMap`; the `/gestures` page documents the slot vocabulary.@@ -131,14 +131,14 @@ Routing summary (from `vite.config.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).+ 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 `/agents/<id>`, app.js:839-1010).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`.+- **Empty / error states:** No true empty void: the CZ default always loads. Anonymous main mode shows the `.auth-gate` card ("Your agent lives here", classic shell) or the "Sign in to save" CTA (Next shell) 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); a drop or pick with no model file shows the error card "No .gltf or .glb file in that drop. Pick a model file to view it." with a "Choose a file" action that reopens the picker (app.js:1840-1857); `_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).---@@ -164,36 +164,38 @@ Routing summary (from `vite.config.js`):### 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).+- **Entry point:** Inline `<script type="module">` at artifact/index.html:798. On load, `init()` reads `?agentId=`, `?theme=`, `?idle=` and `?bg=` back into the form, auto-runs `generate()` when an id is present, and `loadAgents()` fills a picker of real public agents from `GET /api/agents/public?sort=popular&limit=12&avatar=1` (`avatar=1` is load-bearing: an agent without a publicly readable GLB cannot become an artifact) (artifact/index.html:1139, 1228-1240).- **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).+ 2. Enter an **Agent ID** (a UUID; `/api/artifact` rejects anything else with `400 invalid_request`, and the page adds the hint "Agent IDs are UUIDs. Copy one from an agent profile page, or pick an agent on the left.") or click one of the public agents in the picker; optionally set theme (light), idle behavior, and a 6-hex background color (artifact/index.html:649-700).+ 3. Click **Generate** (or Enter) → `buildUrl()` assembles `/api/artifact?agent=…&theme=…&idle=…&bg=…`, mirrors the whole configuration into this page's own query string (`syncQueryString`, so a shared builder URL rebuilds the same artifact), marks the picked agent, and fetches the artifact HTML with `credentials: 'omit'` (artifact/index.html:908-1010).+ 4. On success: compute size (graded against the ceiling a 6 MiB model produces once base64-inlined on top of the ~565 KB viewer, about 8.6 MB; amber past 70%, red past 100%), fetch time, render time (the iframe's first paint, timed out at 30s), 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:1030-1075).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.+ 6. (optional) The page shows the documented Claude.ai sandbox CSP from our own origin, `GET /claude-artifact-csp.txt` (the vendored bytes `tests/api/artifact.test.js` pins the endpoint against; `node scripts/refresh-claude-csp.mjs` refreshes it), with a fallback line pointing at `specs/CLAUDE_ARTIFACT.md` if that fetch fails (artifact/index.html:1213-1226).+ 7. Copy the generated **Claude snippet** ("Here's my agent for this conversation:\n<url>") to paste into Claude.ai (artifact/index.html:1062).+- **Decision points / branches:** `?agentId=` present → auto-generate vs manual entry vs picking from the public-agent list. Fetch network error vs non-OK HTTP vs success. Size/fetch/render/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 /api/agents/public?sort=popular&limit=12&avatar=1` (the picker); `GET /claude-artifact-csp.txt` (reference only, same origin). 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).+- **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, followed by an actionable hint keyed on the error code (`not_found`, `no_avatar` → generate one at `/create`, `too_large` → re-export under 6 MB, `invalid_request`, `rate_limited` → 600 requests a minute per IP, `upstream_error`). Picker fetch failure leaves the list with its own message. CSP fetch failure → documented fallback text.+- **Step count:** ~3 required (arrive → enter or pick an 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.+### Avatar Artifact (standalone avatar viewer): `/avatar-artifact`+- **Source:** `pages/avatar-artifact.html` (markup, the designed loading/error overlays with their `data-msg-*` copy, the embed/share snippet, and the inline failure + watchdog script) → `src/avatar-artifact.js` (scene, artifact resolution, GLB loading, retargeted idle). three.js ships with the bundle; there is no third-party CDN script, because the page is meant to be pasted into other sites as a bare iframe. NOTE: this is the "standalone Three.js viewer for avatar artifacts, embeddable and shareable without any wrapper page" (page OG meta). Three modes share one composed stage (lighting, ground, fog, drifting motes): `?agent=<uuid>` renders that agent's avatar, `?model=<url>` renders any GLB on an allowlisted host, and no params renders the house portrait, a procedural figure (cylinders/spheres/boxes) that tracks the visitor.+- **Entry point:** `<script type="module" src="/src/avatar-artifact.js">` (avatar-artifact.html:511), preceded by the inline script that defines `window.__avatarArtifactFailed` and arms a 12s watchdog (avatar-artifact.html:415-457). The module resolves the artifact from the query string (`resolveArtifact`), imports `three` (plus `GLTFLoader` and the meshopt decoder only on the model lane), and calls `boot(artifact)`.+- **Prerequisites / gates:** None. No auth, wallet, or $THREE gate. The agent lane reads the public `GET /api/agents/:id`; a `?model=` URL must be `https://` on three.ws, `*.r2.dev`, `*.r2.cloudflarestorage.com`, `*.amazonaws.com`, `*.cloudfront.net`, `storage.googleapis.com`, `*.blob.core.windows.net`, or `*.vercel.app` (the same allowlist `/api/artifact` enforces, `ALLOWED_MODEL_HOSTS`, avatar-artifact.js:28-40). Renders 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).+ 1. Arrive at `/avatar-artifact` (optionally with `?agent=` or `?model=`). Loading overlay shows while the bundled runtime loads; the artifact lane holds it until the GLB has actually arrived, with a lane-specific loading note.+ 2. Resolve the artifact: both params → `msgBoth` failure; a non-UUID or unknown `?agent=` → `msgNotFound` with an action link to `/agents`; an agent whose lookup failed → `msgAgentFetch`; an agent with no avatar → `msgNoAvatar`, or `msgAvatarPrivate` when it has one it will not show, each linking the agent's profile; a `?model=` off the allowlist → `msgModelBlocked` (avatar-artifact.js:60-165).+ 3. Runtime + WebGL guard: if the runtime import fails, WebGL context creation throws, or the module never runs at all (the watchdog fires after 12s of silence; a heartbeat re-arms it while a large model is still downloading), the designed error state is shown (`window.__avatarArtifactFailed`, with a Retry that reloads). A GLB that fails to parse → `msgModelFailed`.+ 4. On success the avatar (or the house portrait) renders and the loading overlay fades on the first painted frame, which also clears the watchdog and any error that raced it (avatar-artifact.js:378-392). A loaded humanoid rig plays the shared retargeted `idle` clip from `/animations/manifest.json` through `AnimationManager` (`breatheLife`); a rig the canonicalizer cannot drive simply stands still.+ 5. Interact: the figure's gaze follows the mouse (`mousemove`), touch drag (`touchmove`), or keyboard (arrow keys / WASD nudge the gaze by `KEY_STEP` 0.25; the canvas is focusable, `role="img"`, ARIA-labeled). A turntable orbits the look target unless `prefers-reduced-motion` is set.+ 6. (optional) **Copy embed**: the page carries its own `<iframe>` snippet pointing at this URL; once a specific artifact resolves, the module hands its query back (`__avatarArtifactSetEmbed`) so the copied iframe shows the avatar on screen rather than the house portrait. Clipboard denied (cross-origin frame, insecure context) → the snippet field is revealed and selected for manual copying (avatar-artifact.html:459-507).+ 7. The canvas keeps animating (idle motion, blink, drifting motes) and stays responsive to resize/orientation change.+- **Decision points / branches:** Agent lane vs model lane vs house portrait. Runtime available + WebGL OK (render) vs runtime/WebGL/watchdog failure (error state). Coarse pointer (phones/tablets) → lighter render (no antialias, lower DPR, no shadow pass). Pointer/touch input vs keyboard gaze control. Clipboard write vs manual snippet.+- **External calls / dependencies:** `GET /api/agents/:id` (agent lane), the avatar GLB itself (model lane; meshopt decoded), `GET /animations/manifest.json` + the retargeted idle clip; `/api/page-og` for OG/Twitter share images (meta only). No platform API on the house-portrait lane, no glTF validator, no export.+- **Success state:** Animated avatar (or procedural portrait) that tracks cursor/touch/keys; loading overlay faded out; embed snippet copied.+- **Empty / error states:** Loading overlay (`#loading`) during runtime and model load; designed error overlay (`#error`) with per-failure copy (`data-msg-both`, `-not-found`, `-agent-fetch`, `-no-avatar`, `-avatar-private`, `-model-blocked`, `-model-failed`, `-no-webgl`), one contextual action link, and a Retry. No empty "no model" state: without params the house portrait is always present once the runtime loads.+- **Step count:** ~3 required (arrive → resolve + runtime/WebGL OK → avatar renders) + ~2 optional (interact via cursor/touch/keyboard, copy the embed snippet).diff --git a/docs/ux-flows/04-embed-widget-studio.md b/docs/ux-flows/04-embed-widget-studio.mdindex 3735ca1b5..b1026bb92 100644--- a/docs/ux-flows/04-embed-widget-studio.md+++ b/docs/ux-flows/04-embed-widget-studio.md@@ -13,7 +13,7 @@ Routing recap (from `vercel.json`):| `/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 |+| `/agents/<id>/embed` (the legacy `/agent/<id>/embed` still serves the same page), `/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.@@ -41,7 +41,7 @@ Routing recap (from `vercel.json`):- `?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.+- **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). The page importmap pins `@solana/web3.js` + `@solana/spl-token` to esm.sh; `launch-panel.js` loads its own web3.js and `qrcode` copies through `/load-module.js` (esm.sh, then jsdelivr, then unpkg, each under a deadline) and, if all three miss, reports "<what> could not be loaded (<hosts> unreachable or blocked). Check your connection or ad blocker and try again."- **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 "Make one from a selfie →" / "browse every way to build one →". Avatar load failure → inline error card with **Retry**. Public search failure → status line shows reason. Save failure → `#form-error` text. Preview without a model → a note that the 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 10 are `ready`).- **Step count:** 10 required (+5 optional)@@ -66,7 +66,7 @@ Routing recap (from `vercel.json`):- 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 15 in static HTML, overwritten by real count.+- **Empty / error states:** Showcase fetch failure → `role=alert` card "The widget showcase could not load. Check your connection and try again." with the detail, a **Try again** button that re-runs the load (replacing the filter bar instead of stacking a second one) and a "Read the widget docs" link (`/docs/widgets`). A manifest with zero widgets → "No showcase widgets yet" empty state with **Open the Studio**. Per-card iframe failure leaves the placeholder/play button. Hero count defaults to 15 in static HTML, overwritten by the real count (and re-written whenever the i18n runtime repaints the badge).- **Step count:** 6 required (+3 optional)---@@ -89,48 +89,46 @@ Routing recap (from `vercel.json`):### 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.+- **Prerequisites / gates:** None to use the builder. To produce a working artifact you need a valid **agent UUID** (a hand-typed handle is refused with `400 invalid_request`: "agent must be the agent UUID, copied from the agent profile page") or a 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).+ 1. Visitor lands; the page shows the vendored Claude sandbox CSP (`/claude-artifact-csp.txt`, the same bytes `tests/api/artifact.test.js` pins the endpoint against) in a `<details>`, and a **"Public agents you can embed"** picker loads `GET /api/agents/public?sort=popular&limit=12&avatar=1` (four skeleton tiles → a grid of avatar tiles; "Browse all" → `/agents`).+ 2. **Configure**: click a picker tile (fills the ID and generates in one tap) or paste an agent UUID; `(optional)` set Theme (dark/light), Idle clip name, Background hex (six hex digits, validated live with an inline hint).+ 3. Click **Generate** (or Enter) → `buildUrl()` assembles `/api/artifact?agent=…&theme=…&idle=…&bg=…`; overlay shows "Fetching artifact…"; the query string is synced to `?agentId=` plus any non-default theme/idle/bg so the address bar carries the whole configuration.+ 4. System fetches the artifact HTML, measures size, fetch time and render time, checks the response CSP for `frame-ancestors *`, and renders it into a **sandboxed iframe** (`sandbox="allow-scripts"`, `srcdoc`). Stats panel fills in: Artifact (size, graded against the ~8.6 MB ceiling a 6 MB model produces once base64-inlined on top of the 565 KB viewer), Fetch, Render, 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).+ - Size thresholds: the stat grades the inlined HTML against the ceiling a legal 6 MB model produces (`ceil(6 MiB / 3) * 4 + 565 KB`): over 70% of it = warn, over 100% = bad; the server caps the model itself at 6 MB → 413. Fetch: >2s warn, >5s bad. Render: >3s warn, >8s bad, 30s timeout.- 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.+- **External calls / dependencies:** `GET /api/artifact` (the bundle; answers open CORS for GET/HEAD/OPTIONS so an embedder may fetch it as well as iframe it), `GET /api/agents/public` (the picker), `/claude-artifact-csp.txt` (same-origin vendored copy of Claude's sandbox CSP). 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).+- **Empty / error states:** No agent ID → overlay "Enter an agent ID first." with the hint to pick a public agent on the left or paste an ID from a profile, and focus returns to the field. Network error / non-OK → error overlay with the server's `error_description`, a per-code next step (`not_found` pick a public agent or paste an ID; `no_avatar` generate one at `/create`; `invalid_request` "Agent IDs are UUIDs…"; `upstream_error` retry or use a different avatar) and a **Retry** button. Picker feed failure → note in the picker with a retry. CSP file unreachable → "Could not load /claude-artifact-csp.txt. The locked-in copy is in 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`. (`src/agent-detail.js` and `src/forge.js` use the lighter `showSharePanel` from `src/shared/share.js`, a different share sheet.) 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.+### Agent embed snippet (studio page / `<agent-3d>`): share/embed panel flow+- **Source:** the canonical studio page `/agents/<id>` (`src/avatar-page.js`, `renderEmbedPanel`) and the long-form profile `/agents/<id>/profile` (`src/agent-detail.js` + `renderEmbed` in `src/agent-detail-market.js`, the `#ad-embed-card`). Both build their snippets inline; the **Share** button on those pages opens the lighter `showSharePanel` sheet from `src/shared/share.js` (Copy link, Share on X, Share on Farcaster, Remix, OG preview image). `src/share-panel.js` (`SharePanel` class) + `src/share-panel-builders.js` (`buildEmbedUrl`, `buildIframeSnippet`, `buildWebComponentSnippet`) remain in the tree as a tested library (`tests/share-panel.test.js`), but nothing mounts them since the `agent-home-orphans` helper was deleted on 2026-08-06. Embed targets: `/agents/<id>/embed` (CSP `frame-ancestors *`; the legacy `/agent/<id>/embed` serves the same page), web component `/dist-lib/agent-3d.js`.+- **Entry point:** the **Embed** view in the studio page's action bar (`?view=embed`, alongside 3D · Chat · AR · Profile) reveals the embed panel; on the profile, `?view=embed` scrolls to and flashes the embed card (`focusEmbedSection`).+- **Prerequisites / gates:** Must be on an **existing agent** with a public GLB. No sign-in required to copy snippets; embedding is free (no wallet or on-chain deployment required). No $THREE gate. An owner who switched embedding off in the embed policy (`/api/agents/<id>/embed-policy`) hides the profile card (`data-embed-disabled`).+- **Steps (4):**+ 1. Open the agent's studio page → switch to the **Embed** view (or open the profile and scroll to "Embed").+ 2. Read the intro ("Drop this <agent|avatar> on any website. Use the wizard for a live preview and platform instructions.") and, `(optional)`, click **Configure in wizard ↗** → `/embed?…` (the walk-through embed wizard) in a new tab.+ 3. Choose a snippet and **Copy** (button flips to "Copied ✓", reverting after ~1.8s): **Web component** (`<script type="module" src="https://three.ws/dist-lib/agent-3d.js">` + `<agent-3d src="<glb>" agent-id="…">`), **iframe** (studio page: `<iframe src="/agents/<id>?embed=1">`, the page hides its chrome in embed mode; profile card: `<iframe src="/agents/<id>/embed" width="480" height="640">`), the **page link**, or (studio page) the **Terminal** snippet that runs the avatar in any terminal with no browser or GPU (see `/docs/tty-avatar`).+ 4. Paste the iframe or `<agent-3d>` snippet on any third-party site → the agent renders inline (`/agents/<id>/embed` runs `src/avatar-embed.js` / the 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)+ - iframe vs. web-component snippet (the web component observes `agent-id`, `background`, `name-plate` attrs).+ - Studio page (`?embed=1`, full studio inside the frame) vs. profile card (`/agents/<id>/embed`, the chat-style embed).+ - Separate, simpler embed entry points exist: the legacy **Agent Home** page (`public/agent/index.html`, only reachable at its literal `/agent/index.html` path now that `/agent/<id>` 301s to `/agents/<id>`) mounts `src/agent-hub-actions.js`, whose "Embed" button opens `AgentEmbedModal` (`src/agent-embed-modal.js`); **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:** `/agents/<id>/embed` and `/agents/<id>?embed=1` (final), `/dist-lib/agent-3d.js` (web component), the agent's GLB URL, `/embed` (wizard), `/api/agents/<id>/embed-policy` (profile card gate).+- **Success state:** Snippet copied ("Copied ✓"); the pasted snippet renders the agent inline on the host page.+- **Empty / error states:** Agent without a 3D avatar → the profile card's web-component snippet reads `<!-- No 3D avatar attached yet -->`; embedding switched off by the owner → profile card hidden; a clipboard write that throws leaves the button reading "Copy" (the snippet stays selectable in its `<pre>`).+- **Step count:** 4 required (+1 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."+- **Steps (4):** (1) Click "Embed" on the agent hub → modal opens (default 420×520). (2) `(optional)` adjust Width/Height. (3) Switch tab: **iframe** (`/agents/<id>/embed`), **`<agent-3d>`** (`/dist-lib/agent-3d.js` web component), **SDK** (`/embed-sdk.js` + `Agent3D.connect()` bridge example), or **walking avatar** (a live `/walk-embed` preview iframe that reloads as the options change). (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`)@@ -147,15 +145,15 @@ Routing recap (from `vercel.json`):- **Steps (7):**1. Page boots → loads `BASE_GLB_URL` (`/avatars/default.glb`) into a `TalkScene` viewport with idle breathing/blinking; accessory presets load. In create mode a **Base switcher** offers Stylized (the default stylized humanoid body) or Parametric (`/avatars/parametric-base.glb`, a CC0 MakeHuman-derived base with ~120 identity morph sliders); Color/Layers panels adapt to the loaded base (dead slots hide).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).+ 3. **Customize**: switch tabs: Color (skin/hair/outfit swatches + hex), Hats, Glasses, Earrings (accessory presets from the catalog, each tab with its own loading / error / populated state), Sculpt (morphs), Animate. On narrow viewports the tab bar collapses to icons. Each change applies live to the scene graph; an accessory is recorded in the appearance only once it is actually on the rig, and the tap that adds one shows busy feedback while the GLB fetches. `(optional)` undo/redo (history up to 50; each step is stamped so a press superseded while its accessories were still loading is dropped rather than applied late).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`.+- **External calls / dependencies:** `/avatars/default.glb`, accessory preset assets, `/api/avatars` (save/PATCH), avatar-snapshot upload, GLTFExporter. Hands off to `/studio`, the agent studio page's Embed view (`/agents/<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`.+- **Empty / error states:** Boot failure → "Avatar Studio couldn't load. Check your connection and try again." (a model that fails to load gets the same stage error with a retry). The accessory catalog is a separate fetch from the model: while it loads the three accessory tabs show "Loading hats…" etc.; if it fails they show a retryable error ("We couldn't load the hats catalog … Colors, sculpt and animation still work, and you can save your avatar without accessories") while Color, Sculpt, Animate and Save keep working. A single accessory that fails to load → status "Couldn't load <name>: … Tap it again to retry", and it is not written into the appearance. Queued ops hand their outcome back to the caller (`runQueued` → `{ ok, error }`) instead of swallowing it; 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)---diff --git a/docs/ux-flows/05-discovery-social.md b/docs/ux-flows/05-discovery-social.mdindex ecac9814e..d2461d07a 100644--- a/docs/ux-flows/05-discovery-social.md+++ b/docs/ux-flows/05-discovery-social.md@@ -23,7 +23,7 @@ Routing recap (from `vercel.json`):---### 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/...`)+- **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/...`; a `kind=solana` asset that is not one of ours falls back to the crawled `solana_agents_index`, so external Solana agents get a real link preview, and a malformed id returns the bare shell instead of a 500)- **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):**@@ -34,7 +34,7 @@ Routing recap (from `vercel.json`):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.+ 8. **Payoff:** User clicks a card → its canonical detail page from the API's `detailUrl`: ERC-8004 agents `/a/<chain>/<id>`, three.ws agents `/agents/<id>`, external Solana agents `/discover/a/sol/<asset>` (served by `/api/discover-detail`), avatars `/avatars/<id>`; 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`.@@ -55,7 +55,7 @@ Routing recap (from `vercel.json`):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); or click the hero's "✨ Surprise me" button (`data-surprise-avatar`) → `POST /api/avatars/surprise` composes a unique rigged GLB, revealed live in a tinted-stage modal with Reroll, a shareable `/gallery?surprise=<seed>` link, and "Make it mine" (stages the GLB into the guest flow → `/create-review`). No sign-in needed to see it.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.+ 8. **Payoff:** Click a card thumbnail → `/avatars/<id>` (the avatar's own page, not the bare GLB 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; a forge row has no title, so the card shows the first clause of its spec prompt and keeps the full text in the tooltip) 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.@@ -66,18 +66,18 @@ Routing recap (from `vercel.json`):### Animation Gallery — `/animations`- **Source:** `pages/animations.html`, `src/animations-gallery.js`, `src/animation-categories.js` (derived categories), `src/animations-live-preview.js` (shared WebGL preview engine), `/api/animations/clips`, `/animations/manifest.json`, `/api/animations/library`, `/pose` (studio)-- **Entry point:** Module runs `loadAll()` on import. Query (`?q=`, `?cat=`, `?filter=loop|once`, `?sort=`) round-trips through the URL; `?clip=<id>` deep-links straight into the detail modal.+- **Entry point:** Module runs `loadAll()` on import. Query (`?q=`, `?cat=`, `?filter=loop|once`, `?sort=`) round-trips through the URL, and an unknown `cat`, `filter` or `sort` value falls back to the default rather than blanking the control or filtering everything away; `?clip=<id>` deep-links straight into the detail modal.- **Prerequisites / gates:** None. Community 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 and merges three sources into one grid: community clips (`GET /api/animations/clips?include_public=true&visibility=public`, capped at 300, newest first), the built-in three.ws motion library (`/animations/manifest.json`, the same curated clips `/pose` ships with), and the full Mixamo-sourced catalog (`GET /api/animations/library`, fetched from the R2 CDN in bounded 1000-clip pages).+ 1. User lands on `/animations`. System shows loading state and merges three sources into one grid: community clips (`GET /api/animations/clips?include_public=true&visibility=public`, capped at 300, newest first), the built-in three.ws motion library (`/animations/manifest.json`, the same curated clips `/pose` ships with), and the full Mixamo-sourced catalog (`GET /api/animations/library`, fetched from the R2 CDN in bounded 1000-clip pages; only clips whose manifest entry carries a `thumb` get a thumbnail request, the rest show the icon placeholder without a doomed fetch).2. System normalizes every clip to one card shape (poster thumbnail, derived category, duration, loop/once badge) and paginates client-side (36 per page, infinite scroll, lazy thumbnails).3. (optional) User searches (`/` hotkey focuses the box), picks a category chip, a loop/once filter, or a sort → grid re-filters client-side; the URL stays shareable.4. (optional) User hovers a card's preview zone → the ONE shared WebGL engine moves its singleton canvas into that card and plays the retargeted clip on the preview avatar (no iframes, no per-card GL contexts; skipped for touch and reduced-motion users, who get the preview inside the detail modal instead).- 5. **Payoff:** Click a card → detail modal (arrow keys step between clips, Space toggles play, Copy link copies `/animations?clip=<id>`, Copy embed copies an `/embed/avatar?anim=<id>` iframe snippet) → "Open in Studio" navigates to `/pose?anim=<id>` to apply/remix the clip on an avatar.+ 5. **Payoff:** Click a card → detail modal (arrow keys step between clips, Space toggles play, Copy link copies `/animations?clip=<id>`, Copy embed copies an `/embed/avatar?anim=<id>` iframe snippet) → "Open in Studio" navigates to `/pose?anim=<id>` to apply/remix the clip on an avatar. The transport stays hidden until the clip is on the stage, Tab is trapped inside the dialog, the sliders keep their own arrow and Space keys, and closing returns focus to the card that opened it.- **Decision points / branches:** community vs library vs full-catalog card (community listed first); thumbnail present vs placeholder; touch/reduced-motion (modal-only preview) vs hover preview; search/filter active → empty-search state.- **External calls / dependencies:** `GET /api/animations/clips`, `GET /animations/manifest.json`, `GET /api/animations/library` (R2 CDN pages), shared live-preview engine, `/pose` nav.- **Success state:** One searchable grid across all three clip sources, each card live-previewable in place; "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.+- **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 only when nothing loaded and at least one source failed, since a partial failure still renders whatever answered.- **Step count:** 2 required (+3 optional)---@@ -89,29 +89,29 @@ Routing recap (from `vercel.json`):- **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.+ 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 (opaque: `sort=new` echoes `created_at`, `sort=chats` echoes `<chat_count>:<created_at>` so Top pages through every character instead of ending after one page; a hand-edited cursor is a 400).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.+- **Decision points / branches:** has token block vs not; has Solana address → wallet chip; image URL valid http(s) vs placeholder; reset vs append render (a reset supersedes an in-flight request through a generation token, so a slow first page cannot paint over a newer sort or search).- **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."+- **Success state:** Grid of character cards each linking to its detail page; the header carries a "Create a character" link to `/create-agent`.+- **Empty / error states:** Search-empty → "No characters match “<q>”." with Clear search; feed-empty → "No characters published yet." with a Create a character link (`/create-agent`); fetch error → "Could not load characters." with Try again; a failed Load more keeps the cards already on screen and relabels the button "Retry loading more".- **Step count:** 1 required (+3 optional)---### Community — `/community`-- **Source:** `pages/community.html` (content + inline live-activity module + footer newsletter)+- **Source:** `pages/community.html` (content, an Official channels ledger, inline live-activity module, an inline newsletter form plus the footer one; the palette is token-derived, so the page follows the site theme switcher)- **Entry point:** Page load; the inline module fetches the live activity feed.- **Prerequisites / gates:** None.- **Steps (4):**1. User lands on `/community` and reads the hero ("Build with us.").- 2. System: the "Live activity" section fetches `GET /api/users/me/feed?scope=all&limit=10` (3 skeleton rows while loading) and renders the latest platform activity rows (avatar, actor + verb, title, relative time, thumbnail); "Open the full feed →" links to `/feed`.- 3. (optional) User clicks a channel card: Follow on X (`@trythreews`), GitHub (`nirholas/three.ws`), Docs (`/docs`), Tutorials (`/tutorials`).- 4. (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.+ 2. System: the "Live activity" section fetches `GET /api/users/me/feed?scope=all&limit=10` (3 skeleton rows while loading) and renders the latest platform activity rows (avatar, actor + verb, title · relative time, thumbnail; the item is a stretched overlay link and the actor's name is a separate `/u/<username>` link, so one row carries two destinations without nesting anchors); "Open the full feed →" links to `/feed`.+ 3. (optional) User clicks a channel card: Follow on X (`@trythreews`), GitHub (`nirholas/three.ws`), Docs (`/docs`), Tutorials (`/tutorials`), IBM user group, Rankings (`/rankings`). Below the cards, **Official channels** lists every account and address the platform operates (X, Telegram `t.me/three_ws` plus the community chat, GitHub, the web domain, `[email protected]`, and the `$THREE` contract with a Copy button that falls back to selecting the text when the clipboard is unavailable) and a "Two things we never do" impostor notice.+ 4. (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 inline newsletter form (email + Subscribe, with a status line beneath it) or the footer one.- **Decision points / branches:** activity populated vs empty vs error; which outbound channel the user follows; newsletter subscribe vs not.-- **External calls / dependencies:** `GET /api/users/me/feed?scope=all` (live activity), external links (x.com, github.com), mailto, footer newsletter script.-- **Success state:** Live activity rows render; user reaches a community channel / submits the newsletter form / opens `/feed`.-- **Empty / error states:** Activity empty → "Nothing has happened yet" with a `/create` CTA; fetch failure → "Could not load live activity right now." Newsletter form handles its own submit feedback.+- **External calls / dependencies:** `GET /api/users/me/feed?scope=all` (live activity), external links (x.com, github.com, t.me, IBM Community), mailto, clipboard API, footer newsletter script.+- **Success state:** Live activity rows render; user reaches a community channel / submits the newsletter form / opens `/feed` / copies the `$THREE` contract.+- **Empty / error states:** Activity empty → "No activity yet. Be the first to create something." with a `/create` link; fetch failure → "Could not load live activity right now." with a Try again button that reloads the feed. Newsletter form handles its own submit feedback.- **Step count:** 2 required (+2 optional); content page with a live feed section---@@ -125,7 +125,7 @@ Routing recap (from `vercel.json`):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.+ 5. (optional) Jump (Space / button), cycle camera mode C (follow/cinematic/firstperson/topdown), cycle environment V (rebuilds physics colliders), emote G + 1 to 9 (broadcast), minimap M, chat T/Enter (broadcast bubble), friends F, players-panel; inspecting a remote player offers a DM that opens that thread in the in-world friends panel rather than sending the player to another surface.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.@@ -152,7 +152,7 @@ Routing recap (from `vercel.json`):- **Decision points / branches:** WebGL supported vs fatal overlay; placement path (gyro-GPS / WebXR floor / iOS Quick Look / QR marker / 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.+- **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; a caption naming a cashtag or pump.fun-style mint other than `$THREE` is refused whatever the ticker's length. Pin ids are strict UUIDs on every pin route (`/api/irl/pins`, `/api/irl/interactions`, privacy, report), so a malformed id answers 400 rather than surfacing a Postgres cast error as a 500, and reports read the device credential from the `x-irl-device` header (body fallback) so an owner cannot self-report their own pin as an independent reporter.- **Step count:** 7 required (+ several optional)---@@ -174,7 +174,7 @@ Routing recap (from `vercel.json`):### 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.+- **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. A banner above the app cross-links the Reputation Staking Market (`/reputation/market`).- **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).@@ -200,7 +200,7 @@ Routing recap (from `vercel.json`):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".+- **Decision points / branches:** has `modelUrl` → 3D viewer; `state === 'private'` → 🔒 placeholder; `imageUrl` → thumbnail (served only for a public avatar; a private one yields identity metadata and no imagery); 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.@@ -210,17 +210,17 @@ Routing recap (from `vercel.json`):### Agents Index — `/agents`- **Source:** `public/agents/index.html` (inline module), `/api/explore` (`source=agents` meta-source), `public/agents/boot.js`-- **Entry point:** Inline module runs `load(true)` on load.+- **Entry point:** Inline module runs `load(true)` on load; `?source=`, `?q=` and `?sort=` are read first and kept in sync with `replaceState`, so a filtered directory is a shareable, reload-safe link.- **Prerequisites / gates:** None to browse.- **Steps (4):**1. User lands on `/agents` ("Agent Index"). System renders 8 skeleton cards and fetches `GET /api/explore?source=agents&limit=24`, one unified feed across every registry the platform crawls: ERC-8004 (EVM, erc8004-crawl cron), the Metaplex Agent Registry + AgenC protocol (Solana, solana-agents-crawl cron), and three.ws's own agents. The meta-source returns on-chain agents only, never avatars.2. System renders agent cards: thumbnail proxied through `/api/img` (lettered-initial fallback), a source badge (chain short-name for EVM / Metaplex / AgenC / three.ws), name + description, up to 3 service/skill chips, and an `x402` chip when the agent accepts x402 payments. Count label shows loaded total.- 3. (optional) Source chips All sources / Solana / EVM → reload; search box → 320ms debounce → reload with `q`; sort select (Newest first / Name A-Z, client-side re-sort); "Load more" → cursor pagination (`cursor`).- 4. **Payoff:** Click a card → its natural detail surface: EVM agents → `/a/<chain>/<id>`, three.ws Solana agents → `/agent/<id>`, external Solana agents → their 3D viewer or on-chain explorer (new tab). Hero CTAs link to `/create-agent` and `/marketplace`.+ 3. (optional) Source chips All sources / Solana / EVM (a pressed-button group) → reload; search box → 320ms debounce → reload with `q` (an unchanged term does not refetch); sort select (Newest first / Name A-Z, client-side re-sort); "Load more" → cursor pagination (`cursor`), the button showing a spinner via `aria-busy` while it fetches and appending the new page instead of rebuilding the grid. A newer request always supersedes the one in flight.+ 4. **Payoff:** Click a card → its canonical detail page: EVM agents → `/a/<chain>/<id>`, three.ws Solana agents → `/agents/<id>`, external Solana agents → the API's `detailUrl` (`/discover/a/sol/<asset>`), else their 3D viewer or on-chain explorer (new tab); a registry row with nowhere real to go renders without a link rather than with a dead one. Hero CTAs link to `/create-agent` and `/marketplace`.- **Decision points / branches:** source chip (all / solana / onchain); card kind → internal vs external (target="_blank") destination; thumbnail vs initial fallback; nextCursor present (Load more shown) vs not.- **External calls / dependencies:** `GET /api/explore?source=agents`, `/api/img` (thumbnail proxy).- **Success state:** Grid of on-chain agents across all crawled registries, each linking to its detail surface.-- **Empty / error states:** Query-empty → "No agents found" for the term; unfiltered-empty → "No agents in this source yet" + create-first CTA (registries are crawled continuously); fetch error → "Couldn't load agents" with "Try refreshing the page."+- **Empty / error states:** Query-empty → "No agents match "<q>"" with Clear search and Create an agent; unfiltered-empty → "No agents in this source yet" with Check again and Create the first one (registries are crawled continuously); fetch error → "Couldn't load agents" naming the failure, with Try again and Browse the marketplace; a failed Load more → "Couldn't load more agents" keeping every page already on screen, with Resume loading (off the surviving cursor) or Start over. The panel is a live region, so the outcome is announced.- **Step count:** 1 required (+3 optional)---@@ -233,7 +233,7 @@ Routing recap (from `vercel.json`):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.+ 4. **Payoff:** Per-row actions: "View" (`home_url` or `/agents/:id`), "Edit" (`/agents/: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.@@ -262,4 +262,4 @@ Routing recap (from `vercel.json`):- 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.+- Detail pages reached from these routes (`/discover/a/...`, `/a/:chain/:id`, `/character/:id`, `/avatars/:id`, `/agents/:id`, agent profile `home_url`) are outside this cluster's scope but are the payoff destinations. `/agents/:id` is the canonical agent route; the singular `/agent/:id` now 301s to it.diff --git a/docs/ux-flows/06-marketplace-skills.md b/docs/ux-flows/06-marketplace-skills.mdindex 9565a5116..31f96c013 100644--- a/docs/ux-flows/06-marketplace-skills.md+++ b/docs/ux-flows/06-marketplace-skills.md@@ -80,7 +80,7 @@ Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; g12. 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. A separate agent rail exists: `POST /api/marketplace/purchase-as-agent` `{ buyer_agent_id, seller_agent_id, skill }` buys the skill FOR an owned agent from its custodial wallet (owner-authenticated, CSRF-gated, 10 autonomous purchases/hour/agent, same daily spend cap as asset purchases).-- **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).+- **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` (rotates lanes; when every lane dies at the wire it re-sweeps once and answers an idempotent read from its last-good body, flagged with an `x-solana-rpc-stale` header, instead of a 502), `@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)@@ -120,7 +120,7 @@ Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; g4. 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`. Trial visibility: `GET /api/marketplace/trial-status?role=buyer|seller` reports each of the caller's trials (runs left, price to keep, state: fresh/active/running-low/exhausted) or, for sellers, per-skill trial counts (counts only, never buyer identities).-- **Where the two sides are read:** `/conversions` (`pages/conversions.html`, `src/conversions.js`) renders that endpoint as a two-tab page: "Trials I hold" and "Trials on my skills". The buyer list is capped server-side at 200 rows and the payload carries `total` + `truncated` so the page can say what it is leaving out rather than implying the cap is the whole count. Row CTAs deep-link at one skill: a buyer's row opens `/agents/:id?skill=<name>#pricing`, which scrolls the agent page's pricing card to that skill and marks the row (`focusRequestedSkill()` in `src/agent-detail-market.js`); a seller's "Edit pricing" opens `/agent/:id/edit?tab=monetization`, the panel that actually sets the price and the trial grant.+- **Where the two sides are read:** `/conversions` (`pages/conversions.html`, `src/conversions.js`) renders that endpoint as a two-tab page: "Trials I hold" and "Trials on my skills". The buyer list is capped server-side at 200 rows and the payload carries `total` + `truncated` so the page can say what it is leaving out rather than implying the cap is the whole count. Row CTAs deep-link at one skill: a buyer's row opens `/agents/:id?skill=<name>#pricing`, which scrolls the agent page's pricing card to that skill and marks the row (`focusRequestedSkill()` in `src/agent-detail-market.js`); a seller's "Edit pricing" opens `/agents/:id/edit?tab=monetization`, the panel that actually sets the price and the trial grant.- **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)diff --git a/docs/ux-flows/07-crypto-trading-analytics.md b/docs/ux-flows/07-crypto-trading-analytics.mdindex b7ac57081..7f72b08ac 100644--- a/docs/ux-flows/07-crypto-trading-analytics.md+++ b/docs/ux-flows/07-crypto-trading-analytics.md@@ -12,23 +12,23 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up---### Oracle — `/oracle`-- **Source:** `pages/oracle.html`, `src/oracle.js` (~2400 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; SEO/share links from `coinShareUrl()`. `/oracle/coin/<mint>` is now a standalone full conviction coin page (server-rendered by `api/oracle-share.js` in the markets-hub style: score dial, pillar bars, chart, launch intelligence), reached from the drawer's "Full page ↗" action.+- **Source:** `pages/oracle.html`, `src/oracle.js` (~2500 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; SEO/share links from `coinShareUrl()`. `/oracle/coin/<mint>` is now a standalone full conviction coin page (server-rendered by `api/oracle-share.js` in the markets-hub style: score dial, pillar bars, chart, launch intelligence), reached from the drawer's "Full page ↗" action. The server-rendered hero also carries the score's measured odds (what share of calls in that band won, against the random-launch base rate, read from `conviction-calibration.json` via `hitRateFor`) and a "Since the call" strip (peak multiple, graduated / rugged / still live, market cap now) joined from `pump_coin_outcomes`, so the first paint and the share preview never show an unqualified 100/prime on a coin the market has already resolved; the share description gets a "since:" clause for the same reason. Coin identity falls back to DexScreener when pump.fun does not answer, coin art is proxied through `/api/img`, and the route is GET-only.- **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.+ 2. System: `GET /api/oracle/feed?...` renders conviction cards (0 to 100 score, tier pill prime/strong/lean/watch/avoid). Each card's "Oracle's take" quotes the coin's own evidence (up to two reason clauses served with the feed, each with its lift over the base rate; the pillar template survives only for rows cached before reasons shipped), an odds chip states what that score band has actually returned ("N% held 2x+", shown once the band has 100+ resolved coins), and an outcome chip (graduated ✓ / rugged ✕ / peak Nx) lands once the market resolves the coin. 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 / sort seg / ★-watchlist-only toggle / breadth-bar tier segments → `syncFilterUrl()` + `loadFeed()` (URL is shareable). A hero "Join the live Telegram feed" button appears when `/api/oracle/stats` reports a configured public signals channel.- 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).+ 5. (optional) Switch view tab: `movers`, `wallets` (reputation leaderboard), `edge` (tier backtest win-rate; the hero names the specific bands that invert the ladder instead of claiming calibration, states the fitted event's own hit rate (a 3x run or graduation) beside the stricter clean-win rate, and each calibration row shows "claims N%" next to the realized bar, with "n/a" for an unmeasured band), `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: Full page ↗ (`/oracle/coin/<mint>`), pump.fun ↗, GMGN ↗ (via `src/shared/trading-terminals.js`, referral-tagged), solscan ↗, Details ↗ (`/launches/<mint>`), View in 3D ↗ (`/coin3d?mint=`), ☆/★ Watch (writes `ld_watchlist`), Copy mint, Copy link, Share to X; the live Market panel adds GMGN/DexScreener/GeckoTerminal/Birdeye links when available.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."+ 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." Arming live is judged on the raw request, not the clamped values: a `per_trade_sol` below 0.001 SOL or a `max_daily_sol` below `per_trade_sol` answers 400 before any real-money loop starts (simulate keeps the forgiving clamps), and the GET side rejects a non-uuid `agent_id` with 400.- **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/stats` (hero statline + Telegram channel link), `/api/oracle/activity`, `/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.+- **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; during a database outage the oracle endpoints (stats, feed, coin, activity, backtest, categories, follow, batch) answer 503 with Retry-After instead of a confident empty record, so the page shows its warming/retry state rather than "0 scored, 0 armed".- **Step count:** 3 required (arrive → feed → live stream, all automatic) + ~6 optional read interactions, + a 6-field gated arm flow (steps 8–9).---@@ -39,7 +39,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **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.+ 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. The KPIs merge `/api/oracle/stats` with the 7-day rollup; a value the API does not carry prints "n/a" (never a dash or a fake zero), PnL (7d) stays "n/a" until a settled action carries a realized figure, and the win-rate tile is coloured against the market's own base rate rather than a fixed 50%.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).@@ -47,7 +47,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **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.+- **Empty / error states:** empty feed placeholder; stale/reconnect badge with manual retry button on background-refresh failure; a stats outage renders the KPI tiles as "n/a" instead of leaving the skeleton shimmering.- **Step count:** 2 required (arrive → feed+stream) + ~3 optional (filter, paginate, copy).---@@ -57,15 +57,15 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **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`.+ 1. Arrive → inline module binds tab buttons (Agents / Trusted / Coins; arrow keys move between them) + window buttons (24h / 7d / All time), honors a `?tab=` deep link and keeps it in the address bar with `pushState`, 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 among coins scored inside the selected window, or every retained coin for All time, with ties broken by momentum and smart-wallet count so the board does not reshuffle on reload).+ 3. (optional) Switch tab Agents / Trusted / Coins → renders the other ranked list; Trusted reads `GET /api/reputation/leaderboard?limit=25`, an all-time wallet-trust score, so the window control hides on that tab.+ 4. (optional) Switch window 24h/7d/All time → re-fetch with new `window`; the legends and the coin empty state name the window.+ 5. (optional) Click a row → `/agents/<id>` for an agent, `/oracle/coin/<mint>` for a coin, `/agents/<id>/wallet#reputation` for a trusted row. The whole row is the link, so the wallet chip renders without its Tip button and popover (tipping lives on the agent page).+- **Decision points / branches:** Agents / Trusted / Coins tab; 3 time windows; per-tab retry button on fetch failure.+- **External calls / dependencies:** `GET /api/trending?window=&limit=10`; `GET /api/reputation/leaderboard?limit=25` (Trusted tab).- **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`).+- **Empty / error states:** per-tab designed empty copy that names the window ("No agent chats in this window yet.", "No coins scored in the last 24 hours.") with a widen-the-window hint and a `/create` or `/oracle` link; per-tab error + Retry button (`#agentRetry` / `#coinRetry`). Server side, an unparseable `limit` falls back to 10 (max 20) instead of failing both rankings into a fake "nothing trending", and a ranking that does fail is logged before it degrades to empty.- **Step count:** 2 required (arrive → list) + ~3 optional (tab, window, drill-in).---@@ -77,15 +77,15 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **Steps (N):**1. Arrive → `readUrl()` restores mint/tab/network (network persisted to localStorage `tf_network`); the deep-dive mounts immediately with the URL mint, or $THREE by default (never an empty void).2. System: left rail loads the active tab: **Launches** (`GET /api/pump/launches?network=&limit=40`, $THREE pinned at the top) or **Exits** (`GET /api/trades/feed?network=&window=7d&min_pnl_pct=10&limit=40`); refreshes every 30s. Header pulse (`GET /api/pump/helius-stats`, 20s) shows network mint rate, graduations/hour, and SOL price ± 24h change.- 3. System: centre deep-dive (`mountDetail`) paints header + skeleton instantly from the clicked row, then fills progressively from five live endpoints (`/api/pump/launch-detail`, `/api/pump/curve`, `/api/pump/intel`, `/api/pump/smart-money`, `/api/coin/:mint/cohorts`; cohorts only for platform-tracked coins) plus three self-fetching widgets: candlestick chart, bonding-curve ring, live trade tape.+ 3. System: centre deep-dive (`mountDetail`) paints header + skeleton instantly from the clicked row, then fills progressively from five live endpoints (`/api/pump/launch-detail`, `/api/pump/curve`, `/api/pump/intel`, `/api/pump/smart-money`, `/api/coin/:mint/cohorts`; cohorts only for platform-tracked coins) plus three self-fetching widgets: candlestick chart, bonding-curve ring, live trade tape. A row clicked in the Exits tab carries its trade with it, so an "Agent exit" card (realized PnL, exit multiple, hold time, entry/exit SOL, exit reason, entry/exit tx links, the agent's `/agents/<id>` link and "Copy trader →" to `/trader/<id>`) paints with the shell, no second round-trip. The price strip reads a migrated coin as Graduated even when the curve account is closed, and swaps the SOL cell for a "Price source" cell (Jupiter / pump.fun curve) once there is no curve price to quote.4. (optional) Switch tab Launches ↔ Exits (`#ttTabs`) → reload rail; URL synced.5. (optional) Change network mainnet/devnet (`#ttNetwork`, persisted) → reload rail + remount deep-dive.6. (optional) Paste a mint into `#ttSearch` (base58-validated) → drives the deep-dive for that coin.7. (optional) Click any rail row → `select(mint)` remounts the deep-dive (re-selecting the mounted coin is a no-op); URL reflects `?mint=` for sharing.-- **Decision points / branches:** Launches vs Exits tab; mainnet vs devnet; platform-tracked coin (cohorts fetched) vs external mint (designed no-data state); each detail section degrades independently to an honest "unavailable" note.+- **Decision points / branches:** Launches vs Exits tab; mainnet vs devnet; platform-tracked coin (cohorts fetched) vs external mint (designed no-data state); each detail lane (curve / detail / intel / smart) degrades independently: a lane that threw says "Could not load this section. The request to three.ws failed." with its own ↻ Retry that reruns only that lane, while a coin the first-seconds indexer never observed gets designed not-indexed cards pointing at `/oracle/coin/<mint>`, Bubblemaps and Solscan instead of being blamed for an outage.- **External calls / dependencies:** `GET /api/pump/launches`, `GET /api/trades/feed`, `GET /api/pump/helius-stats`, `GET /api/pump/launch-detail`, `GET /api/pump/curve`, `GET /api/pump/intel`, `GET /api/pump/smart-money`, `GET /api/coin/:mint/cohorts`.- **Success state:** live two-pane terminal: rail of platform launches/exits, deep-dive with chart, bonding curve, holders/cohorts, funder bubblemap, smart money, wallet footprint, trade tape, outcome, agent economics; shareable `?mint=` URL.-- **Empty / error states:** per-tab empty copy ("No launches on this network yet" / "No profitable agent exits in this window yet"); per-section "unavailable" degradation in the deep-dive; pulse failures silent (decorative).+- **Empty / error states:** per-tab empty copy that stays visible under the pinned $THREE row ("No launches indexed on this network yet." / "No agent exit cleared the +10% bar in the last 7 days." with a "Browse launches" action; on devnet both offer "Switch to mainnet"); feed load failure ("Could not load the launch feed." / "Could not load the agent exit feed." + Retry) only on a cold load, since a failed 30s refresh leaves the rows already on screen alone; per-lane retryable failure and not-indexed states in the deep-dive; the trade tape says "Live trades are unavailable for this coin right now. Showing settled trades only." and drops its live lamp when PumpPortal refuses the subscription; pulse failures silent (decorative).- **Step count:** 3 required (arrive → rail + deep-dive) + ~4 optional (tab, network, search, row select).---@@ -136,15 +136,15 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **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.+ 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. A parallel `GET /api/oracle/batch?mints=` sweep (chunks of 20) paints a conviction badge per card; a mint the Oracle answered for but has not scored gets an "unrated" badge linking to `/oracle/coin/<mint>`, and a chunk that failed leaves its cards' badges untouched rather than calling them unscored.+ 4. System: detects tier upgrades vs `wl_last_tiers` and surfaces changes. The summary tiles (market cap, 24h volume, graduated, average conviction) aggregate only the coins that actually report each figure, with a hover note giving the coverage ("Combined across 3 of 5 watched coins"), and the tier bar carries a muted "not scored yet" segment for the remainder so the distribution never implies an opinion the Oracle has not given.5. (optional) Toggle alerts (`#wl-alerts`, `wl_alerts_on`).6. (optional) Clear list (`#wl-clear`).7. (optional) Click a card → the coin's Oracle page (`/oracle/coin/<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).+- **External calls / dependencies:** `GET /api/pump/coin` (one per watched coin, via coin-status-card); `GET /api/oracle/batch?mints=&network=mainnet` (conviction badges, chunks of 20).- **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.+- **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; a summary tile shows the no-value dash rather than a fabricated $0 when no coin reports the figure, and the tier bar reads "Awaiting Oracle scores" or "Oracle unreachable" when nothing is scored.- **Step count:** 1 required to view (arrive) — payoff depends on the prerequisite Watch action elsewhere; + ~3 optional (alerts, clear, drill-in).---@@ -165,9 +165,9 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up9. (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.+ 12. (optional) **Configuration** (save + reconnect + probes), **API Reference** (create/revoke keys). The Revenue tab and its reporting endpoints were retired from this page on 2026-08-25.+- **Decision points / branches:** 11 hash-routed tabs (dashboard, feed, watches, claims, alerts, scanner, quoting, vanity, animations, config, api); 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); `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).@@ -202,14 +202,14 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **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.+ 3. (optional) Switch view: Feed ("Smart money is buying", with On radar / Graduated / All filters) / Top wallets / Watchlist; the Watchlist view looks up each `ld_watchlist` mint with `?mint=`.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".+- **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". A cold failure (nothing cached yet) paints "Couldn't reach the radar" with Retry on both the feed and the Top wallets view and says whether the API answered a status or was unreachable from the browser; the drawers show the explanatory "Not scored yet" (with a pump.fun link) / "No track record yet" (with a Solscan link) only when the radar answered, and offer Retry when it did not; on the Watchlist view a coin the radar could not be reached for reads "Couldn't load this one" with Retry rather than "Not on the radar yet", and if every lookup was unreachable one message covers the whole list.- **Step count:** 1 required (arrive → feed) + ~5 optional (tab, watch, inspect coin/wallet).---@@ -228,7 +228,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up- **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.+- **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. The leaderboard's own empty state reads "Nothing scored in the last 24 hours" (the radar's "loosen your filters" copy no longer appears on a tab with no filters); every failed tab (radar, both leaderboard rails, traders, all three learning panels, the drawer) carries its own Retry, and the header stat tiles fall back to dashes beside the amber degraded pulse rather than disappearing.- **Step count:** 2 required (arrive → radar feed) + ~6 optional (search/filters, watch, tabs, inspect coin).---@@ -315,21 +315,21 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up---### Constellation — `/constellation`-- **Source:** `pages/constellation.html`, `src/constellation/main.js` (~500 lines), `src/constellation/embedding.js` (PCA/MDS + neighbor lookup)+- **Source:** `pages/constellation.html`, `src/constellation/main.js` (~790 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.+- **Prerequisites / gates:** The galaxy, its live stats and its semantic layout are public; the per-star Granite analysis needs a signed-in account (it runs on the platform's own model keys), so `GET /api/auth/me` is resolved once at boot and a signed-out visitor gets a sign-in / create-account notice in the panel instead of a doomed request. 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".+ 3. System (optional/semantic): `POST /api/watsonx/embed` → 1024-d vectors → PCA to 3 axes → nodes lerp from rank positions into semantic clusters; the status names the model that actually produced the vectors: "Embedded by IBM Granite · model · 1024d", or a "Semantic layout live · <fallback embedder>" line when the embed endpoint fell through its failover chain, never a Granite credit for another model's output.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).+ 5. (optional) Hover star → glow + tooltip (symbol/name). The canvas is focusable: arrow keys walk the stars in trending-rank order with the tooltip following, Home/End jump to the ends, and Enter/Space opens the focused star. Picking tolerates a near miss (22px, 34px on a coarse pointer; a tap gets 46/60px and is judged on movement, not hold time) so the visible glow is the target.+ 6. (optional) Click star → right detail panel (symbol, name, logo, market cap, price when the feed carries one, rank, nearest semantic neighbors once vectors land, Pump.fun/Solscan links); the panel is `inert` while closed and hands focus back to the canvas after a keyboard open.+ 7. (optional) **Analysis payoff:** selecting a star fires `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. The byline names what actually answered: the `meta` event's model label, or after a `fallback` event "Analysis by <route>" with a meta line saying Granite could not serve the request.+- **Decision points / branches:** WebGL present vs fatal; signed in (analysis streams) vs signed out (sign-in notice); Granite configured (semantic layout + analysis) vs unconfigured (rank layout, analysis notice) vs served by a fallback (labelled as such); rate-limited; <3 tokens → fatal.+- **External calls / dependencies:** `GET /api/pump/trending?limit=64`; `GET /api/auth/me`; `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.+- **Empty / error states:** WebGL fatal overlay; a feed failure ("Couldn't load live tokens.", naming the pump.fun trending feed) and "No trending tokens right now." both carry a "Try again" button that rebuilds the galaxy (disposing the previous nodes' materials); a semantic-layout-off status when IBM watsonx is not configured (stars placed by trending rank); analysis notices (sign in required / unconfigured / rate-limited / every route refused / stream error), each telling the visitor to pick the star again to retry.- **Step count:** 2 required (arrive → galaxy renders) + ~5 optional (orbit/zoom, hover, select, Granite analysis). Live-data exploration + AI analysis.---@@ -364,14 +364,14 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up2. System: `loadAgent(id)` → `GET /api/agents/:id` names the co-pilot and labels it "Your alpha co-pilot" for the owner or "Alpha co-pilot · public read" for everyone else; the `<agent-3d>` avatar mounts from `agentAvatarGlb()`.3. System: `loadCandidates()` → `GET /api/agents/:id/alpha/candidates?network=mainnet` renders the live pump.fun launch rail behind 4 skeleton cards, counts up the launch total, and marks one "top pick" ranked by real smart-money + quality signals with a penalty for a sybil-dominated funder graph.4. **Read payoff:** click a launch (or arrive with `?mint=`) → `POST /api/agents/:id/alpha/read {mint, network}` → thinking state, then a verdict (Snipe / Watch / Pass), a conviction bar that fills from 0, the spoken line, "What could go wrong" risks, and the eight grounded signal rows (liquidity, market cap, age, buy impact at 0.1 SOL, curve filled, quality, smart money + wallet count, organic), with the rows the agent actually cited highlighted.- 5. System: the avatar speaks the verdict: `POST /api/tts/eleven` when the agent has a voice, else `POST /api/tts/speak`, else the browser `speechSynthesis` fallback. If the server's hallucination guard replaced a figure, the panel says so and points at the signals as ground truth.+ 5. System: the avatar speaks the verdict: `POST /api/tts/eleven` (with `agentId`, so an owner-cloned voice is served on the owner's saved ElevenLabs key) when the agent has a voice, else `POST /api/tts/speak`, else the browser `speechSynthesis` fallback. If the server's hallucination guard replaced a figure, the panel says so and points at the signals as ground truth.6. (optional) Owner extras in the read: the wallet line shows balance, per-trade limit, daily budget, and a paused flag.- 7. (optional) **Act payoff (owner, gated):** click "Act, buy N SOL" → drawer opens → `previewAgentTrade()` fetches a fresh live quote (you pay / expected tokens / price impact, plus any warning) → **Confirm buy** → `executeAgentTrade()` posts through the guarded agent wallet path (spend limits and firewall re-checked at submit, written to the custody audit) → done state with the Solscan tx, the new wallet balance, and a link to the custody trail.+ 7. (optional) **Act payoff (owner, gated):** click "Act: buy ◎N" → drawer opens (focus moves inside and returns to the trigger on close) → `previewAgentTrade()` fetches a fresh live quote (you pay / expected tokens / price impact, plus any warning) → **Confirm buy** → `executeAgentTrade()` posts through the guarded agent wallet path (spend limits and firewall re-checked at submit, written to the custody audit) → done state with the Solscan tx, the new wallet balance, and a link to the custody trail.8. (optional) Replay the last spoken line; refresh the launch rail; paste a different agent ID or profile URL; pick another agent from the public gallery.- **Decision points / branches:** owner vs public read (act button vs gate message); `gate.can_act` true vs blocked with a reason; agent resolved from URL / storage / session / featured vs none at all (the gallery becomes the call to action, and only if the gallery is empty does the ID row open); ElevenLabs voice vs server TTS vs browser speech; hallucination guard triggered vs clean; reduced motion (bars and counters land at their final values).- **External calls / dependencies:** `GET /api/agents/:id`, `GET /api/agents/me`, `GET /api/agents/featured`, `GET /api/agents/public?sort=popular&limit=12`, `GET /api/agents/:id/alpha/candidates`, `POST /api/agents/:id/alpha/read`, `POST /api/tts/eleven`, `POST /api/tts/speak`; `previewAgentTrade` / `executeAgentTrade` (`POST /api/agents/:id/solana/trade`) for the act path.- **Success state:** a named 3D agent reads a real launch aloud in character, shows the live signals behind the call, and the owner can act on it through the same guarded, audited wallet path the conversational copilot uses. The narrator itself never moves funds.-- **Empty / error states:** "No live launches on the feed this second" with "Check again"; "Live feed hiccup" with Retry; read failure with "Try again"; "Couldn't fetch a live quote"; trade errors rendered above the confirm button with the button re-enabled; no-agent fallback copy on the avatar placeholder.+- **Empty / error states:** "No live launches on the feed this second" with "Check again"; "Live feed hiccup" with Retry; read failure with "Try again"; "Couldn't fetch a live quote"; trade errors rendered above the confirm button with the button re-enabled; no-agent fallback copy on the avatar placeholder. The launches column never renders as an empty box: before an agent is on stage it reads "Pick a co-pilot above and the live launches it can read land here." (or the ID-entry variant when the gallery is empty), and an agent that fails to load clears the previous one off the stage rather than leaving its launch cards wired to nothing.- **Step count:** 3 required (arrive → agent + launch rail → read) + ~5 optional, including the owner-gated buy (steps 7 to 8).---diff --git a/docs/ux-flows/08-coin-launch-wallets.md b/docs/ux-flows/08-coin-launch-wallets.mdindex 32c82c44b..a10718ed7 100644--- a/docs/ux-flows/08-coin-launch-wallets.md+++ b/docs/ux-flows/08-coin-launch-wallets.md@@ -48,7 +48,7 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.- 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/native-launch/config`, `/api/native-launch/launch-prep`, `/api/native-launch/launch-confirm`, `/api/solana-rpc` (Connection RPC). External: `esm.sh/@solana/[email protected]`, `esm.sh/[email protected]`, pump.fun (mint target), Solscan (links).+- **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/native-launch/config`, `/api/native-launch/launch-prep`, `/api/native-launch/launch-confirm`, `/api/solana-rpc` (Connection RPC). External: `@solana/[email protected]` and `[email protected]`, both loaded through `/load-module.js` (the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline; if all three miss the panel says "<what> could not be loaded (<hosts> unreachable or blocked). Check your connection or ad blocker and try again."; `fees-panel.js` loads web3.js the same way), 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)@@ -78,21 +78,21 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.### 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`.+- **Entry point:** `#cwInput` address field + `#cwBtn` **Analyze**; results render in `#cwResult` (a polite live region).- **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 60 recent pump.fun coins.+ 3. Click **Analyze** (button reads "Analyzing…" and is held by the page while busy so a late-landing locale catalog cannot overwrite it) → `GET /api/traders/preview?wallet=` (in parallel with a SOL price read) → skeleton, then the Trader Card: label, KPI row (win rate, early-entry win rate, smart-money score, net PnL, dump rate; the reputation rates arrive already in percentage points and are printed as-is), a 7D / 30D / ALL time-window toggle, and a **Trade ledger** of up to 60 recent pump.fun coins with sortable columns, filter chips (Hide dust, on by default / Open only / Created), a header that reads "N of M coins · window", and a per-row link to `/launches/<mint>`.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."+ 8. On success, re-read linked wallets (force) and re-render in the claimed state; message "Claimed" (or "Moved to your account" after a takeover) followed by "your Trader Card is live."- **Decision points / branches:** claimable-or-known vs. not-indexed (`notFoundHtml`); a wallet the indexer has seen trade is claimable even before the rollup grades it, so only a wallet with neither a reputation row nor a single indexed trade takes the not-indexed branch; 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.+- **Empty / error states:** invalid-address inline error (`role=alert`); a dead or non-OK fetch → an error card in the results area with the server's message (or a connection explanation) and a **Try again** button, never a blank page; "Wallet not yet indexed" not-found state; an empty ledger explains itself ("No pump.fun trades from this wallet in the last 7/30 days" with **Widen to all-time →**; a wallet the brain has graded but whose per-coin rows are still being indexed says so; "No indexed pump.fun trades for this wallet yet"); filters that exclude every row → "None of this window's N coins match the active filters" + **Clear filters**; signature-cancelled message; per-step error toasts on the claim button.- **Step count:** 8 required (claim path; preview alone is 3)---@@ -109,11 +109,11 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.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.- 8. (optional) **Send a sealed gift** (`sealed-drops.js`): compose a funded wallet drop (asset/amount, optional vanity pattern reusing the page's grind fields, seal mode "Bearer link" vs direct X25519 key, message/theme, expiry, optional reclaim address) → pays the x402 create fee → shareable `/drop/:id` link + QR + OG card. The recipient's claim page opens the ECIES sealed envelope entirely client-side (claim key rides the URL fragment in bearer mode), then offers import / download / sweep; three.ws never sees the plaintext key. "Gifts you've sent from this browser" lists sent drops with reclaim for expired ones.+ 8. (optional) **Send a sealed gift** (`sealed-drops.js`): the form first reads the drop config from `/api/vanity/drops` and applies it (the asset list is narrowed to what the funding wallet supports, the expiry field takes the server's min / max / default hours, and the hint states the create fee, or explains that sealed drops are unavailable when no funding wallet is configured); then compose a funded wallet drop (asset/amount, optional vanity pattern with its own "Starts with" / "Ends with" fields, seal mode "Bearer link" vs direct X25519 key, message/theme, expiry, optional reclaim address) → pays the x402 create fee → shareable `/drop/:id` link + QR + OG card. The recipient's claim page opens the ECIES sealed envelope entirely client-side (claim key rides the URL fragment in bearer mode), then offers import / download / sweep; three.ws never sees the plaintext key. "Gifts you've sent from this browser" lists sent drops with reclaim for expired ones.- **Decision points / branches:** prefix vs suffix vs both; case-sensitive vs insensitive; assign vs keep self-custody; replace-existing-wallet branch; gift seal mode bearer vs direct-key; gift claimed vs expired (reclaim).- **External calls / dependencies:** None for grinding (client-side WASM ed25519 workers). Assign: `/api/agents`, `/api/agents/:id/solana` (POST + DELETE). Gifts: `/api/vanity/drops` (+ x402 create fee, on-chain funding/reclaim server-side).- **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.+- **Empty / error states:** invalid-Base58 preview; combined-length-over-max warning; grind-failed error; assign 401 (sign-in link to `/login?next=/vanity-wallet`) / empty / 409 handled inline; an agent-list load failure says "Could not load your agents (…). Your wallet above is unaffected: download it now, then retry." with a **Retry** button, since only the assignment step is lost; sealed drops disabled when the funding wallet is not configured.- **Step count:** 3 required (+4 optional)---@@ -167,7 +167,7 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.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).+- **External calls / dependencies:** bridge `status`/`quote`/`pay` (`/api/agent-wallet-bridge` or local `:4402`); the paid endpoint `https://three.ws/api/x402/crypto-intel` (the hosted bridge calls it through the shared upstream fetch: the 402 probe is bounded and retried on a dropped connection, while the re-send that carries the signed payment is a single attempt with a timeout only, because a retry could double-spend); 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)@@ -182,31 +182,31 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.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. The API reports an unreadable balance as `balanceAvailable: false` instead of failing the response, so an RPC blip shows "balance unavailable" while the address + explorer link survive.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. An unknown balance never triggers the hint (unreachable RPC ≠ empty wallet).- 4. User chats; `ask()` streams an assistant reply, the avatar speaks/gestures, and the model may emit actions.+ 4. User chats; `ask()` streams an assistant reply, the avatar speaks/gestures, and the model may emit actions. A turn that fails is not a dead sentence: the bot bubble is marked errored with the reason (the server's `error_description`, or "I couldn't reach my brain. Check your connection and try again." when the fetch itself died) and carries a **Try again** button that re-sends the same message.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:** "balance unavailable" chip (with fund hint suppressed) when the RPC is unreachable; fund-hint / low-balance states; payment-failed card + toast + avatar "didn't go through"; governance-blocked chip.+- **Empty / error states:** "balance unavailable" chip (with fund hint suppressed) when the RPC is unreachable; fund-hint / low-balance states ("Only X SOL, not enough to cover a $1 send plus fees. Top it up at the address below."); errored chat bubble with **Try again**; payment-failed card + toast + avatar "didn't go through"; governance-blocked chip ("Send held by IBM Granite Guardian: <reason>").- **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 the profile page's "Claim <username>.threews.sol" wallet pill (`pages/profile.html`).-- **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`.+- **Entry point:** an **account card** (`#tw-account`, polite live region, skeleton while loading) above the mint card; `#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`); the label is the account's username, so a username must be set and must be a valid `.sol` label (a-z, 0-9, hyphens, not starting or ending with a hyphen). 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; label must equal the account's username (the server 409s `username_mismatch` otherwise, and requires a username to be set); signed-in vs not; optional `owner_wallet` must be a Solana wallet already linked to the account.-- **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.+ 1. Boot checks the session (`GET /api/auth/me`, skipped for anonymous visitors so the 401 never logs) then `GET /api/threews/me` and renders the account card: anonymous → "Sign in to mint a subdomain. You can still check availability below." + Sign in; already claimed → "You already own <full>." with the owned-name card (showcase URL, tx link); no username → "Set a username before claiming a subdomain." + link to account settings; unmintable username → "Your username @x cannot be a .sol label…" + Change your username; ready → "Signed in as @handle. Your subdomain label must match your username.", the label input is pre-filled with the username and made read-only, and the availability check fires at once.+ 2. For an anonymous visitor the label input stays free-typed: lowercased, stripped to `[a-z0-9-]`, debounced 350ms availability check `GET /api/threews/subdomain?label=` → "<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`. Before minting, the server re-checks the on-chain owner as a hard gate (minting over a taken name burns rent and fails anyway); if that read fails it answers `503 upstream_unavailable` ("could not verify the name on Solana right now; retry in a moment") rather than a server error.+ 4. On success → "<full> minted." status, the account card flips to "You own <full>." with a **View your showcase** link, and the owned-name card shows the showcase URL and a Solscan tx link for the mint signature.+- **Decision points / branches:** anonymous / claimed / needs-username / unmintable-username / ready account states; available vs taken; label must equal the account's username (the server 409s `username_mismatch` otherwise); optional `owner_wallet` must be a Solana wallet already linked to the account; `DELETE /api/threews/subdomain?label=` releases a stored subdomain.+- **External calls / dependencies:** `/api/auth/me`, `/api/threews/me`, `/api/threews/subdomain` (GET check + POST mint + DELETE release), `/api/csrf-token`; Solscan (tx link). On-chain SNS mint.+- **Success state:** Minted name card with showcase URL + tx signature link; account card in the claimed state.+- **Empty / error states:** "Type a label to check availability."; availability check unreachable → "Could not reach three.ws to check availability…" with a retry; availability "bad" state for taken names; account lookup failure → account card error state with retry; mint `401` → "Your session has expired. Sign in again to mint." + Sign in; mint `no_wallet` → "Create an agent" link (`/create`); mint `429/502/503` → the server's message with a retry action; any other mint failure re-enables the button with the server's `error_description`.- **Step count:** 4 required---@@ -221,7 +221,7 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.3. (optional) **Hold more $THREE** → opens the Jupiter swap modal (SOL → $THREE) in place.4. (optional) Per-feature access matrix from `/api/three/access` shows what each tier unlocks (`enforced` / `eligible` / `required`).- **Decision points / branches:** wallet connected or signed in (tier highlighted) vs neither (connect/sign-in prompt); ladder loaded vs outage (retry); holdings overflow handled gracefully at $10M+.-- **External calls / dependencies:** `/api/three/tier`, `/api/three/access` (both `?wallet=`-aware), Jupiter swap modal, `/three-token` (price page link).+- **External calls / dependencies:** `/api/three/tier`, `/api/three/access` (both `?wallet=`-aware), Jupiter swap modal (`src/swap-jupiter.js`: quote 12s, swap build 20s and verified-token list 8s deadlines, so a stalled Jupiter surfaces as an error instead of a hung modal), `/three-token` (price page link).- **Success state:** populated tier ladder with the visitor's real tier, delta to the next tier, and a working in-page path to hold more.- **Empty / error states:** all five states designed: skeleton ladder while loading, connect/sign-in prompt with the public ladder, actionable error with retry, populated ladder, $10M+ overflow formatting.- **Step count:** 1 required (+3 optional)@@ -246,17 +246,18 @@ real Solana/EVM RPC, pump.fun, and x402 — no mocks.### 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.+- **Entry point:** Full-screen Three.js scene seeded by `?mint=<base58>` (& optional `&network=`); without a mint the page is a landing card.+- **Prerequisites / gates:** None. 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.+ 1. No `?mint=` → landing card: "See any token in 3D" with a paste-a-mint form (**View in 3D**, inline validation), a "View $THREE in 3D →" link, a "Recent launches on three.ws" grid of 8 cards from `/api/pump/launches?limit=8` (falling back to the encoded `/api/pump/%5Baction%5D?action=launches` form so a partial deploy never empties it; each card shows the launching agent's avatar or the symbol initials, no per-card fetch), and links to `/launches` and `/launch`.+ 2. With a mint: loading overlay, then the snapshot: `getTokenDetails` + `getBondingCurve` via `POST /api/pump-fun-mcp` (15s deadline each; a timeout or unreachable endpoint is kept apart from a JSON-RPC "no such token" answer) in parallel with GeckoTerminal token info (mainnet only: the reliable name / symbol / logo / market-cap source for graduated coins whose metadata authority is renounced, `$THREE` included). The logo is fetched from the metadata URI through the shared IPFS gateway chain (`src/ipfs.js`, 6s per fetch, walking the whole gateway list on retry).+ 3. The data HUD paints first and the overlay clears, then the scene: spinning coin medallion (logo-textured), graduation ring filled to bonding-curve progress, OrbitControls. If WebGL is unavailable the page degrades to the HUD + live tape instead of hanging on the spinner.+ 4. Async enrichment, none of it blocking the render: `getTokenHolders` (top 12, 25s deadline, best-effort; its HUD cell shows a pulsing bar until it lands and the holder galaxy fills in, spheres sized by balance and tinted by concentration; an empty scan says so), Oracle conviction (`/api/oracle/coin`), coin intel (`/api/pump/coin-intel`), market figures + sparkline (`/api/pump/price-history?interval=15m`, refreshed every 60s), and a live trade tape (`/api/pump/dex-trades?limit=40`, polled every 9s).+ 5. (optional) Watchlist toggle persists to localStorage (`ld_watchlist`, shared with `/launches`); HUD links out to the coin's 3D world (`/communities/<mint>`).+- **Decision points / branches:** mint present vs missing (landing); mainnet vs devnet; every source unreachable vs a definite "not a token"; logo available vs fallback; WebGL available vs data-only fallback.+- **External calls / dependencies:** `/api/pump-fun-mcp` (pump.fun MCP), GeckoTerminal token info, IPFS gateway chain for the logo, `/api/oracle/coin`, `/api/pump/coin-intel`, `/api/pump/price-history`, `/api/pump/dex-trades`, `/api/pump/launches` (landing grid). All on-chain/live.+- **Success state:** interactive 3D token scene (medallion + holder galaxy + graduation ring) with a live HUD, sparkline and trade tape.+- **Empty / error states:** landing card with a validated mint form; loading overlay; every live source failing to respond → "Every live source for this token failed to respond. Check your connection, then try again." + **Retry**; a definite miss → "Token not found" + **Browse coins** (`/launches`); empty holder scan, "No price history yet." / "Price history unavailable." sparkline slot, and "Live trades are unavailable right now. Retrying every few seconds." tape, each in place; recent-launches grid → "No launches yet. Be the first →" or a "Browse launches →" fallback.- **Step count:** 3 required (+1 optional)---diff --git a/docs/ux-flows/09-x402-agent-commerce.md b/docs/ux-flows/09-x402-agent-commerce.mdindex 61599a1ae..dd34630ce 100644--- a/docs/ux-flows/09-x402-agent-commerce.md+++ b/docs/ux-flows/09-x402-agent-commerce.md@@ -27,9 +27,9 @@ choreographed two-agent narrative driven by Server-Sent Events.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`.+- **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`. The Phantom path imports `@solana/web3.js` through `/load-module.js`, which tries the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline, so one blocked CDN no longer stalls the run at the signing step.- **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.+- **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; Solana RPC unreadable while the server builds the transfer (every read on that path is guarded and cache-backed first) → `503 rpc_unavailable` with a `Retry-After` header and the copy "No funds were transferred; retry shortly" (the same guard answers `/api/x402-checkout?action=prepare`); a wallet component that fails to load on all three CDN mirrors → the failed step names the hosts it tried.- **Step count:** 4 required (+ ~4 optional).### Paid-call permalink — `/pay/calls`@@ -65,16 +65,16 @@ choreographed two-agent narrative driven by Server-Sent Events.- **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. The handler merges every configured facilitator behind a 60s in-process catalog memo (`BAZAAR_CATALOG_TTL_MS`), returns at most `limit` rows (default 200) and reports the pre-cut match count as `total`.+ 1. Page loads → `GET /api/bazaar/list` → renders endpoint cards. The handler merges every configured facilitator behind a 60s in-process catalog memo (`BAZAAR_CATALOG_TTL_MS`), returns at most `limit` rows (default 200) and reports the pre-cut match count as `total`; `offset` (default 0) skips that many matches so a caller can page past the cap. The page asks for one page at a time (`limit=200`, or 100 for a search) and walks the rest with `offset`: the count reads "200 of 1,234" and a **Load more** button appends the next page, disappearing once everything is shown or when a page comes back empty because the catalog moved. Every request carries a sequence number and aborts the one in flight, so the cards always match the controls the user last touched.2. (optional) Filter by type (HTTP/MCP), network (EVM/Solana), max price, extension, sort.- 3. (optional) Search (`/api/bazaar/search?query=`) or scroll.+ 3. (optional) Search (`/api/bazaar/search?query=`, same `offset` paging) or scroll, then **Load more**.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" (every `/api/bazaar/*` handler answers `502 facilitator_error` when all facilitators fail, so a total outage never renders as an empty catalog); modal load fail → "Payment module failed to load"; cancel → receipt hidden; error → red receipt.+- **Empty / error states:** no results → "No matching services…"; catalog unreachable → "Couldn't reach the catalog… Retry" (every `/api/bazaar/*` handler answers `502 facilitator_error` when all facilitators fail, so a total outage never renders as an empty catalog); modal load fail → "Payment module failed to load"; cancel → receipt hidden; error → red receipt; a **Load more** failure keeps the rows already on screen and puts the reason next to the button ("Couldn't reach the catalog. Try again." or "Could not load more: …"); a cross-origin endpoint whose response carries no CORS headers → the modal's discover step says "<host> does not allow browser requests … Call it from a server, an agent, or the x402 CLI instead" and offers no Try-again button, since the same click can never succeed.- **Step count:** 5 required (+2 optional).### x402 Arbitrage — `/arbitrage`@@ -83,16 +83,16 @@ choreographed two-agent narrative driven by Server-Sent Events.- **Prerequisites / gates:** None to browse; wallet only to pay.- **Deep links in:** `/arbitrage?focus=<capability>` (what `/bazaar` sends from a listing's priced-peers hint), `?q=<text>`, `?type=http|mcp`. The page writes its own filter state back with `replaceState`, so any filtered view is shareable.- **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).+ 1. Page loads → `GET /api/bazaar/arbitrage?minSpreadPct=0&limit=200` → skeleton then arb cards (spread %, up to 5 providers cheapest-first, metrics). A source strip (`#sources`, polite live region) names every facilitator that answered with its listing count; one that dropped out reads "<host> unreachable" (reason on hover) under an amber "Partial scan: N of M facilitators unreachable" pill, because the handler ships its `errors` next to `sources` and a half-blind scan must not read as a quiet market.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.+ 4. Result shows on the button: "✓ Paid" (auto-revert 4s) / "Failed: …" or "Error: …" (auto-revert 4s) / closing the modal hands the button straight back with no hold.5. (optional) Click **Avoid · $Y** → navigates to `/bazaar?q=<capability>` (plus `&type=mcp` for MCP capabilities, since the catalog defaults to the HTTP tab) to see the full spectrum.- **Decision points / branches:** MCP capability → "Pay" redirects to the catalog (can't call MCP directly); on-demand x402 load; button state management.- **What counts as an opportunity (backend):** listings are grouped by capability key (MCP tool name, else service name, else the last literal URL segment; route placeholders like `/:solana_address` and `/{mint}` are skipped because they name the argument, not the capability). A group ships only if it spans two or more provider hosts, or if one host has a single resource quoted at two different prices by two different facilitators (a genuine cross-venue gap). A vendor charging different prices for its own distinct endpoints is not arbitrage and is dropped.- **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:** filters exclude everything → "No opportunities match these filters" with a Clear-filters button and a catalog link; feed genuinely has no gap → "No cross-provider price gaps right now" with links to `/bazaar` and `/providers`; timeout (20s) → "Request timed out… Retry"; feed error → "Couldn't reach the arbitrage feed…"; modal fail → "Payment modal failed to load".+- **Empty / error states:** filters exclude everything → "No opportunities match these filters" with a Clear-filters button and a catalog link; feed genuinely has no gap → "No cross-provider price gaps right now" with links to `/bazaar` and `/providers`; timeout (20s) → "Request timed out… Retry"; feed error → "Couldn't reach the arbitrage feed…"; a partial scan renders normally with the degraded source strip rather than as an error; modal fail → "Payment modal failed to load".- **Step count:** 3 required (+3 optional).### x402 Providers — `/providers`@@ -159,7 +159,7 @@ choreographed two-agent narrative driven by Server-Sent Events.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. When the LLM stages cannot reach a provider, the check degrades instead of failing: real sources still return with neutral stances, the response carries a `degraded` marker, and the result is never cached (so a provider outage is not pinned for 7 days).-- **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; the whole pipeline runs under a wall-clock budget, `FACT_CHECK_BUDGET_MS`, default 45s, so it never outlives the edge's 60s cutoff), Base/Solana USDC, Redis cache (7-day TTL, full-chain results only).+- **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; the whole pipeline runs under a wall-clock budget, `FACT_CHECK_BUDGET_MS`, default 45s, so it never outlives the edge's 60s cutoff), Base/Solana USDC, Redis cache (7-day TTL, full-chain results only; every cache read and write is bounded at 2s, reads retry once, so a slow Upstash degrades to a cache miss instead of holding a paid request open).- **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).@@ -201,14 +201,14 @@ choreographed two-agent narrative driven by Server-Sent Events.- **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).+ 3. (optional) Select fee rate → live fee estimate (`#feeEstimate`) with sats / BTC / ≈USD (the first of four keyless price feeds to answer: CoinGecko, Coinbase, Kraken, DefiLlama, 4s each, 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.+ 6. Pay view: QR (BIP-21; api.qrserver.com, then quickchart.io, and if both fail the payment URI as selectable text so the payer is never left with a broken image), 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`. Once a reveal txid exists the response also carries `inscription.onchain` (confirmed, confirmations, block height and time) read keyless from Blockstream Esplora, so finality depth comes from the chain rather than from OrdinalsBot's order state; an Esplora outage degrades that field to `null` instead of failing the poll.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; signed-out → the server's 401 copy surfaces in the error banner; confirm-dialog cancel → stays in compose; order-create `502/503` → "Inscription failed. Try again."; status `failed` → OrdinalsBot contact note; status `404` (the order id no longer resolves upstream) → polling stops, the saved order is cleared, and the page returns to compose with a nothing-was-charged explanation; reload mid-payment → `resumeIfAny()` restores the pay view + resumes polling (unless the saved order 404s, which takes the same retire path).-- **External calls / dependencies:** `/api/forever/inscribe` + `/api/forever/status` → **OrdinalsBot** (`api.ordinalsbot.com`, Bitcoin mainnet Taproot inscription), Blockstream Esplora (`api/_lib/esplora.js`, keyless reveal-tx confirmations, fail-soft), CoinGecko (USD, best-effort), QR server, mempool.space + ordinals.com for verification.+- **Decision points / branches:** empty / > 1500 bytes / invalid Taproot / invalid fee rate → inline errors; signed-out → the server's 401 copy surfaces in the error banner; confirm-dialog cancel → stays in compose; order-create `502/503` → "Inscription failed. Try again." (the OrdinalsBot order call is bounded at 30s and never retried, since a retry after a request that actually landed would buy a second inscription); a non-OK, non-404 poll (including the `502` the API answers when OrdinalsBot misses its 15s deadline twice) is skipped and the next 6s tick retries; status `failed` → OrdinalsBot contact note; status `404` (the order id no longer resolves upstream) → polling stops, the saved order is cleared, and the page returns to compose with a nothing-was-charged explanation; reload mid-payment → `resumeIfAny()` restores the pay view + resumes polling (unless the saved order 404s, which takes the same retire path).+- **External calls / dependencies:** `/api/forever/inscribe` + `/api/forever/status` → **OrdinalsBot** (`api.ordinalsbot.com`, Bitcoin mainnet Taproot inscription), Blockstream Esplora (`api/_lib/esplora.js`, keyless reveal-tx confirmations, fail-soft), four BTC/USD feeds (CoinGecko, Coinbase, Kraken, DefiLlama; best-effort), two QR services (qrserver, then quickchart), 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).@@ -234,16 +234,16 @@ choreographed two-agent narrative driven by Server-Sent Events.### 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.+- **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`) runs with Run disabled and a skeleton card ("Checking the demo wallets") in the centre; configured → ready card + Run enabled; unconfigured → modal overlay walkthrough + env instructions, Run stays disabled; pre-flight unreachable → a "Status check failed" card with **Retry the status check**, and Run is left enabled so the run itself reports what failed.- **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).+ 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; the buyer bubble "Sending X SOL on-chain…" carries an indeterminate progress bar, since a real transfer can take tens of seconds and static text is indistinguishable from a stalled page) → `confirmed` (burst, Solscan tx card, balance debited) → `delivering` ("Analyzing with <model>…", same pending bar) → `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.+- **Decision points / branches:** topic feeds the request payload; config gate (dismiss only hides overlay); `error` event → the active chip flips red, a toast fires, and a centre failure card names the cause in its badge (`insufficient_funds` "Buyer wallet is short", `daily_budget_exhausted` "Daily spend limit reached", `analysis_unavailable` "No analysis model available", `analysis_failed` "Analysis failed after payment", `send_failed` "Payment failed", anything else "Trade stopped") with a **Run it again** button; `not_configured` instead re-opens the walkthrough overlay and disables Run; a stream that drops mid-run gets the same card badged "Stream dropped". Below 560px the labels and bubbles leave the 3D projection and stack into a flat strip (the layout the no-WebGL fallback also uses) so the card never paints over a speech bubble.- **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.+- **Empty / error states:** pre-flight skeleton card; not-configured modal overlay + unconfigured card; status-check-failed card with retry; failure card (badge + message + Run it again) on any `error` event or dropped stream; idle ready card.- **Step count:** 2 required (auto SSE thereafter).### Agent Economy (Live) — `/agent-economy`@@ -272,8 +272,8 @@ choreographed two-agent narrative driven by Server-Sent Events.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.+- **Decision points / branches:** configured+funded vs underfunded (error w/ fund notice) vs not-configured (error, prompts anon to sign in); `simulated=true` → the pay card reads "Simulated payment" and asks the visitor to sign in to run a live on-chain transfer, plus a "Mode: Simulated" row. 35s hard timeout.+- **External calls / dependencies:** `/api/demo-economy` (SSE), Solana RPC settlement (if live), GeckoTerminal trending pools for the briefing (read through the shared upstream fetch: 8s deadline, one retry, breaker-guarded, and backed by a last-known-good copy up to 30 min old, so a throttled upstream leaves the demo with a briefing flagged `stale` + `as_of` rather than nothing to sell), 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).@@ -330,7 +330,7 @@ choreographed two-agent narrative driven by Server-Sent Events.## Notes- **Routing:** all clean URLs resolve through the `vercel.json` route table — read directly by the Cloud Run server (`server/index.mjs`) in production and mirrored by the `vite.config.js` `historyApiFallback` map in dev. `/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.+- **Shared payment modal:** `/x402.js` (`public/x402.js`, ~2.4k 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. Its Solana web3.js and SIWX hashing imports go through `/load-module.js` (the pinned version on esm.sh, then jsdelivr, then unpkg, each under a deadline); only when all three fail does the modal steer the buyer to MetaMask on Base, which needs no third-party code. A cross-origin endpoint whose response carries no CORS headers is reported as "<host> does not allow browser requests" with a pointer to a server, an agent, or the x402 CLI, and no Try-again button.- **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.diff --git a/docs/ux-flows/10-chat-brain-labs.md b/docs/ux-flows/10-chat-brain-labs.mdindex c10cdb097..27c5bb0da 100644--- a/docs/ux-flows/10-chat-brain-labs.md+++ b/docs/ux-flows/10-chat-brain-labs.md@@ -9,7 +9,7 @@ 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/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. Voice output is opt-in (off by default).+- **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; sign-in only for cross-device sync + on-chain tool calls, either by wallet (SIWE/SIWS via `/api/auth/*`, `chat/src/walletAuth.js`) or by email/password on the platform's own cookie session (`chat/src/passwordAuth.js` POSTs `/api/auth/login` / `/api/auth/register`, with the Terms clickwrap gating the submit); `TxApprovalModal` requires a connected wallet for wallet/pump tool transactions. No $THREE gate. Voice output is opt-in (off by default).- **Steps (6):**1. Open `/chat`; app boots, fetches the free model list from `/api/chat/models`, shows empty state with suggestion chips. `BUILTIN_MODELS` in `providers.js` is only a first-paint seed; `resolveDefaultModel()` prefers a model the server reports as live, so if the configured default has been retired upstream a new conversation opens on a live model instead of a dead one. The list also carries one virtual entry, "three.ws Agent · server tools": a server-side agent loop that answers through `/api/chat/proxy` in the same wire format but runs multiple tool-calling LLM rounds per message; it is appended last so it can never become the silent default.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). Loading an agent mounts its live `<agent-3d>` avatar in the panel.@@ -18,9 +18,9 @@ modules. Routes resolved via `vercel.json` rewrites.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 an agent is loaded, its `<agent-3d>` avatar plays the talk animation (`agentEl.speak(...)`) and expresses the classified emotion (`agentEl.expressEmotion(...)`); those two calls are animation only and carry no audio. With voice output enabled, browser `speechSynthesis` reads the reply aloud, agent or not. Payoff: a 3D agent that answers in voice with 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 (agent-3d speech vs browser speechSynthesis vs silent); persona/agent loaded vs raw model; tool-calling on/off (16 curated tool packs in `tools.js` `curatedToolPacks`, surfaced via `ToolPackModal`: wallet-transactions, x402-pay, tradingview, price-chart-3d, token-price, token-ticker-3d, web-search, date-time, pump-launch, tx-explain, mint-scene-nft, nft-3d-import, forge-text-to-3d, forge-avatar, wallet-balances, token-gate-scene; the built-in wallet/agent/pump/payments tool schemas back them); every generated 3D model card carries "View in AR ↗" (`/ar?src=<glb>`), "Download GLB", and "Viewer ↗" actions; 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/mcp` + `/api/pump-fun-mcp` (skills marketplace / pump tools), `/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.+- **External calls / dependencies:** `/api/chat/models` (free model list, OpenRouter-proxied), `/api/chat/proxy` (built-in completions), `/api/chat/config`, `/api/mcp` + `/api/pump-fun-mcp` (skills marketplace / pump tools), `/api/agents` + `/api/marketplace/agents` (agent picker), `/api/auth/{me,logout,siwe/nonce,siwe/verify,siws/nonce,siws/verify}` (wallet auth), `/api/auth/{login,register}` (email/password 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.- **Success state:** Streamed assistant message rendered; with voice enabled the reply is read aloud once per message (a repeated end-of-stream chunk cannot double-speak it), and a loaded agent mouths along with mood animation; 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; speech failure degrades silently to text.+- **Empty / error states:** Empty state with brand tagline + suggestion chips when no messages. Provider/network errors surface as inline notices: a request that never left the device is tagged `code: 'network'` in `convo.js` and renders "Could not reach the model. The request never left this device, so nothing was sent…" with a hover-refresh hint, and a stream that dies mid-reply renders "The reply stopped early because the connection dropped…" instead of the transport's own wording; the built-in proxy waits at most 25s for OpenRouter to start answering, rotates keys and models on a timeout, and reports a clean 504 when every route hangs. Abortable generation via `controller`. Missing API key → model marked unavailable in selector. Avatar GLB load failure falls back to default avatar; speech failure degrades silently to text.- **Step count:** 6 required (+4 optional)- **Voice path (resolved 2026-08-06):** there is exactly one speaker, browser `speechSynthesis`, gated on the voice-output toggle. The legacy standalone Talking Head component (a CDN build of met4citizen/TalkingHead pointed at the long-retired `/api/tts/google`) was imported but never rendered, and its dead `talkingHeadEnabled` flag suppressed `speechSynthesis` for anyone whose browser still carried the flag from an older build. Component, flag, and both dead branches are removed. `talkingHeadAvatarUrl` survives on purpose: it is the live store behind the Settings avatar picker, the sidebar logo, and the in-reply `<agent-3d>` viewer.@@ -29,13 +29,13 @@ modules. Routes resolved via `vercel.json` rewrites.### 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.+- **Prerequisites / gates:** None to view. Editing (`/agents/:id/edit` → `agent-edit.html`; the older `/agent/:id/…` subroutes still resolve but every link now uses the canonical `/agents/:id/…` form) 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: a live Three.js hero avatar (`mountIdleAvatar` retargets the canonical idle clip onto the rig with a procedural idle-life loop; no static `<model-viewer>`), identity, voice metadata (cloned provider or browser TTS pill), live $THREE/pump token chip (streamed via `/api/pump/by-agent`), skills (with dynamic price/promo state from `/api/marketplace/skill-promo?agent_id=…&skill=…`), 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.+- **Decision points / branches:** view vs edit (owner); "See in world" (→ /play) vs embed (`/agents/:id/embed`) vs wallet (`/agents/:id/wallet`); token chip present (launched coin) vs not; a `/agents/:id?skill=<name>#pricing` deep link (what the Buy CTA on `/conversions` sends) scrolls the pricing card to that skill row once it renders (`focusRequestedSkill` in `agent-detail-market.js`, honoured once per page load).- **External calls / dependencies:** `/api/agents/:id`, `/api/marketplace/agents/:id`, `/api/pump/by-agent` (live market-cap stream), `/api/marketplace/skill-promo` (skill pricing/promo), `/api/agent-share` (share). Three.js idle-avatar mount for the 3D preview (falls back to a flat image when WebGL/GLB fails).- **Success state:** Agent profile with interactive 3D avatar, live token data, and working navigation to world/embed/edit.- **Empty / error states:** Avatar mount failure → flat-image fallback; enrich failure logged non-fatally; save errors surface inline in the edit flow.@@ -47,18 +47,18 @@ modules. Routes resolved via `vercel.json` rewrites.### 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 "Pick a vibe", sub-copy "One tap gives your agent a personality. No extra steps."; "Build Persona" is a sidebar button), two tabs: Persona + Playground.-- **Prerequisites / gates:** None to open the playground, but signed-out callers are limited to the free-model set (`ANON_BRAIN_PROVIDERS` in `api/brain/chat.js`: gpt-oss-120b plus the NVIDIA NIM family); every paid first-party model returns `401 "sign in to use this model"`, and anonymous traffic is rate limited. 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.+- **Prerequisites / gates:** None to open the playground, but signed-out callers are limited to the free-model set (`ANON_BRAIN_PROVIDERS` in `api/brain/chat.js`: gpt-oss-120b plus the NVIDIA NIM family); every paid first-party model returns `401 "sign in to use this model"`, and anonymous traffic is rate limited. `GET /api/brain/chat` reports `requiresAuth` per model alongside `available`, so the page suffixes those chips "(sign in)" for a signed-out visitor and answers a click with the notice "<model> needs an account." plus a Sign in link (`/login?redirect=/brain`) instead of failing after Send. Freeform persona extraction (`POST /api/persona/extract`) also requires sign-in (`401 "Sign in to build your persona."`; the Persona tab shows a "Sign in to build your persona" gate that clears once you sign in and return) and is metered at 5 extractions per user per day. Saving a persona as a deployed agent requires sign-in (auth-hint check + `/api/agents` with credentials). 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.+ 2. (optional) Apply an archetype preset or type freeform persona text → `/api/persona/extract` structures it into a persona object (tone, vocabulary, interests, communication_style, dont_say, sample_greeting); the body is validated before the daily limiter is charged, and an empty model reply comes back as a retryable `502` rather than a blank card.+ 3. Switch to the Playground tab; provider availability fetched from `GET /api/brain/chat` (each model carries `available` and `requiresAuth`), 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 (via Google Vertex), OpenAI (via OpenRouter), xAI Grok, DeepSeek, Qwen/DashScope, IBM watsonx, NVIDIA NIM, and Google Vertex Gemini 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; signed-out use of a paid model errors with a sign-in prompt; auth gate shown when saving while signed out; sessions/persona persisted to localStorage.+- **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, and when every rung of a model's fallback chain fails the column shows a plain-language verdict (rate limited: try again or pick another model; no working route on this deployment; no longer served upstream; took too long) with the precise upstream reason alongside as `reason`; signed-out use of a paid model errors with a sign-in prompt; auth gate shown when saving while signed out; sessions/persona persisted to localStorage.- **Step count:** 6 required (+2 optional)---@@ -120,7 +120,7 @@ modules. Routes resolved via `vercel.json` rewrites.### 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.+- **Prerequisites / gates:** None client-side (no auth, wallet, mic, or $THREE). Requires WebGL; TTS is served by `/api/tts/speak`, which tries the free NVIDIA NIM Magpie lane first and falls back to OpenAI.- **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.@@ -129,7 +129,7 @@ modules. Routes resolved via `vercel.json` rewrites.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.+- **External calls / dependencies:** `POST /api/tts/speak` (lane 1 NVIDIA NIM Magpie, free, 30s budget; lane 2 OpenAI `/v1/audio/speech`, the paid backstop with its own 20s budget; `503 not_configured` when neither key is set), `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)@@ -164,11 +164,11 @@ modules. Routes resolved via `vercel.json` rewrites.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.+ 5. Door reveals the x402 cover screen; connect wallet and pay the cover → a paid `GET /api/x402/club-cover` (x402, `club-gate.js`) 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.+- **External calls / dependencies:** `GET /api/x402/club-cover` (the door; a `POST` to the same path is a separate paid read for agents, `mode: "snapshot"` for membership growth/churn or `mode: "revenue"` for the door + floor take over a `period` of 24h/7d/14d/30d/all, not part of the visitor flow), `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)diff --git a/docs/ux-flows/11-account-dashboard.md b/docs/ux-flows/11-account-dashboard.mdindex e50f381d3..ec49bab9c 100644--- a/docs/ux-flows/11-account-dashboard.md+++ b/docs/ux-flows/11-account-dashboard.md@@ -28,7 +28,7 @@ Shared auth concepts:---### 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).+- **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; it also imports `solana-mobile/src/index.js`, which boots the Seed Vault / Mobile Wallet Adapter wallet inside the Seeker Android app and is a no-op everywhere else), `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):**@@ -41,7 +41,7 @@ Shared auth concepts:7. `POST /api/auth/login` with `{ email, password, remember, tosAccepted: true }` (notice-style clickwrap; the legal line sits under the form), 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.+ 10. **(optional) Privy email-OTP path:** type email in `#privy-email-input` → click **Send code**. The Privy app's CAPTCHA config is read first (`src/auth/privy-captcha.js`, 6 s timeout): when one is required a Cloudflare Turnstile challenge resolves before the request, and when the config cannot be read the step stops with "We could not reach the sign-in service to check whether this step needs a CAPTCHA…" rather than sending a token-less request that Privy would reject as `invalid_credentials`. `privy.auth.email.sendCode()` sends the code; UI advances to the code step. The same check runs before the Privy EVM wallet path.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.@@ -50,7 +50,7 @@ Shared auth concepts:- **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.+- **Empty / error states:** Per-field inline errors with shake + avatar facepalm; transport-failure banner on the session probe; if `GET /api/config` fails or times out (6 s), the Privy email and wallet sections hide behind an inline "Email and wallet sign-in could not load…" notice while the password form stays usable; every Privy and SIWS network call is bounded (10 to 20 s) and a transport failure reads as "Could not reach the sign-in service"; 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)---@@ -157,7 +157,7 @@ Shared auth concepts: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" → `DELETE /api/auth/sessions` (revokes every other session **and rotates the current session cookie**) → toast.6. **(optional) Notifications:** "Mark all read" → `POST /api/notifications/read-all` → toast. The inbox covers the full bell vocabulary (sales, purchases, follows, remixes, DMs, coin-launch graduations, IRL, market, account).- 6b. **(optional) Notification preferences:** a category × channel matrix driven by the server response (`categories` + `channels`, default channels in-app / push / email / Telegram). Toggles flip locally; a single **Save notification preferences** button sends the whole matrix via `PUT /api/notifications/preferences` `{ categories }` → toast "Notification preferences saved". Per-category `lockedChannels` render disabled (in-app is typically locked on); the Telegram column stays disabled ("Link a Telegram chat id to enable") until `telegram_chat_id` is set; a footer reports subscribed push devices.+ 6b. **(optional) Notification preferences:** a category × channel matrix driven by the server response (`categories` + `channels`, default channels in-app / push / email / Telegram / avatar). The **Avatar** column routes a category to the corner companion, which walks on screen and says the message out loud while the user is on the site; a hint line under the table explains it, and it can be muted per browser from the bubble's "Turn off" control. The response also carries `type_categories` (notification type → category), so the client-side herald (`src/notification-herald.js`) gates the avatar channel with the same mapping the server uses for push and email. Toggles flip locally; a single **Save notification preferences** button sends the whole matrix via `PUT /api/notifications/preferences` `{ categories }` → toast "Notification preferences saved". Per-category `lockedChannels` render disabled (in-app is typically locked on); the Telegram column stays disabled ("Link a Telegram chat id to enable") until `telegram_chat_id` is set; a footer reports subscribed push devices.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".@@ -186,7 +186,7 @@ Shared auth concepts:- **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.-- **Fixed 2026-08-06 (was: two broken writes):** the page ran on a local `fetch` helper that attached no `x-csrf-token`, so profile **Save changes** and both session revokes were rejected in production with `403 csrf_missing` while the UI still reported success; and the Danger Zone called a `DELETE /api/auth/me` the server did not implement (`me` was GET-only), so deletion always ended in the "contact support" alert. Every call on the page now goes through the shared CSRF-carrying client (`src/api.js`), a non-ok response surfaces as an error instead of a false success, and `DELETE /api/auth/me` is implemented (see [authentication.md](../authentication.md#deleting-the-account)).+- **Fixed 2026-08-06 (was: two broken writes):** the page ran on a local `fetch` helper that attached no `x-csrf-token`, so profile **Save changes** and both session revokes were rejected in production with `403 csrf_missing` while the UI still reported success; and the Danger Zone called a `DELETE /api/auth/me` the server did not implement (`me` was GET-only), so deletion always ended in the "contact support" alert. Every call on the page now goes through the shared CSRF-carrying client (`src/api.js`, which also bounds every call: 20 s for reads, 90 s for mutations, `timeoutMs` to override), a non-ok response surfaces as an error instead of a false success, and `DELETE /api/auth/me` is implemented (see [authentication.md](../authentication.md#deleting-the-account)).- **Step count:** 3 required (boot + profile load + save profile) (+5 optional tab flows)---diff --git a/docs/ux-flows/12-home-and-content.md b/docs/ux-flows/12-home-and-content.mdindex 95bd6a73e..28f8b6f2b 100644--- a/docs/ux-flows/12-home-and-content.md+++ b/docs/ux-flows/12-home-and-content.md@@ -17,8 +17,8 @@ viewers), all confirmed against source.- 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 type="module" src="https://three.ws/agent-3d/latest/agent-3d.js">` (near the top of `<head>`) + `/model-viewer-meshopt.js` (no `/embed.js` on this page)- Chrome: `/nav.js` + `/seasonal.js`; the footer is hardcoded inline in `home.html` (no `/footer.js` here)-- **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. **Progressive disclosure:** first-time visitors get the "lite" page (`tws-lite` class unless `localStorage['tws:tier'] === 'full'`); nine advanced sections are tagged `data-tier="advanced"` and hidden behind an "advanced platform" gate section (`#advanced-gate`) that links each of them (sniper, capabilities, token economy, live economy, oracle, x402, dev platform, stack).+- **Entry point:** Root route. No auth. The hero `<agent-3d>` and the capability/press strips render immediately (the capability strip is decorative: `aria-hidden` and unreachable by keyboard); 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. **Progressive disclosure:** first-time visitors get the "lite" page (`tws-lite` class unless `localStorage['tws:tier'] === 'full'`); eight advanced sections (plus the hero "Earn" bullet) are tagged `data-tier="advanced"` and hidden behind an "advanced platform" gate section (`#advanced-gate`) that links each of them (sniper, capabilities, token economy, live economy, oracle, x402, dev platform, stack).- **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 (the third, "Earn USDC per chat", is advanced-tier), a live `<agent-3d>` on stage, and the eyebrow link "New · Text → 3D is live…" → `/forge`.2. (Optional) Forge from the hero: `#hero-forge-form` is a live text-to-3D input ("describe anything…" + **"Forge it"** button + three Try chips: low-poly fox / sci-fi helmet / ceramic teapot) that types straight into the mini-Forge, which now sits directly under the hero. An "Open the full Forge →" note links `/forge`. A `<lang-switcher>` sits under the CTA row.@@ -33,7 +33,7 @@ viewers), all confirmed against source.- Three Doors: "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`.- - Autonomous trading (`#home-sniper`, via `src/home-sniper.js`): "Watch the arena →" → `/arena`; "Arm a strategy" → `/oracle/arm`.+ - Autonomous trading (`#home-sniper`, via `src/home-sniper.js`): "Watch the arena →" → `/arena`; "Arm a strategy" → `/oracle/arm`. The engine pill is honest about solvency: a `starved` engine (no wallet can fund a trade) reads "Engine out of SOL" in the down style, and a degraded fleet shows "N/M wallets funded".- 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`; "Open this model in AR →" → `/forge`; "Browse the avatar gallery →" → `/gallery`; "AR feature overview →" → `/features/ar`; "How AR works →" → `/blog/see-your-3d-in-ar`.@@ -43,7 +43,7 @@ viewers), all confirmed against source.- Oracle: "Open Oracle →" / "View all conviction scores →" → `/oracle`; coin cards deep-link `/oracle/coin/<mint>`.- Pay-per-call: "Configure monetization →" → `/dashboard/monetize`.- Walk: "See walk mode →" → `/temporary` (the `/walk` route still exists but home points at `/temporary`).- - Developer platform: "Get a key ↗"/"Get API key →" → `/dashboard/api`; "Docs" → `/docs`; "GitHub" → github.com/nirholas/three.ws; "OpenAPI" → `/api/openapi-json.js` (currently a dead link; only `/openapi.json` is routed); "MCP server" → `/docs/mcp`.+ - Developer platform: "Get a key ↗"/"Get API key →" → `/dashboard/api`; "Docs" → `/docs`; "GitHub" → github.com/nirholas/three.ws; "OpenAPI" → `/openapi.json` (the routed spec; the handler is `api/openapi-json.js`); "MCP server" → `/docs/mcp`.- The Stack: Studio → `/studio`; Registry → `/discover`; Embed → `/docs`; Pay-per-call → `/dashboard/monetize`; Walk → `/temporary`; SDK → `/docs/sdk`.- Showcase 3D: "Browse all" → `/discover`; "Make your own" → `/create`.- Avatar Drop & Vclose: "Build your agent →" → `/create`; "Text → 3D" → `/forge`; "Read the docs" → `/docs`.@@ -55,9 +55,9 @@ viewers), all confirmed against source.- **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 (fed by a top-sorted `/api/forge-gallery` fetch).- **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 ("Oracle is warming up…" empty state; error state renders an "Open Oracle →" button).- - **Community Forge gallery**: a live, sortable browse loop over `GET /api/forge-gallery?scope=community&…limit=24`: Fresh/Trending tabs (`sort=fresh` vs `sort=top&window=week`), a 25s background refresh that prepends genuinely-new models on Fresh (with a live chip), prompt-based dedupe, and a "Show more" button (12 shown initially, up to 24).- - **Showcase 3D grid**: `GET /api/explore?source=avatar&only3d=1&category=avatar,creature&limit=24&quality=high` (via `src/home-live-agents.js`), agent cards + CTA cards.+ - **Oracle feed**: `GET /api/oracle/feed?network=mainnet&limit=6&min_score=56`, renders top conviction coins ("Oracle is warming up…" empty state; error state renders an "Open Oracle →" button). During a database outage the endpoint answers `503` with `Retry-After` instead of a confident empty feed, so the section shows the error state rather than a dead market presented as fact.+ - **Community Forge gallery**: a live, sortable browse loop over `GET /api/forge-gallery?scope=community&…limit=24`: Fresh/Trending tabs (`sort=fresh` vs `sort=top&window=week`), a 25s background refresh that prepends genuinely-new models on Fresh (with a live chip), prompt-based dedupe, and a "Show more" button (12 shown initially, up to 24). Cards paint as poster images and upgrade to the live rotating mesh only as they near the viewport; community cards stay as posters.+ - **Showcase 3D grid**: `GET /api/explore?source=avatar&only3d=1&category=avatar,creature&limit=24&quality=high` (via `src/home-live-agents.js`), agent cards + CTA cards; each card links the item's `detailUrl` (the canonical `/avatars/<id>` detail page with chat, skills, embed and launch actions), not the bare GLB viewer.- **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` (+ `?catalog`/`?health` for the options panel), `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).@@ -88,7 +88,7 @@ viewers), all confirmed against source.- **Source:** `pages/status.html` (dynamic).- **Entry point:** `vercel.json` `/status → /status.html`.- **Prerequisites / gates:** None.-- **Steps (4):** 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. 4) Read the live build stamp: a `GET /api/version` fetch fills `#st-build` with the live commit (linked to GitHub), version, Cloud Run revision, and build time; it stays hidden if the endpoint is unreachable. Footer links to the SVG status badge (`/api/status?format=svg`) and `/changelog`.+- **Steps (4):** 1) On load, fetch `GET /api/status` and render service cards (status dot, uptime %, avg latency, 90-day history bar); a subsystem that publishes structured `metrics` (today the agent index) also renders metric pills beside its sentence: Solana lag, Solana agents, EVM lag, Events indexed (`subMetrics`). 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. 4) Read the live build stamp: a `GET /api/version` fetch fills `#st-build` with the live commit (linked to GitHub), version, Cloud Run revision, and build time; it stays hidden if the endpoint is unreachable. A "Last check …" stamp (`#st-checked`) sits beside the cadence sentence. Footer links to the SVG status badge (`/api/status?format=svg`) and `/changelog`.- **External calls:** `GET /api/status`, `GET /api/version`.- **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.@@ -103,13 +103,13 @@ viewers), all confirmed against source.### 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).+- **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 in a new tab: GitHub Issues for bugs and feature requests, or "Questions & help", which opens a question issue template (`issues/new?template=question.yml`) in the same tracker; Discussions is no longer a channel. 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) The countdown block reflects event phase (event was 2026-06-23 18:00 MT, 60 min, online; rAF tick → days/hrs/min/sec pre-event; "LIVE NOW" during; since EVENT_END passed it now renders the post-event headline "Thanks for joining" with the sub-label "replay coming soon"; no replay link exists yet). 2) Add to calendar (`#add-cal`/`#add-cal-2` build a Google Calendar render URL from EVENT_START/END, now a past date). 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.+- **Steps (5):** 1) The countdown block reflects event phase (event was 2026-06-23 18:00 MT, 60 min, online; rAF tick → days/hrs/min/sec pre-event; "LIVE NOW" during; since EVENT_END passed it now renders the post-event headline "Thanks for joining" with the sub-label "this session has aired"; no replay link exists). Past-event mode also swaps the eyebrow to "Past event · hosted by three.ws" and strips the upcoming-event i18n hooks so the translation pass cannot paint the old copy back. 2) Add to calendar (`#add-cal`/`#add-cal-2` build a Google Calendar render URL from EVENT_START/END, re-applied on every `i18n:change`); both calendar controls are hidden once the event has passed, since adding a past event is a dead path. 3) RSVP email signup (`#rsvp-form`, `data-newsletter-form` → `POST /api/newsletter/subscribe`, aria-live result); after the event the section reads "Next session" / "Hear about the next live build" and asks for an email for the next scheduled session. 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 hub and policy documents - `/legal`, `/legal/privacy`, `/legal/tos`, `/legal/eula`, `/legal/content-policy`, `/legal/risk`@@ -141,21 +141,21 @@ viewers), all confirmed against source.- **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); `figure:` directives in the markdown resolve to real captured images via `/tutorial-figures.js` + `/tutorial-figures.css` (pipeline shared with the cookbook recipe viewer). 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.+- **Empty / error states:** "Tutorial not found" on an unknown slug or 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: the sidebar NAV is loaded from `GET /docs/nav.json` (currently 14 sections / ~273 links, with a designed failure state if the manifest 404s) + `start-here.md` fetched & rendered. 2) Sidebar **search** live-filters the nav by label AND surfaces a full-text results panel fed by the docs search index (with a Clear search control). 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; a lazy doc-freshness banner (`/doc-freshness.js`, backed by `public/docs-freshness*.json`).+- **Steps (4):** 1) Land: the sidebar NAV is loaded from `GET /docs/nav.json` (currently 14 sections / ~286 links, with a designed failure state if the manifest 404s) + `start-here.md` fetched & rendered. 2) Sidebar **search** live-filters the nav by label AND surfaces a full-text results panel fed by the docs search index (with a Clear search control). 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; a lazy doc-freshness banner (`/doc-freshness.js`, backed by `public/docs-freshness*.json`).- **External calls:** `GET /docs/nav.json`; `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; a designed nav-manifest failure state.- **Notes:** Nearly all `/docs/*` slugs 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). **Exceptions mapped before the generic rule:** `/docs/widgets` (standalone page, below), `/docs/3d-api` → `/3d.html`, `/docs/agent-3d` → 308 → `/docs/web-component`, and the `/docs/walk*` family.### 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`).+- **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). The former footer `<model-viewer>` demo is gone; the page loads the model-viewer runtime but renders no demo of its own.- **Notes:** Pure static docs, no API. Distinct from the docs SPA.### Blog index — `/blog`@@ -163,15 +163,15 @@ viewers), all confirmed against source.- **Entry point:** `/blog`.- **Prerequisites / gates:** None.- **Steps (2):** 1) Scan the hardcoded list of 35 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:** 35 indexed posts → individual article routes (37 post files exist; two are routable but unlinked from the index); RSS / social out.+- **Decision points / branches:** 35 indexed posts → individual article routes (38 post files exist; three are routable but unlinked from the index); 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 (37): `/blog/<slug>`-- **Source:** `blog/<slug>.html`: 37 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`. One legacy slug redirects: `/blog/all-90-trades` 308s to `/blog/autonomous-trading-experiment`.-- **Slugs:** the routable set is exactly the `blog/*.html` filenames (37 today; enumerate with `ls blog/*.html`), which rots less than restating the list here. (`three-ws-alibaba-cloud-partnership` and `three-ws-play-coin-communities` are routable but not linked from the index.)+### Blog posts (38): `/blog/<slug>`+- **Source:** `blog/<slug>.html`: 38 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`. One legacy slug redirects: `/blog/all-90-trades` 308s to `/blog/autonomous-trading-experiment`.+- **Slugs:** the routable set is exactly the `blog/*.html` filenames (38 today; enumerate with `ls blog/*.html`), which rots less than restating the list here. (`three-ws-alibaba-cloud-partnership`, `three-ws-play-coin-communities` and `ibm-user-group-first-in-world-meetup-recap` are routable but not linked from the index.)- **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:** Several `.md` files under `blog/` (drafts and source material such as `decision-optimization-3d-ai-crypto.md`, `internets-second-species.md`, `we-are-the-provider.md`, the autonomous-trading X drafts, plus `README.md`) are NOT routed (no rule maps `.md` blog slugs) and are not in the index; source material only, not live pages.@@ -188,9 +188,9 @@ viewers), all confirmed against source.- **Notes:** The header carries the subscribe row (`/changelog.xml` RSS, `/changelog.json`, `/llms.txt`, `/sitemap`). Delivery to the holders' Telegram channel is handled by the `changelog-push` cron off the same feed, not by this page.### News index and articles - `/news`, `/news/<slug>`-- **Source:** `public/news/index.html` plus 110 static article files `public/news/<slug>.html`.+- **Source:** `public/news/index.html` plus 112 static article files `public/news/<slug>.html`.- **Entry point:** `vercel.json` `/news → /news/index.html`, `/news/([a-z0-9_-]+)/? → /news/$1.html`. The home page's press strip links straight into individual `/news/*` slugs, so most arrivals skip the index.-- **Steps (2):** 1) Scan the index: 110 hardcoded `post-link` cards, newest first, each with a `<time>` date, headline, summary paragraph, and a display-only tag list. 2) Click through to an article and read it; a "News" breadcrumb returns to the index, and inline links point at product routes.+- **Steps (2):** 1) Scan the index: 112 hardcoded `post-link` cards, newest first, each with a `<time>` date, headline, summary paragraph, and a display-only tag list. 2) Click through to an article and read it; a "News" breadcrumb returns to the index, and inline links point at product routes.- **External calls:** None. Fully static: no fetch, no pagination, no search, and the tags are not filterable.- **Success state:** User reads the announcement and follows its product link.- **Empty / error states:** N/A (static).@@ -223,7 +223,9 @@ Agent/crawler endpoints — not user UX (0 user steps). All resolve via `vercel.| 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 || OAuth protected resource | `/.well-known/oauth-protected-resource` (also under `/api/mcp/`) | `/api/wk?name=oauth-protected-resource` | OAuth 2.0 Protected Resource metadata |-| Chat plugin manifest | `/.well-known/chat-plugin.json` | `/api/wk?name=chat-plugin` | AI chat-plugin manifest |+| Chat plugin manifest | `/.well-known/chat-plugin.json` | `/api/wk?name=chat-plugin` | AI chat-plugin manifest (the real LobeChat manifest) |+| Sperax plugin manifest | `/.well-known/sperax-plugin.json` | `/api/wk?name=sperax-plugin` | Sperax plugin manifest |+| Apple app-site association | `/.well-known/apple-app-site-association` | `/api/wk?name=apple-app-site-association` | iOS universal-link association for the App Store shell || Vanity metadata | `/.well-known/three-vanity.json` | `/api/wk?name=three-vanity` | Vanity-wallet discovery metadata || JWKS | `/.well-known/jwks.json` | `/api/auth/persona/[action]?action=jwks` | Signing keys || DID document | `/.well-known/did.json` | `/api/x402/did` | x402 DID document |diff --git a/docs/vaults.md b/docs/vaults.mdindex d877a5e48..abb4de8be 100644--- a/docs/vaults.md+++ b/docs/vaults.md@@ -73,7 +73,7 @@ curl -sX POST https://three.ws/api/vaults \`201` returns the vault row including `vault_address`. Note the address: the vault also needs a little **SOL** to pay swap fees and open token accounts, and there is no vault-funding endpoint. Send roughly 0.01 SOL to `vault_address` yourself, for example from your master wallet (see [user-wallet.md](user-wallet.md)). Without it, trades are refused with `insufficient_sol_for_fees` before anything is signed.-The browser flow is the "Open a vault" modal on [/vaults](https://three.ws/vaults), which is only shown to a signed-in user and pre-fills the same defaults.+The browser flow is the "Open a vault" modal on [/vaults](https://three.ws/vaults), which is only shown to a signed-in user and pre-fills the same defaults. A signed-in user with no agents gets a disabled form pointing at [/create](https://three.ws/create) instead of a submit that can only fail.## How the money is priceddiff --git a/docs/voice-lab.md b/docs/voice-lab.mdindex e8b64f468..e7c7ad86f 100644--- a/docs/voice-lab.md+++ b/docs/voice-lab.md@@ -24,7 +24,7 @@ An agent that speaks in a generic stock voice is a demo. An agent that speaks in| OpenAI | 11 | Credits | `gpt-4o-mini-tts` also takes a direction. || ElevenLabs | your account + the public library | Credits or BYOK | The only lane that can clone your voice. |-The `providers` array from `GET /api/tts/catalog` is the source of truth: it reports, per lane, whether this deployment can actually serve it and why not when it cannot, which models it offers, and whether it accepts a direction. The picker renders unavailable lanes with their reason rather than hiding them.+The `providers` array from `GET /api/tts/catalog` is the source of truth: it reports, per lane, whether this deployment can actually serve it and why not when it cannot, which models it offers, and whether it accepts a direction. The picker renders unavailable lanes with their reason rather than hiding them: the lane pill stays fully legible (a greyed billing badge and a not-allowed cursor carry the state, never a faded label) and its `aria-label` reads the lane name plus the reason, so a screen reader hears what to do about it.### The ElevenLabs Voice Library@@ -96,7 +96,7 @@ curl -X POST 'https://three.ws/api/tts/eleven' \--output hello.mp3```-Note that agent-assigned voices always run on the platform account (the agent speaks server-side, where your browser key is not present), so a voice you want an agent to use must be cloned on the platform rungs, not under BYOK.+Agent-assigned voices have their own rung. When an agent's voice was bound with the owner's saved ElevenLabs key (`agent_identities.voice_key_source = 'owner'`, set by `PUT /api/agents/:id/voice`), `/api/tts/eleven` with that `agentId` serves the clip on the owner's account (`x-tts-billing: agent_byok`), including to signed-out visitors on the chat and embed surfaces, rate-limited per IP; the requested `voiceId` must be the agent's own bound voice, so the credential can never be borrowed to synthesize anything else. An agent bound on the platform key speaks on the `credits` rung instead, and the agent lane falls back to that cleanly when the owner's key is absent. Your browser-side `x-eleven-key` is never involved in agent speech, so a voice an agent should use must be cloned either on the platform rungs or with the key you have saved to your account, not with a key that only lives in `localStorage`.## Walkthrough@@ -152,7 +152,7 @@ The agent-voice handler ([`api/agents/_id/voice.js`](../api/agents/_id/voice.js)- **"Add to an agent" on `/voice`** links to the dashboard; the actual assignment happens in the agent editor. The cloned `voice_id` lives in browser `localStorage` until you assign it.- **Error copy.** Mic denial, recorder failure, too-short recording, missing name, network failure, and clone failure each map to a specific message; the playground shows "Synthesizing...", then a size, a cached/generated tag, and the billing rung that served it, or an error. A lane's upstream failure is tagged with a code (`invalid_key`, `rate_limited`, `content_blocked`, `provider_unreachable`) that `/api/tts/synthesize` maps to a truthful HTTP status rather than a blanket 502. The message the picker renders is a written sentence, never the vendor's raw body: that ships alongside it in `detail` for debugging.- **A lane that goes down leaves the menu.** Configuration presence is not health, so what the last real synthesis learned decides what the catalog offers. A lane the provider refuses (expired key, billing hold upstream) is reported `available: false` with the reason for a few minutes, its voices drop out of the picker, and a synthesis aimed at it answers `503 lane_unavailable` with `retry_with: ["edge", "nvidia"]` rather than failing slowly again. The Voice Lab re-reads the catalog the moment a preview hits that 503, so the grid stops offering voices nobody can render while the explanation stays on screen. The window expires on its own and any successful call clears it, so recovery needs no deploy. Your own `x-eleven-key` is never gated by the platform key's outage.-- **Catalog freshness.** The Edge catalog is fetched live from Microsoft and cached 6 hours per instance; the ElevenLabs account catalog 5 minutes. Nothing is a hardcoded snapshot, so a voice Microsoft or ElevenLabs adds shows up on its own.+- **Catalog freshness.** The Edge catalog is fetched live from Microsoft and cached 6 hours per instance; the ElevenLabs account catalog 5 minutes. Nothing is a hardcoded snapshot, so a voice Microsoft or ElevenLabs adds shows up on its own. The ElevenLabs voice-list and voice-delete calls go through the shared `fetchUpstream` with a 10 s deadline and two attempts, so a slow upstream degrades the lane to empty-with-a-reason instead of holding the catalog request open.## Relateddiff --git a/docs/world-lines.md b/docs/world-lines.mdindex 2959622d5..20c3c8212 100644--- a/docs/world-lines.md+++ b/docs/world-lines.md@@ -2,7 +2,7 @@A **World Line** is a quest an agent leaves at a real place. Someone walks to that spot, completes the agent's challenge in a live ceremony panel (a tap, a passphrase, or a quiz), and the agent's own wallet signs an ed25519 **proof of presence**: a tamper-evident receipt that says *this visitor was in this area and did this thing*. The proof is independently verifiable by anyone, ownable by the visitor, and it never carries a coordinate finer than a roughly 1 km cell.-Live at `three.ws/world-lines`. Four tabs: **Near me** (fix-gated quests within walking range), **Explore** (coordinate-free region roll-up), **My proofs** (your earned collectibles, each re-verifiable in place), and **Create** (place a quest on a pin you own, plus the completion dashboard).+Live at `three.ws/world-lines`. Four tabs: **Near me** (fix-gated quests within walking range), **Explore** (coordinate-free region roll-up), **My proofs** (your earned collectibles, each re-verifiable in place), and **Create** (place a quest on a pin you own, plus the completion dashboard). The active tab is mirrored into the URL hash (`#near`, `#explore`, `#collectibles`, `#create`), so a tab is linkable and the back button walks tabs; Left/Right/Home/End move between them from the keyboard.This document is the deep reference. For where World Lines sits inside the wider IRL product (placing agents, discovering by walking up, Money Drops, the presence privacy contract), read the short version first: [IRL: agents in the real world](./irl.md#world-lines). The REST summary lives in the [API reference](./api-reference.md); everything below is the full contract, the anti-cheat reasoning, and the exact privacy posture as coded.@@ -95,7 +95,7 @@ The collectible's display name is `reward_ref` when you set one, otherwise it isWhat the visitor sees, and what the server checks under each step. The ceremony state machine is [src/irl/world-line-ar.js](../src/irl/world-line-ar.js); every state below is a rendered state, including the failure ones (speaking, awaiting the interaction, submitting, granted, already completed, capacity reached, no longer active, and error).-The ceremony runs as a designed in-page panel on every device, with the agent's avatar rendered live and breathing in the card. The module also carries a self-contained immersive WebXR layer (`enterAR()`, floor hit-test, avatar anchored to the detected surface), which no current UI path activates: the ceremony renders no AR button, so the panel is what visitors get today on every browser. Nothing about the proof depends on which of the two is used, because the client owns no secrets and the server enforces co-location, the nonce, the signature, the caps, and idempotency regardless.+The ceremony runs as a designed in-page panel on every device, with the agent's avatar rendered live and breathing in the card. The module also carries a self-contained immersive WebXR layer (`enterAR()`, floor hit-test, avatar anchored to the detected surface). On a browser that reports `immersive-ar` support the intro panel grows a "Meet the agent in AR" button that starts it; everywhere else no button renders and the panel is what visitors get, and an AR session that fails to start falls back to the panel's begin step. Nothing about the proof depends on which of the two is used, because the client owns no secrets and the server enforces co-location, the nonce, the signature, the caps, and idempotency regardless.**1. Discover.** The page watches geolocation, mints a fix token, and calls `GET /nearby`. Each quest card shows a distance chip coarsened to 10 m, the difficulty, the reward, and whether you already hold its proof. Under 80 m the button becomes "You're here, begin"; further away it reads "Travel here to begin".diff --git a/docs/x-posts/android-app-launch.md b/docs/x-posts/android-app-launch.mdindex 1d855ae10..36ebf0bbd 100644--- a/docs/x-posts/android-app-launch.md+++ b/docs/x-posts/android-app-launch.md@@ -51,9 +51,12 @@ What the app adds over the website:## The four images-The artwork and the X copy live in [`../../marketing/android-launch/`](../../marketing/android-launch/), generated by `npm run build:x-grid`. One composition is drawn at 4096x2304 and quartered, so X's 2x2 collage reassembles into the picture that was drawn: every quadrant of a 16:9 rectangle is itself 16:9, which is the aspect of the cell it lands in, so nothing is cropped.+The artwork and the X copy live in [`../../marketing/android-launch/`](../../marketing/android-launch/). X changed its four-image layout on 2026-08-28 from a 2x2 collage to a swipe carousel that shows one image at a time in a cell of about 1.18:1, center-cropped, so there are two renders of the same scene:-**Attach the tiles in the order in [`kit/IMAGE-ORDER.md`](../../marketing/android-launch/kit/IMAGE-ORDER.md).** X fills the grid in attachment order, and any other order scrambles the composition. Per-image alt text and the follow-up replies are in [`kit/post.md`](../../marketing/android-launch/kit/post.md).+- **The strip (current).** `npm run build:x-strip` draws one 4800x1020 scene and cuts it into four 1200x1020 tiles in `kit/strip/`, the cell's own shape, so nothing is cropped and swiping reads as one continuous picture.+- **The grid (kept in case X brings the collage back).** `npm run build:x-grid` draws one 4096x2304 composition and quarters it into `kit/images/`: every quadrant of a 16:9 rectangle is itself 16:9, so a 2x2 collage reassembles into the picture that was drawn. The headline is set as two halves that meet at the vertical seam with a word space at the cut, every phone sits wholly inside one tile, and the render refuses to write tiles whose outer border or seams are brighter than X's black timeline allows. The uncut master also becomes `kit/cmc-cover-640x360.png`, the CoinMarketCap article cover.++**Attach the tiles in the order in [`kit/IMAGE-ORDER.md`](../../marketing/android-launch/kit/IMAGE-ORDER.md).** X lays the images out in attachment order, and any other order scrambles the scene. The full thread, per-image alt text, and the follow-up replies are in [`kit/post.md`](../../marketing/android-launch/kit/post.md).## X (@trythreews), held until the account is restoreddiff --git a/docs/x402-endpoints.md b/docs/x402-endpoints.mdindex 64f171e4d..21f0fe62e 100644--- a/docs/x402-endpoints.md+++ b/docs/x402-endpoints.md@@ -100,11 +100,11 @@ buyer's USDC settles **directly** to that wallet and the platform never holds it| Endpoint | Receiver | Source || -------- | -------- | ------ |-| `/api/x402/skill-call` | skill **author** | `author_payto_*` ([skill-call.js:196](../api/x402/skill-call.js#L196)) |+| `/api/x402/skill-call` | skill **author** | `author_payto_*` ([skill-call.js:205](../api/x402/skill-call.js#L205)) || `/api/x402/service` | service **provider** | `row.payout_address` ([service.js:91](../api/x402/service.js#L91)) || `/api/x402/asset-download` | 3D-asset **creator** | `creator_payto_*` ([asset-download.js:124](../api/x402/asset-download.js#L124)) || `/api/x402/animation-download` | clip **creator** | `creator_payto_*` ([animation-download.js:115](../api/x402/animation-download.js#L115)) |-| `/api/x402/pay-by-name` | **buyer-named** wallet | resolved name/`.sol`/address, direct SPL transfer ([pay-by-name.js:279](../api/x402/pay-by-name.js#L279)) |+| `/api/x402/pay-by-name` | **buyer-named** wallet | resolved name/`.sol`/address, direct SPL transfer ([pay-by-name.js:280](../api/x402/pay-by-name.js#L280)) |**2. Post-settlement split** — the USDC lands in the **platform receiver**, then a*separate* treasury forwards a share out-of-band (these are NOT `payTo` overrides):@@ -112,7 +112,7 @@ buyer's USDC settles **directly** to that wallet and the platform never holds it| Endpoint | Lands in | Then forwarded to | By || -------- | -------- | ----------------- | -- || `/api/x402/cosmetic-purchase` | platform receiver | **creator** 50% (≤90% cap) | `COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64` ([cosmetics-economy.js:203](../api/_lib/cosmetics-economy.js#L203); the 50% default and 90% ceiling are [L31-L32](../api/_lib/cosmetics-economy.js#L31)) |-| `/api/x402/dance-tip` | platform receiver | **dancer** (full tip) | `club-payouts` cron ([club/sweep.js](../api/_lib/club/sweep.js)) paying from `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` ([club/payouts.js:54](../api/_lib/club/payouts.js#L54)) |+| `/api/x402/dance-tip` | platform receiver | **dancer** (full tip) | `club-payouts` cron ([club/sweep.js](../api/_lib/club/sweep.js)) paying from `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` ([club/payouts.js:55](../api/_lib/club/payouts.js#L55)) || `/api/x402/club-cover` | platform receiver (kept) | — (funds the club float; issues a door pass) | — |`/api/x402/ring-settle` is an **internal** primitive (`discoverable:false`) — it is@@ -141,8 +141,17 @@ for to feed the oracle and sniper.Agent-ready answers composed over live market data — composites, verdicts, andrisk flags rather than raw category feeds (the raw feeds stay free at`/api/defi/*`, `/api/coin/*`, and `/api/news/*`; these paid surfaces are the-loss-leader funnel's paid tier). Every one refuses before settlement when its-upstream is down — a buyer is never charged for missing data.+loss-leader funnel's paid tier). Every one refuses before settlement when it has+no data to sell, so a buyer is never charged for missing data. The+DeFiLlama-backed boards (`defi-radar`, `yield-scan`, `stablecoin-health`,+`hack-check`) and `market-mood` keep a shared last-good copy+(`cacheWrapLastGood` in `api/_lib/cache.js`) for 15 minutes past their normal+TTL: a short upstream blip serves that recent copy rather than a refusal, and the+pre-settle `503` fires only when there has never been data to serve. Their+upstream reads go through `api/_lib/upstream-fetch.js` (bounded timeout, one+retry), and `three-intel` reads $THREE's market through the shared failover+reader (`api/_lib/market/token-market.js`: Birdeye, tokens.xyz, DexScreener,+GeckoTerminal, DefiLlama, Raydium) instead of a single DexScreener call.| Endpoint | Default | Returns || ------------------------------- | ------- | ------------------------------------------------------------------------------------------------ |diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 5c8c915d2..06456e69a 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -309,6 +309,16 @@ then kept in a verified, watched, auto-fundable state:the sponsor" attack **and** enforces "only our wallets settle here".- **SOL floor.** Below `X402_SPONSOR_SOL_FLOOR_LAMPORTS` (default 0.02 SOL) thefacilitator refuses to settle, pausing the loop before it can drain your SOL.+ The floor guard is written by two witnesses, not one: the balance read, and+ the chain's own verdict. `noteSponsorRentFailure()` trips it whenever a+ settle simulation (or the rebalancer's sweep broadcast) fails with+ `InsufficientFundsForRent` on account index 0 and that fee payer is our+ sponsor, so a dry wallet is caught even while every RPC lane is over quota+ and `getBalance` cannot answer (on 2026-08-28 that gap cost three hours and+ 95 unsettleable payments). A buyer paying its own fee never trips it. The+ autonomous loop reads the same guard (`sponsorKnownBelowFloor()`) when its+ once-per-tick balance read fails, so an unreadable balance never reads as+ solvent.- **Runway alert.** The floor says the rail is already dead. The runway sayshow long until it is, and it pages first: the ring monitor measures thesponsor's burn from `fee_lamports` over `X402_SPONSOR_BURN_WINDOW_DAYS`@@ -328,7 +338,10 @@ then kept in a verified, watched, auto-fundable state:returns a real economic-tick receipt.- **Rebalancer** — [api/_lib/x402/pipelines/ring-rebalance.js](../api/_lib/x402/pipelines/ring-rebalance.js),registered in the autonomous loop. Sweeps treasury→payer so the float never- drains. Recirculation, not spend — never consumes the daily spend cap.+ drains. Recirculation, not spend: never consumes the daily spend cap. A+ sweep broadcast rejected for the sponsor's rent exemption feeds the floor+ guard above (most of the 2026-08-28 faults arrived through this branch, not+ through settle simulation).- **Net-position report** — [api/x402-ring.js](../api/x402-ring.js). `GET/api/x402-ring?period=24h|7d|30d|all`. Gross volume, tx count, SOL burned (inSOL + USD), sweep totals, live balances, the two fee-efficiency numbers@@ -339,6 +352,11 @@ then kept in a verified, watched, auto-fundable state:registered as `fee-audit` (nightly). Measures the real per-settlement andper-$100 fee burn into `x402_fee_audit`, alerts on drift, and closes emptynon-role ATAs to reclaim their rent. Audit + reclaim only — never a spend.+ This pipeline, the rebalancer and the pool funder all take their blockhash+ from the shared read guard (`api/_lib/solana/read-guards.js`), which answers+ from a hash still inside its validity window when the chain is briefly+ unreadable, so a short RPC blip no longer throws a cron tick straight into an+ ops alert; USDC's decimals resolve locally and cost no RPC call at all.- **Endpoint catalog** —[api/_lib/x402/ring-catalog.js](../api/_lib/x402/ring-catalog.js) is the singlesource of truth for **every** paid x402 endpoint on the platform (84 entries asdiff --git a/docs/x402-studio.md b/docs/x402-studio.mdindex e70b8139e..5531a9803 100644--- a/docs/x402-studio.md+++ b/docs/x402-studio.md@@ -22,7 +22,7 @@ The page (`public/x402/studio.js`) is a dependency-free vanilla-JS single-page a**SNS name resolution** (`/api/sns`) resolves a `.sol` name (including subdomains like `nich.threews.sol`) to an address, and reverse-resolves an address to its primary `.sol`, via Bonfida's `@bonfida/spl-name-service` `resolve()` on Solana mainnet. It always answers 200 (`resolved: false` on a miss, not a 404) and caches results in-process (5 minutes positive, 60 seconds negative).-**Real USDC send** (`/api/x402/pay-by-name`) routes a payment by name across three namespaces in order: a raw base58 address, a `<name>.sol` resolved on-chain, or an `@username` mapped to that user's default agent's Solana address. Studio uses `mode: 'prep'`, which builds an unsigned SPL USDC transfer (mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`) with your Phantom wallet as fee payer and source, returns the base64 transaction for signing, and caps the amount at 10,000 USDC per call. This send path is Solana-only (Phantom plus SPL USDC); Base is supported as a payout, agent, or charity destination, not in the send tool.+**Real USDC send** (`/api/x402/pay-by-name`) routes a payment by name across three namespaces in order: a raw base58 address, a `<name>.sol` resolved on-chain, or an `@username` mapped to that user's default agent's Solana address. Studio uses `mode: 'prep'`, which builds an unsigned SPL USDC transfer (mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`) with your Phantom wallet as fee payer and source, returns the base64 transaction for signing, and caps the amount at 10,000 USDC per call. The blockhash in that transaction comes from the shared Solana read guard, which serves a cached hash still inside its validity window when the RPC is briefly unreadable. This send path is Solana-only (Phantom plus SPL USDC); Base is supported as a payout, agent, or charity destination, not in the send tool. The `@solana/web3.js` signing component is fetched on demand through `/load-module.js`, which tries esm.sh, then jsdelivr and unpkg for the same pinned version, each under a deadline; if all three are unreachable or blocked, the status line names the hosts, states that nothing was sent, and re-enables the button.**Storefront builder.** A palette of eight blocks (hero, product grid, single product, text, image, button, divider, footer) drops onto a canvas with HTML5 drag-and-drop and reorder. Save keeps it a draft; Publish sets `store_published` and serves it at `/store/<handle>`. Layout is capped at 60 blocks.diff --git a/prompts/swarm-100/sweep-docs-audit.md b/prompts/swarm-100/sweep-docs-audit.mddeleted file mode 100644index 93b8a05eb..000000000--- a/prompts/swarm-100/sweep-docs-audit.md+++ /dev/null@@ -1,86 +0,0 @@-# Sweep: Docs audit clean--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--Run the sweep's own command first and work from its output, not from any-memory of what used to fail:-- npm run audit:docs && npm run check:docs-freshness--Capture the full output to the session scratchpad; do not work from an-excerpt.--## Task--Run both. Fix dead relative links, site links matching no route, commands naming missing scripts, and packages or workers directories missing a README. Freshness failures mean a doc contradicts current code: fix the doc or the code, whichever is wrong.--Fix everything found in this sweep's scope. Findings that belong to a-different surface entirely (and would take this session off its one task) go-in the report as named follow-ups instead; everything in scope gets fixed-here, at root, with no masking.--## Definition of done--- [ ] The command above exits 0 (or, for measurement-style sweeps, the report- carries the measured numbers and every committed fix).-- [ ] Every fix is a root-cause fix; no check was weakened, skipped, or- quarantined to get to green.-- [ ] npm run check:rules -- --paths <touched files> exits 0; npm test passes- if code changed.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/sweep-docs-audit.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.