Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

docs(ux-flows): catch the forge, commerce, embed, marketplace, and editor walkthroughs up to shipped behavior

nirholas9646eb4a7955
diff --git a/docs/ux-flows/02-forge-text-to-3d.md b/docs/ux-flows/02-forge-text-to-3d.md
index d0799f710..f5356ba82 100644
--- a/docs/ux-flows/02-forge-text-to-3d.md
+++ b/docs/ux-flows/02-forge-text-to-3d.md
@@ -3,7 +3,10 @@
This atlas entry traces the "Text/Image-to-3D (Forge)" cluster end-to-end from real source. Routes are resolved through `vercel.json` rewrites (not the default `pages/<route>.html` convention in every case).
Routing facts (from `vercel.json`):
-- `/forge` → `pages/forge.html` (loads `src/forge.js` + 12 sibling `forge-*` modules).
+- `/forge` → `pages/forge.html` (loads `src/forge.js` + 19 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).
- `/features/forge` → `pages/features/forge.html` (static marketing landing, no app module).
- `/create/prompt` → `pages/create-prompt.html` → `src/create-prompt.js` (text → **rigged avatar**, a different backend from Forge).
- `/tutorials/text-to-3d` and `/tutorials/image-to-3d` → `pages/tutorial.html` (one shared template) which `fetch`es `/docs/tutorials/<slug>.md` and renders it with marked.js. Read-only content pages.
@@ -13,14 +16,15 @@ Routing facts (from `vercel.json`):
### Forge (Text / Photos / Sketch → 3D) — `/forge`
- **Source:**
- - `pages/forge.html` (3177 lines — full composer/stage markup + styles)
- - `src/forge.js` (2445 lines — main controller: catalog, engine/tier selection, job submit, polling, result, gating)
- - `src/forge-prompt-studio.js` (Surprise-me + prompt coach), `src/forge-enhance.js` (AI prompt rewrite → `/api/forge-enhance`)
- - `src/forge-dropzone.js` (paste/drop image handling), `src/forge-reveal.js` (WebGL "materialize" dissolve overlay)
+ - `pages/forge.html` (4153 lines: full composer/stage markup + styles)
+ - `src/forge.js` (3213 lines: main controller, catalog, engine/tier selection, job submit, polling, result, gating; imports `src/forge-timeline.js` for the generation stage timeline and `src/forge-compare.js` for side-by-side compare)
+ - `src/forge-prompt-studio.js` (Surprise-me + prompt coach; prompts come from the slot-grammar generator `src/forge-prompt-gen.js`), `src/forge-enhance.js` (AI prompt rewrite → `/api/forge-enhance`), `src/forge-directed-prompt.js` (reveals the server's art-director rewrite from the `directed_prompt` response field)
+ - `src/forge-dropzone.js` (paste/drop image handling), `src/forge-reveal.js` (WebGL "materialize" dissolve overlay), `src/forge-wait.js` (rotating craft tips while generating)
- `src/forge-refine.js` (in-browser geometry refine, no API), `src/forge-stylize.js` (→ `/api/forge-stylize`), `src/forge-optimize.js` (→ `/api/forge-remesh`), `src/forge-gameready.js` (→ `/api/forge-gameready`)
- - `src/forge-export.js` (in-browser OBJ/STL/PLY/USDZ export), `src/forge-embed-panel.js`, `src/forge-ar.js`, `src/forge-showcase.js` (community feed)
+ - `src/forge-rig.js` (auto-rig → `POST /api/forge?action=rig`), `src/forge-materials.js` (PBR material restyle → `POST /api/material-studio?action=restyle`), `src/forge-conversational-refine.js` (free-text shape iteration → `POST /api/forge-iterate`), `src/forge-more-like-this.js` (one-tap material/finish variation chips), `src/forge-segment.js`
+ - `src/forge-export.js` (in-browser OBJ/STL/PLY/USDZ export), `src/forge-reel.js` (client-side looping video + hero still + transparent-PNG cutout capture), `src/forge-embed-panel.js`, `src/forge-ar.js`, `src/forge-showcase.js` (community feed with upvotes)
- `src/forge-pay.js` (pay-per-generation $THREE rail → `src/token-pay.js` → `/api/token/quote|settle`)
-- **Entry point:** Direct nav to `/forge`; CTAs from `/features/forge` ("Open Forge →"), the two tutorial pages, blog `text-to-3d-is-live`, gallery, and the `/forge` empty-state idle viewer. Also reachable as the "make an object/prop" alternative linked from `/create/prompt`.
+- **Entry point:** Direct nav to `/forge`, `/image-to-3d` (photo tab preselected), or `/forge-max` (High tier pinned); CTAs from `/features/forge` ("Open Forge →"), the two tutorial pages, blog `text-to-3d-is-live`, gallery, and the `/forge` empty-state idle viewer. Also reachable as the "make an object/prop" alternative linked from `/create/prompt`.
- **Prerequisites / gates:**
- **None for the default lane.** Draft/Standard tiers on the free NVIDIA-hosted engine require no auth, no wallet, no payment ("No account required for your first model").
- **BYOK engines** (Fast, Meshy, Tripo, Rodin, Stability, Replicate) require the user to paste their own provider API key (kept in-browser, sent as `x-forge-provider-key` header).
@@ -36,22 +40,26 @@ Routing facts (from `vercel.json`):
7. (optional) User sets the reference-image **aspect ratio** (1:1 / 4:3 / 3:4 / 16:9) — shown only when relevant to the mode/engine. A live **estimate** line (`#estimate`) shows the catalog's real cost/time for the current tier+engine.
8. User clicks **Generate** (or ⌘/Ctrl+Enter). `collectComposerCfg()` validates (text ≥ 3 chars). If High is locked and submitted via keyboard, the gate/upsell opens instead of firing.
9. `startJob()` `POST`s to `/api/forge` with `{ prompt, aspect_ratio, path, tier, backend }` plus headers (client id, BYOK key if any, $THREE tier pass if eligible/needed — minted/awaited before the request when `highTierNeedsPass()`). Stage switches to `#state-generating`.
- 10. **Generating state**: three labeled steps animate — *Painting reference image* → *Reconstructing textured mesh* → *Finalizing GLB* — with an honest elapsed-vs-typical progress bar (asymptotic, never fakes 100%, recolors amber past the catalog ETA). A **Cancel** button is available. When the submit response returns a `preview_image_url`, the reference image paints into the preview pane.
+ 10. **Generating state**: a named stage timeline (`#gen-stages`, rendered by `forge-timeline.js`) animates; every row and state change is driven by a real `/api/forge` signal, so the lane decides which stages exist (a no-reference-image engine never shows one). Below it: an honest elapsed-vs-typical progress bar (asymptotic, never fakes 100%, recolors amber past the catalog ETA), a "feel free to leave this page" hint, and a **Cancel** button. When the API reports `cold_start` for a scale-to-zero self-hosted GPU lane, a "Waking up a GPU" warming card appears and is dismissed by the first real running poll, never by a timer (a keep-warm cron, `/api/cron/gpu-keepwarm`, holds allowlisted GPU workers open during peak hours). While waiting, `forge-wait.js` rotates curated craft tips. When the submit response returns a `preview_image_url`, the reference image paints into the preview pane.
11. If the engine is the synchronous free draft lane, the POST returns the finished `glb_url` directly; otherwise `forge.js` polls `GET /api/forge?job=<id>` every interval until `status:"done"` (with `glb_url`), `failed`, or timeout.
12. On done: `showResult()` sets the `<model-viewer src>`, plays the WebGL **materialize** reveal (`forge-reveal.js`, skipped under reduced-motion), shows the result bar, wires the **Download GLB** anchor, and (if `creation_id`) shows a "Saved ✓" auto-save chip. Geometry-first/sketch results with no reference image get a captured **poster** frame (`POST /api/forge-poster`).
13. (optional) User rates the model: **👍 Keep / 👎 Discard** (verdict) → `POST /api/forge-feedback`; or tags a category (Avatar/Creature/Item/Accessory/Scene/Vehicle) → `POST /api/forge-categorize`. (Data flywheel.)
14. (optional) **Refine → <next tier>** — re-runs the exact same prompt/views one quality tier higher (re-enters step 9). Shown only when a higher tier exists and the job is re-runnable.
15. (optional) **Refine** panel (`forge-refine.js`) — instant in-browser geometry passes (weld/smooth/relax/decimate/subdivide), non-destructive, no API call, no rate limit. Download the refined GLB.
- 16. (optional) **Stylize** (`forge-stylize.js`) — voxels/bricks/lattice/low-poly geometric filters via `POST /api/forge-stylize` (worker job, polled), with a resolution slider, download, and revert.
- 17. (optional) **Optimize topology** (`forge-optimize.js`) — tri/quad/low-poly remesh via `POST /api/forge-remesh` (polled).
- 18. (optional) **Game-Ready** (`forge-gameready.js`) — retopologize to a poly budget and export a textured GLB + FBX for Unity/Unreal via `POST /api/forge-gameready` (polled), with budget slider + wireframe preview.
- 19. (optional) **Split into parts** → links to `/segment?mesh=<glb>` (Parts Studio). **Compose** → `/compose?glb=<glb>` (Scene Composer / attach to avatar).
- 20. (optional) **Export** (`forge-export.js`) — in-browser convert to OBJ / STL / PLY / USDZ (lazy three.js exporters, no upload).
- 21. (optional) **Embed** (`forge-embed-panel.js`) — generate an embeddable web-component snippet for the model.
- 22. (optional) **View in AR** (`forge-ar.js`) / model-viewer's `ar` (webxr/scene-viewer/quick-look) — place the model in the room.
- 23. (optional) **Share** → `forge-share-btn` (share-link path), **Cinema** mode (fullscreen turntable for screen recording, F/Esc).
- 24. User clicks **Download GLB** — anchor fetches + "stamps" the GLB (`#download[data-stamping]`), reports `downloaded:true` feedback, and saves the file. **OR** clicks **Make another** to reset to the idle composer.
-- **Photo / multi-view branch (steps 3–11 differ):** "From photos" tab shows up to 4 view slots (front/back/left/right) with a live "N of 4 views" counter + pips. Each photo is uploaded via presign `POST /api/forge-upload` → `PUT` to object storage; the public URL is recorded. Drag-to-reorder, paste (⌘V/Ctrl+V), drop, or click-to-browse (PNG/JPG/WebP, ≤8MB). An optional guidance prompt is allowed. Submit posts `{ image_urls, prompt?, ... }`. A server-side **vision pre-check** can reject an unusable photo (`422 image_not_usable`) → recoverable "Generate anyway" override.
+ 16. (optional) **Iterate** (`forge-conversational-refine.js`): a free-text instruction against the model on screen ("make the helmet red", "add a cape") via `POST /api/forge-iterate` (polled). The only post-result action that changes the model's shape from natural language; same core as the MCP `refine_model` tool.
+ 17. (optional) **Stylize** (`forge-stylize.js`): voxels/bricks/lattice/low-poly geometric filters via `POST /api/forge-stylize` (worker job, polled), with a resolution slider, download, and revert.
+ 18. (optional) **Restyle materials** (`forge-materials.js`): free-text or preset-chip PBR re-skin (chrome, brushed gold, weathered wood, ...) via synchronous `POST /api/material-studio?action=restyle`; geometry untouched. Same pipeline as the paid `restyle_material` MCP tool.
+ 19. (optional) **Rig for animation** (`forge-rig.js`): adds a humanoid skeleton + skin weights to the current GLB via `POST /api/forge?action=rig` (self-hosted GCP UniRig, Replicate fallback), polled through the same `GET /api/forge?job=` contract.
+ 20. (optional) **Optimize topology** (`forge-optimize.js`): tri/quad/low-poly remesh via `POST /api/forge-remesh` (polled).
+ 21. (optional) **Game-Ready** (`forge-gameready.js`): retopologize to a poly budget and export a textured GLB + FBX for Unity/Unreal via `POST /api/forge-gameready` (polled), with budget slider + wireframe preview.
+ 22. (optional) **Split into parts** → links to `/segment?mesh=<glb>` (Parts Studio). **Compose** → `/compose?glb=<glb>` (Scene Composer / attach to avatar). **Place IRL** → `/irl?avatar=<glb>` (anchor the model in a real room).
+ 23. (optional) **Export** (`forge-export.js`): in-browser convert to OBJ / STL / PLY / USDZ (lazy three.js exporters, no upload).
+ 24. (optional) **Reel** (`forge-reel.js`): fully client-side cinematic capture of the model into a looping video (MP4 or WebM), a hero still, and a transparent-PNG cutout; no upload, no worker.
+ 25. (optional) **Embed** (`forge-embed-panel.js`): generate an embeddable web-component snippet for the model.
+ 26. (optional) **View in AR** (`forge-ar.js`) / model-viewer's `ar` (webxr/scene-viewer/quick-look): place the model in the room. The AR panel also links to the multi-model **AR Studio** (`/ar/studio?src=<glb>`).
+ 27. (optional) **Share** → `forge-share-btn`: when the creation was persisted server-side it shares a real permalink, `/forge/share/<id>`, that unfurls with a preview card; otherwise it falls back to a remix link (`/forge?prompt=`). **Cinema** mode (fullscreen turntable for screen recording, F/Esc). **More like this** (`forge-more-like-this.js`): one-tap chips that re-run the same subject with a different material/finish via the `forge:run-prompt` event (text results only).
+ 28. User clicks **Download GLB**: the anchor fetches + "stamps" the GLB (`#download[data-stamping]`), reports `downloaded:true` feedback, and saves the file. **OR** clicks **Make another** to reset to the idle composer.
+- **Photo / multi-view branch (steps 3-11 differ):** "From photos" tab shows up to 6 view slots (Front/Back/Left/Right/Top/3-4) with a live "N of 6 views" counter + pips. Each photo is uploaded via presign `POST /api/forge-upload` → `PUT` to object storage; the public URL is recorded. Drag-to-reorder, paste (⌘V/Ctrl+V), drop, or click-to-browse (PNG/JPG/WebP, ≤8MB). An optional guidance prompt is allowed. Submit posts `{ image_urls, prompt?, ... }`. A server-side **vision pre-check** can reject an unusable photo (`422 image_not_usable`) → recoverable "Generate anyway" override.
- **Sketch branch:** "From a sketch" tab (only when a live sketch engine exists) takes one drawing + a **required** description; outputs untextured geometry (user is told to Stylize/Retexture after).
- **Decision points / branches:**
- Mode: text vs photos vs sketch (gates which engines/inputs are valid).
@@ -59,20 +67,21 @@ Routing facts (from `vercel.json`):
- Engine: free NVIDIA lane vs BYOK engines (reveals key field; text-only engines disabled when photos are attached).
- High gate resolution: hold $THREE (tier pass) → pay-per-generation ($THREE via `forge-pay.js`) → drop to Draft/Standard.
- Sync draft (POST returns done) vs async poll loop.
- - Post-result fork: Refine-tier / Refine-local / Stylize / Optimize / Game-Ready / Export / Embed / AR / Share / Compose / Segment / Download / Make another.
+ - Post-result fork: Refine-tier / Refine-local / Iterate / Stylize / Restyle-materials / Rig / Optimize / Game-Ready / Export / Reel / Embed / AR / Place-IRL / Share / More-like-this / Compose / Segment / Download / Make another.
+ - Gallery: side-by-side **Compare** mode (`forge-compare.js`) when the same prompt was forged on 2+ engines; showcase cards are upvotable (auth-free, one vote per browser; the Forge-Off board) with a latest / top-this-week sort.
- **External calls / dependencies:**
- Catalog/health: `GET /api/forge?catalog=1`, `GET /api/forge?health=1`
- Submit/poll: `POST /api/forge`, `GET /api/forge?job=<id>`
- Uploads: `POST /api/forge-upload` (presign) + `PUT` object storage
- Flywheel: `POST /api/forge-feedback`, `POST /api/forge-categorize`, `POST /api/forge-poster`
- - Galleries: `GET /api/forge-gallery?limit=24` (your creations), `GET /api/forge-gallery?scope=community&limit=24` (showcase), `GET /api/forge-creation?id=` (share open)
- - Post-processing jobs: `POST /api/forge-stylize`, `POST /api/forge-remesh`, `POST /api/forge-gameready`, `POST /api/forge-enhance` (all polled by `?job=`)
+ - Galleries: `GET /api/forge-gallery?limit=24` (your creations), `GET /api/forge-gallery?scope=community&limit=24` (showcase, plus `&sort=` for the Forge-Off board), `POST /api/forge-vote` (showcase upvotes), `GET /api/forge-creation?id=` (share open)
+ - Post-processing jobs: `POST /api/forge-stylize`, `POST /api/forge-remesh`, `POST /api/forge-gameready`, `POST /api/forge-enhance`, `POST /api/forge-iterate` (all polled by `?job=`); `POST /api/forge?action=rig` (auto-rig, polled by `GET /api/forge?job=`); `POST /api/material-studio?action=restyle` (synchronous)
- Payment: `forge-pay.js` → `src/token-pay.js` → `/api/token/quote` + `/api/token/settle` ($THREE)
- Access/tier pass: `/api/three/access` (read) + tier-pass mint (referenced via `attachTierPass`/`getTierPass`)
- Generation engines: FLUX (image) → TRELLIS (mesh) free lane; BYOK Meshy / Tripo / Rodin / Stability / Replicate; Hunyuan3D / TripoSG (sketch). Hosted on NVIDIA NIM / providers; same pipeline exposed to agents over MCP at `/api/mcp-3d`.
- **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. Additive with automatic fallthrough to the existing provider chain (`textToImage`: NIM FLUX free → Vertex Imagen → Replicate), returning the same `{ imageUrl, model }` shape. When `negativePrompt` is omitted it derives subject-aware negatives from the prompt itself, so a caller gets them for free. The `api/forge.js` text→3D path can adopt it as a drop-in replacement for its `textToImage(directedPrompt, …)` call.
+ - `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 the same `{ imageUrl, model }` shape. When `negativePrompt` is omitted it derives subject-aware negatives from the prompt itself, so a caller gets them for free. `api/forge.js` now imports it on the text→3D path (dynamic import with `textToImage` as the fallback).
- 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:**
@@ -85,7 +94,7 @@ Routing facts (from `vercel.json`):
- Payment errors: `payment_invalid` / `payment_expired` re-offer Pay; `payment_already_used` clears the stale proof.
- Upload errors: per-slot states (503 uploads unavailable, 429 rate-limited, too-large/empty/wrong-type, network).
- Viewer load failure: `#viewer-load-error` overlay → "use the download button to save the file directly".
-- **Step count:** ~12 required (text path, entry → download) + ~12 optional (surprise/enhance, tier/engine/aspect choices, refine-tier, refine-local, stylize, optimize, game-ready, export, embed, AR, share/cinema/compose/segment/verdict/category).
+- **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).
---
@@ -112,7 +121,7 @@ Routing facts (from `vercel.json`):
- **Entry point:** From `/create` (and `create.js`), the create-agent flow, dashboard, and gallery "make one" CTAs.
- **Prerequisites / gates:** **Sign-in required** ("Sign-in required" chip). A `401` on submit or poll redirects to `/login?next=/create/prompt`. No wallet / no $THREE gate. Avatars default to `private` visibility.
- **Steps (3 stages):**
- 1. **Compose:** User types a single-subject character description in `#prompt` (max 600; counter; Generate disabled under 3 chars). Optional example chips fill the box. Hint: "Single subject, full body works best." Cross-link offered to `/forge` for objects.
+ 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).
3. **Building:** Live phased progress — *Rendering a reference image…* (Flux) → *Reconstructing it into 3D…* → *Adding a skeleton so it can move…* — with an elapsed clock. Polls `GET /api/avatars/regenerate-status?jobId=` every 3s (up to 8 min).
4. **Done:** On `status:"done"` + `resultAvatarId`, fetches `GET /api/avatars/<id>`, previews the rigged GLB in the done model-viewer, shows tags (Animation-ready / Static mesh — riggable / Private to you). CTAs: **Open in editor** (`/avatars/<id>/edit`) and **Make another**. If no model URL yet, it redirects straight to the editor.
@@ -126,7 +135,7 @@ Routing facts (from `vercel.json`):
### 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`).
+- **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).
- **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.md
index 363be32a1..3251a842b 100644
--- a/docs/ux-flows/03-3d-editing-viewer.md
+++ b/docs/ux-flows/03-3d-editing-viewer.md
@@ -126,7 +126,7 @@ Routing summary (from `vite.config.js`):
3. Viewer renders via `view()` → WebGL check, `createViewer()`, `viewer.load(url, …)` with a progress callback, then attach avatar, notify editor, configure animations, set AR target, run validator (app.js:1783-1876).
4. (optional) Load your own model — drag-drop a `.glb`/`.gltf` or folder anywhere on `.wrap` (`SimpleDropzone` → `load(files)`, app.js:1708-1776); or the `#file-input` picker; or `?model=<url>`/`#model=` (host-validated by `isSafeQueryModelUrl` for the deploy path, app.js:25-38); or `?agent=<uuid>`.
5. (optional) Open the editor controls (dat.GUI / Next-layout drawer): **Display** (background, autoRotate, wireframe, skeleton, grid, point size, transparent bg, screenshot, model info, mesh labels), **Lighting** (IBL/envMap, exposure, tone mapping, punctual lights), **Light Probes**, **Animation**, **Morph Targets**, **Cameras**, **Agent** follow mode, **Performance** stats (viewer.js `addGUI`).
- 6. (optional) Play animations — `_configureAnimations` fetches `/animations/manifest.json`, registers clips, honors `?anim=<name|uuid>`; Next-layout dock gives clip picker + play/pause + scrubber + loop (app.js:1921-1986).
+ 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.
7. (optional) Edit environment / lights / camera / display via the GUI (`updateEnvironment`, `updateLights`, `setCamera`, `frameContent`, etc. in viewer.js).
8. (optional) Edit materials / textures / scene via the `Editor` (`MaterialEditor`, `TextureInspector`, `SceneExplorer`, `MagicBrush`; rebuilt on each new model, editor/index.js:19-55).
9. (optional) Take a screenshot → `viewer.captureScreenshot()` → `ScreenshotModal.show(blob)` (app.js:825-837).
diff --git a/docs/ux-flows/04-embed-widget-studio.md b/docs/ux-flows/04-embed-widget-studio.md
index f42986f92..bb0a9e370 100644
--- a/docs/ux-flows/04-embed-widget-studio.md
+++ b/docs/ux-flows/04-embed-widget-studio.md
@@ -23,10 +23,10 @@ Routing recap (from `vercel.json`):
### Widget Studio — `/studio`
- **Source:** `public/studio/index.html`, `public/studio/studio.js`, `public/studio/studio.css`, `public/studio/launch-panel.js`, `public/studio/knowledge-panel.js`. Preview iframe loads `/widget` (slim `src/app.js` shell). APIs: `/api/auth/me`, `/api/avatars`, `/api/avatars/public`, `/api/avatars/:id`, `/api/widgets`.
- **Entry point:** Direct nav to `/studio`; "Create yours" / "Open the Studio" CTAs on `/widgets`; "Open Studio →" on `/features/studio`; "Open in Studio" links from gallery cards (`/studio?template=<id>`); deep links `?edit=<id>`, `?type=<type>`, `?model=<url>`, `?avatar=<id>`.
-- **Prerequisites / gates:** None to try — a built-in **demo avatar (CZ, `/avatars/cz.glb`)** is preloaded so an anonymous visitor can configure and preview. **Saving a draft / embedding a non-demo avatar requires sign-in** (`/login?next=/studio`) and an owned/public avatar. The demo avatar can generate an embed (pointing at a baked demo fixture, e.g. `wdgt_demo_talking`) but cannot save. No $THREE gate. ⚡ Launch tab can optionally launch the agent's coin via `launch-panel.js`.
+- **Prerequisites / gates:** None to try: a built-in **demo avatar (CZ, `/avatars/cz.glb`)** is preloaded so an anonymous visitor can configure and preview. **Saving a draft / embedding a non-demo avatar requires sign-in** (`/login?next=/studio`) and an owned/public avatar. The demo avatar can generate an embed (pointing at a baked demo fixture, e.g. `wdgt_demo_talking`) but cannot save. No $THREE gate. ⚡ Launch tab can optionally launch the agent's coin via `launch-panel.js` (lane toggle: pump.fun or the three.ws curve; oversized token images are downscaled in-browser instead of rejected).
- **Steps (10):**
1. Page boots → `fetchMe()` (`/api/auth/me`) resolves user; user menu renders (signed-out shows "Sign in"); 3-column layout unhides.
- 2. System renders the **widget-type grid** (9 ready types: turntable, animation-gallery, talking-agent, passport, hotspot-tour, pumpfun-feed, kol-trades, live-trades-canvas, bonding-curve) and **avatar list** (`loadAvatars()` → demo avatar + `/api/avatars?limit=100` for signed-in users, with skeleton cards while loading).
+ 2. System renders the **widget-type grid** (10 ready types: turntable, animation-gallery, talking-agent, passport, hotspot-tour, pumpfun-feed, kol-trades, live-trades-canvas, bonding-curve, walking-avatar) and **avatar list** (`loadAvatars()` → demo avatar + `/api/avatars?limit=100` for signed-in users, with skeleton cards while loading).
3. **Pick avatar** (step-1 panel): click an avatar card → `selectAvatar()`; or `(optional)` search public avatars (`/api/avatars/public?q=`) and pick one; demo avatar is selected automatically if none chosen.
4. **Pick widget type** (step-2 panel): click a type card → `selectType()` rebuilds the type-specific config fields, preserving brand settings.
5. System loads the **live preview** in the `/widget` iframe (`updatePreview()` builds `#model=…&kiosk=true&type=…`), posts the config via `postMessage({type:'widget:config'})`; status flips to "Live preview".
@@ -43,7 +43,7 @@ Routing recap (from `vercel.json`):
- Right column tabs: **Brand** ↔ **⚡ Launch** (launch panel hides save/generate row).
- **External calls / dependencies:** `/api/auth/me`, `/api/auth/logout`, `/api/avatars`, `/api/avatars/public`, `/api/avatars/:id` (POST to register), `/api/widgets` (GET/POST/PATCH/DELETE), preview iframe `/widget#…`, embed loader `/embed.js`, share/live `/w/<id>`, `/api/widgets/:id/og` (poster). Importmap loads `@solana/web3.js` + `@solana/spl-token` from esm.sh for the Launch tab.
- **Success state:** Embed modal open with a copyable iframe + script snippet and a live shareable `/w/<id>` URL; "View live" opens it in a new tab. Toast "Saved" on draft save.
-- **Empty / error states:** No avatars → empty card with "Scan yourself to 3D →" / "AI selfie →". Avatar load failure → inline error card with **Retry**. Public search failure → status line shows reason. Save failure → `#form-error` text. Preview without a model → "Avatar has no public URL — make it public/unlisted to preview". Pre-selected avatar missing → toast + falls back to demo. Pending-status types show a "ships in a later prompt" banner (currently none — all 9 are `ready`).
+- **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)
---
@@ -56,7 +56,7 @@ Routing recap (from `vercel.json`):
1. Page loads → 3 skeleton cards render (`showSkeleton`).
2. `fetch('/widgets-gallery/showcase.json')` → builds **filter chips** (one per widget type + "All"), updates hero count, renders one **showcase card** per widget; cards fade in on scroll (IntersectionObserver).
3. Each card auto-loads its preview iframe when 50% visible (or via the ▶ play button); `(optional)` toggle **Preview ↔ Code** tab to see the snippet in the frame area.
- 4. **Customize** `(optional)`: open the Customize `<details>` and adjust Size (S/M/L), Accent color, and per-type knobs (mint for kol-trades/live-trades-canvas, kind for pumpfun-feed). Snippet + iframe update live (debounced 350 ms reload); "Reset" restores defaults.
+ 4. **Customize** `(optional)`: open the Customize `<details>` and adjust Size (S/M/L), Accent color, and per-type knobs (mint for kol-trades/live-trades-canvas/bonding-curve, kind for pumpfun-feed). Snippet + iframe update live (debounced 350 ms reload); "Reset" restores defaults.
5. **Copy embed**: split-button copies the current snippet; `(optional)` use the format dropdown to switch **HTML iframe / JSX (React) / Share URL** before copying. Button flips to "Copied!".
6. Paste the snippet on any site → renders the live widget. Done. (Or click **"Open in Studio"** → `/studio?template=<id>` to clone & customize fully — branches into the Widget Studio flow.)
- **Decision points / branches:**
@@ -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 8 in static HTML, overwritten by real count.
+- **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.
- **Step count:** 6 required (+3 optional)
---
@@ -109,7 +109,7 @@ Routing recap (from `vercel.json`):
---
### Agent embed snippet (SharePanel / `<agent-3d>`) — share/embed panel flow
-- **Source:** `src/share-panel.js` (`SharePanel` class) + `src/share-panel-builders.js` (`buildEmbedUrl`, `buildIframeSnippet`, `buildWebComponentSnippet`) + `src/share-panel.css`. Mounted on the agent home page via `src/agent-home-orphans.js`; also referenced from `src/agent-detail.js` and `src/forge.js`. Embed targets: `/agent/<id>/embed` (CSP `frame-ancestors *`), web component `/dist-lib/agent-3d.js`. Preview iframe = same `/agent/<id>/embed?preview=1`.
+- **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):**
@@ -145,7 +145,7 @@ Routing recap (from `vercel.json`):
- **Entry point:** `/avatar-studio` or `/create/studio` (create from `default.glb`); `?edit=<id>` reloads a saved avatar.
- **Prerequisites / gates:** Anyone can build/preview from the base template. **Saving requires sign-in** (so it persists to the account). No $THREE gate. This is the *upstream* builder — the avatar it produces becomes selectable in Widget Studio and embeddable via the SharePanel/embed modals.
- **Steps (7):**
- 1. Page boots → loads `BASE_GLB_URL` (`/avatars/default.glb`) into a `TalkScene` viewport with idle breathing/blinking; accessory presets load.
+ 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 RPM-style 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).
4. `(optional)` Show/hide garment layers; `(optional)` search accessories.
diff --git a/docs/ux-flows/06-marketplace-skills.md b/docs/ux-flows/06-marketplace-skills.md
index e0bcc0d26..9ddd7b6b3 100644
--- a/docs/ux-flows/06-marketplace-skills.md
+++ b/docs/ux-flows/06-marketplace-skills.md
@@ -1,17 +1,18 @@
# Marketplace & Skills
-UX Flow Atlas — cluster 6. Traced against real source in `/workspaces/three.ws`. The marketplace is a path + query-param SPA served by one HTML shell (`marketplace.html`) driven by `src/marketplace.js` (8.4k lines). `/skills` is a redirect into that SPA. `/collection` and `/marketplace/analytics` are standalone pages. The critical path (browse → buy → unlock → collection) spans two purchase endpoints (`/api/marketplace/purchase` for individual skills, `/api/marketplace/buy-asset` for whole avatars/agents/plugins), both Solana-Pay-by-reference with optional gasless sponsorship and an EVM/USDC fallback.
-
-Routing facts confirmed in `vercel.json`:
-- `/marketplace`, `/marketplace/` → `/marketplace.html` (lines 1603-1610)
-- `/marketplace/(tools|skills|animations|onchain)/:id` → `/marketplace.html` (SPA handles detail; line 1611)
-- `/marketplace/agents/:id` → **301 redirect to `/agents/:id`** (canonical agent page; line 1615)
-- `/marketplace/avatars/:id` → **301 redirect to `/avatars/:id`** (line 1622)
-- `/marketplace/analytics` → `/pages/marketplace-analytics.html` (line 1595)
-- `/collection` → `/pages/collection.html` (line 1587)
-- `/skills` → `/skills.html` (line 1571), which client-redirects to `/marketplace?tab=skills`
-- `/api/marketplace/purchase/:ref/confirm` → `purchase.js?reference&op=confirm` (line 1555)
-- `/api/marketplace/buy-asset/:ref/confirm` → `buy-asset.js?reference&op=confirm` (line 1563)
+UX Flow Atlas, cluster 6. Traced against real source in `/workspaces/three.ws`. The marketplace is a path + query-param SPA served by one HTML shell (`marketplace.html`) driven by `src/marketplace.js` (8.9k lines). `/skills` is a redirect into that SPA. `/collection` and `/marketplace/analytics` are standalone pages. The critical path (browse → buy → unlock → collection) spans two purchase endpoints (`/api/marketplace/purchase` for individual skills, `/api/marketplace/buy-asset` for whole avatars/agents/plugins), both Solana-Pay-by-reference with optional gasless sponsorship and an EVM/USDC fallback.
+
+Routing facts confirmed in `vercel.json` (line numbers shift too often to pin; grep the route `src` instead):
+- `/marketplace`, `/marketplace/` → `/marketplace.html`
+- `/marketplace/(tools|skills|animations|onchain)/:id` → `/marketplace.html` (SPA handles detail)
+- `/marketplace/agents/:id` → **301 redirect to `/agents/:id`** (canonical agent page)
+- `/marketplace/avatars/:id` → **301 redirect to `/avatars/:id`**
+- `/marketplace/analytics` → `/pages/marketplace-analytics.html`
+- `/collection` → `/pages/collection.html`
+- `/skills` → `/skills.html`, which client-redirects to `/marketplace?tab=skills`
+- `/api/marketplace/purchase/:ref/confirm` → `purchase.js?reference&op=confirm`
+- `/api/marketplace/buy-asset/:ref/confirm` → `buy-asset.js?reference&op=confirm`
+- `/api/marketplace/purchase-bundle/:id/confirm` → `purchase-bundle.js?purchase_id&op=confirm`
---
@@ -78,7 +79,7 @@ Routing facts confirmed in `vercel.json`:
11. **Branch — verification outcomes:** `confirmed` → success; `409 transfer_mismatch` (status `tipped` when a smaller-but-real transfer landed); `410 purchase_expired` for a stale pending row.
12. On confirmed, modal renders a signed receipt (`buildReceiptHTML`) with a Solscan link, then resolves true.
13. Client refreshes ownership: `fetchUserPurchases()` and reloads the detail (`loadDetail`) so the skill now shows "Installed ✓"; the purchase appears under the "My Purchases" tab and in `/collection`.
-- **Decision points / branches:** gasless (wallet connected, sponsored) vs buyer-pays vs mobile QR (Solana Pay); already-owned short-circuit; insufficient funds → Add funds; gift purchase (`recipient`) resolved server-side via `resolveRecipient`; verification mismatch (tipped) vs expired.
+- **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).
- **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.
@@ -92,15 +93,15 @@ Routing facts confirmed in `vercel.json`:
- **Prerequisites / gates:** Auth + CSRF + rate limit; asset must have an active `asset_prices` row; seller must have a configured payout wallet for the chain (else `412 creator_wallet_missing`); buyer must not be the owner (else `400 self_purchase`); connected wallet with sufficient balance.
- **Steps (N):**
1. User clicks "Buy now" → `openAssetPurchaseFlow({ item_type, item_id, label, price })` opens the payment modal in `mode='asset'`.
- 2. (optional) Connect wallet if not connected.
- 3. User confirms → POST `/api/marketplace/buy-asset` `{ item_type, item_id, [buyer_public_key] }`.
+ 2. (optional) Connect wallet if not connected. For signed-in users the modal also prepends a "Pay from an agent's own wallet, no popup" block (up to 4 owned agents with live USDC balances, from `/api/x402-pay?agents=1`; underfunded agents are disabled).
+ 3. User confirms → POST `/api/marketplace/buy-asset` `{ item_type, item_id, [buyer_public_key] }`. **Agent-wallet branch:** picking an agent instead POSTs `{ item_type, item_id, agent_id }`; the server verifies ownership, enforces the agent's daily purchase cap (`agent_identities.meta.auto_purchase_daily_limit_usdc`, summed across skill AND asset purchases by `api/_lib/agent-purchase.js`; exceeding it returns `402 spend_cap_exceeded`), signs from the agent's custodial wallet, validates the transfer on-chain, and grants in one round trip (no prepare → sign → confirm dance).
4. Server validates price/seller/payout; **already-owned** confirmed purchase short-circuits with `already_owned: true`; otherwise reuses or inserts a pending `asset_purchases` row (30-min expiry) and returns `{ reference, recipient, amount, currency_mint, chain, mint_decimals }` (+ gasless block when applicable).
5. **Branch — already owned:** modal jumps to the success screen, skips payment.
6. Client builds + signs the full-amount SPL transfer (single leg, no platform fee) with the reference key; user approves in wallet.
7. Client confirms on-chain, then polls `/api/marketplace/buy-asset/:reference/confirm` (2.5s, 60s).
8. Server (Solana) `findReference` → `validateTransfer`; on success marks `confirmed`, writes a signed `asset_purchase_receipts` row, and notifies both seller (`asset_purchased`) and buyer (`asset_purchase_confirmed`).
9. Modal renders the success card; primary CTA goes to `/dashboard/avatars`, `/dashboard/agents`, or `/dashboard` per asset type; `fetchUserPurchases()` refreshes ownership.
-- **Decision points / branches:** chain = Solana vs EVM (EVM confirm requires a submitted `tx_hash`, verified via `verifyEvmUsdcPayment` on Base; short transfer = `tipped` 409); gasless vs buyer-pays; already-owned; mismatch (tipped) vs expired (410).
+- **Decision points / branches:** chain = Solana vs EVM (EVM confirm requires a submitted `tx_hash`, verified via `verifyEvmUsdcPayment` on Base; short transfer = `tipped` 409); browser wallet (gasless vs buyer-pays) vs agent custodial wallet (server-signed, capped); already-owned; mismatch (tipped) vs expired (410).
- **External calls / dependencies:** `POST /api/marketplace/buy-asset` (+ `/:ref` status, `/:ref/confirm`), Solana RPC w/ fallback, `@solana/pay`, EVM USDC verifier, `insertNotification`, receipt HMAC signing.
- **Success state:** Asset confirmed and owned; receipt stored; both parties notified; CTA into the relevant dashboard; surfaced in `/collection`.
- **Empty / error states:** `404 not for sale`, `412 creator_wallet_missing`, `400 self_purchase`, `409 transfer_mismatch` (tipped), `410 purchase_expired`; client retry/re-verify identical to the skill flow.
@@ -111,14 +112,14 @@ Routing facts confirmed in `vercel.json`:
### Free trial unlock — `/api/marketplace/start-trial`
- **Source:** `src/marketplace.js` (`openTrialFlow()` ~L6794), backend `api/marketplace/start-trial.js`
- **Entry point:** "Try free (N left)" button on a trial-eligible paid skill (detail view or grid card).
-- **Prerequisites / gates:** Auth (button redirects to login on 401). No wallet/payment.
+- **Prerequisites / gates:** Auth (button redirects to login on 401): a browser session cookie (CSRF enforced) or an API-key bearer token (CSRF skipped for bearer callers). No wallet/payment.
- **Steps (N):**
1. User clicks "Try free" → `openTrialFlow(agentId, skill, btn)`.
2. Client POSTs `/api/marketplace/start-trial` `{ agent_id, skill }`.
3. **Branch:** if already owned or trial already used, an alert explains and stops.
4. On success, `fetchUserPurchases()` + `loadDetail()` refresh; the skill now shows in My Purchases with a "Trial (N left)" badge and works until uses are exhausted.
- **Decision points / branches:** trial available vs already-owned vs trial-used.
-- **External calls / dependencies:** `POST /api/marketplace/start-trial`, `/api/users/me/purchased-skills`.
+- **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).
- **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)
@@ -171,15 +172,16 @@ Routing facts confirmed in `vercel.json`:
- **Prerequisites / gates:** None — public aggregate stats.
- **Steps (N):**
1. Page loads → `load()` fetches `/api/marketplace/analytics`.
- 2. Stat cards render: total skill sales, total volume, unique buyers, creators with sales, NFT receipts minted.
- 3. A 30-day volume bar chart draws on a Canvas (no charting dependency; theme-aware colors, missing days zero-filled).
- 4. Top Skills ranked list renders (skill, agent, sales count, revenue).
- 5. Top Agents ranked list renders (agent, skill-sale count, net revenue).
-- **Decision points / branches:** has-data vs empty ("No sales yet." / "No agents yet."); dark vs light theme chart palette.
+ 2. Stat cards render: Paid skill sales, Total volume, Free trials taken, Paying buyers, Creators listing skills. Sales/volume/buyers count `status = 'confirmed'` rows only; free trials are counted on their own card so they can never read as revenue.
+ 3. A **trial funnel** section renders (Trials granted → used → exhausted → converted), with a diagnosis note when the funnel is broken (e.g. many exhausted trials with zero conversions) linking to `/tutorials/sell-a-skill-with-a-trial`.
+ 4. A 30-day volume bar chart draws on a Canvas (no charting dependency; theme-aware colors, missing days zero-filled). With no paid sales it renders an honest empty state ("No paid sales in the last 30 days") instead of a void.
+ 5. Top Skills ranked list renders (skill, agent, sales count or "N trials, no sales yet", revenue).
+ 6. Top Agents ranked list renders (agent, skill-sale count, net revenue).
+- **Decision points / branches:** has-data vs empty ("No skills listed yet." / "No agents yet."); paid vs trial split everywhere; dark vs light theme chart palette.
- **External calls / dependencies:** `GET /api/marketplace/analytics` only.
-- **Success state:** Stats grid, volume chart, and both ranked lists populated.
+- **Success state:** Stats grid, trial funnel, volume chart, and both ranked lists populated.
- **Empty / error states:** Fetch/parse failure → `#an-error` "Failed to load analytics. Please refresh." and all sections cleared; per-list empty placeholders.
-- **Step count:** 5 required (+0 optional)
+- **Step count:** 6 required (+0 optional)
---
@@ -201,7 +203,7 @@ Routing facts confirmed in `vercel.json`:
## Notes
- `/marketplace/agents/:id` and `/marketplace/avatars/:id` are **301 redirects** to the canonical `/agents/:id` and `/avatars/:id` pages (vercel.json). Within the SPA, the same paths render inline via `loadDetail()`/`loadAvatarDetail()` before a hard navigation would redirect; `marketplace-detail.js` powers both the SPA detail and the canonical pages.
-- Two distinct purchase rails: **individual skills** (`/api/marketplace/purchase`, splits creator + platform fee, records `agent_revenue_events`) vs **whole assets** (`/api/marketplace/buy-asset`, single full-amount leg, no fee, EVM/USDC fallback). The embed widget (`payment-modal.js`) only drives the skill rail.
+- Two distinct purchase rails: **individual skills** (`/api/marketplace/purchase`, splits creator + platform fee, records `agent_revenue_events`) vs **whole assets** (`/api/marketplace/buy-asset`, single full-amount leg, no fee, EVM/USDC fallback). The embed widget (`payment-modal.js`) only drives the skill rail. Both rails also have an **agent-payer** variant (`/api/marketplace/purchase-as-agent`, and `buy-asset` with `agent_id`) where the server signs from an owned agent's custodial wallet under one shared daily spend cap (`api/_lib/agent-purchase.js`).
- "Skills marketplace" (`/skills`, `/api/skills/*`) sells community tool packs — **install is free, payment is per-call via x402** — which is a different mechanism from the skill *unlock* purchase on an agent's detail page (`/api/marketplace/purchase`). Both can show under a user's owned items.
- `src/marketplace-lobby.js` is not URL-routed; it's a Three.js scene mounted into the hero canvas with an `onSelect` callback back to `marketplace.js`.
-- Source coverage: all referenced files were located and read. No missing sources. Line numbers for `marketplace.js` are approximate anchors from a structural read of the 8.4k-line file, not exact-verified per line.
+- Source coverage: all referenced files were located and read. No missing sources. Line numbers for `marketplace.js` are approximate anchors from a structural read of the 8.9k-line file, not exact-verified per line.
diff --git a/docs/ux-flows/09-x402-agent-commerce.md b/docs/ux-flows/09-x402-agent-commerce.md
index 354402ab9..4d1c93481 100644
--- a/docs/ux-flows/09-x402-agent-commerce.md
+++ b/docs/ux-flows/09-x402-agent-commerce.md
@@ -156,8 +156,8 @@ choreographed two-agent narrative driven by Server-Sent Events.
3. Click **Check This Fact** → validate → skeleton + "Searching sources…".
4. `POST /api/x402/fact-check` with `{ claim, strictness }`.
5. On `402` → payment panel (Base USDC $0.10 / Solana USDC $0.10) + "Connect wallet to pay →" (`/marketplace`). On `200` → verdict banner (SUPPORTED/CONTRADICTED/MIXED/INSUFFICIENT + confidence), sources grid (stance/authority), cost breakdown, expandable SHA-256 attestation.
-- **Decision points / branches:** empty claim → no submit; `402` → payment panel; `429` → "Too many checks…"; `5xx` → internal-error message; retry button re-runs same claim. Cached result returns `200` instantly.
-- **External calls / dependencies:** `/api/x402/fact-check` (3 search queries → multi-source retrieval → LLM stance → weighted verdict → attestation; optional vision for image evidence, fail-open), Base/Solana USDC, Redis cache (7-day TTL).
+- **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).
- **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).
@@ -333,4 +333,5 @@ choreographed two-agent narrative driven by Server-Sent Events.
- **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.
+- **Adjacent economy surfaces (2026-08-01, not yet traced as full sections):** `/economy-lab` (Runway Lab, a live digital twin of the x402 payment rail; backend `api/x402/runway-lab.js`), `/pay-simulator` (Spend Policy Simulator: dry-run an agent spending policy against real x402 prices), `/flow` (Money Flow Map, see `docs/money-flow-map.md`), `/play/solver` (see `docs/economy-solver.md`), and `/conversions`.
- **Source coverage:** all 17 routes located and traced from real source. `/tutor` resolves to `public/tutor.html` + `public/tutor.js` (served statically; no explicit vite map entry needed). No source was missing.