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: add R-3d-world-fun phase 3/4 briefs and X-prod-errors-2026-06-05 program

nirholasa814b6adbddb
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-3/R17-world-object-persistence.md b/docs/agent-briefs/R-3d-world-fun/phase-3/R17-world-object-persistence.md
new file mode 100644
index 000000000..f05cd5982
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-3/R17-world-object-persistence.md
@@ -0,0 +1,39 @@
+# R17 — Persistence layer for world objects
+
+**Phase 3 (Sandbox building) · Depends on: R01 · Unblocks: R19**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. **Inspect the repo's existing storage — do NOT invent a new provider.** Real backend only.
+
+## Goal
+
+Make placed objects durable per coin world, keyed by coin mint. Leaving and re-entering a coin
+world shows the same build; it survives a server restart.
+
+## Files
+
+- `api/` and/or `workers/` — a storage-backed endpoint/worker using the **existing** KV/DB the repo
+ already uses (inspect `api/_lib/`, existing workers, and how the off-schema economy already
+ persists state — match that). Do not introduce a new datastore.
+- `multiplayer/src/rooms/WalkRoom.js` — load saved objects on room create; persist on
+ `obj:spawn` / `obj:update` / `obj:remove` (debounced).
+
+## Spec
+
+1. **Inspect first.** Find how the repo already persists data (the fishing/inventory off-schema
+ economy, KV, or DB) and use that exact provider/pattern. A new provider is not allowed.
+2. **Keyed by coin mint.** Saved object sets are scoped per coin world (the room's coin mint is the
+ key).
+3. **Load on create.** When a `WalkRoom` is created for a coin, hydrate the R01 `objects` map from
+ storage before clients connect.
+4. **Persist on change.** On `obj:spawn` / `obj:update` / `obj:remove`, write through to storage,
+ **debounced** so rapid updates don't hammer the backend. Distinguish persistent build pieces
+ from transient objects (e.g. the R05 ball) so transient ones are not saved.
+5. **Real, not in-memory.** Persistence must survive a full server restart, not just live in room
+ memory.
+
+## Definition of done
+
+- Placing objects, leaving, and re-entering a coin world shows the same build.
+- Persistence survives a server restart. Writes are debounced; transient objects are excluded.
+- Uses the existing datastore — no new provider. No console/server errors. Diff self-reviewed per DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-3/R18-build-mode-and-placement-ui.md b/docs/agent-briefs/R-3d-world-fun/phase-3/R18-build-mode-and-placement-ui.md
new file mode 100644
index 000000000..3e624f52b
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-3/R18-build-mode-and-placement-ui.md
@@ -0,0 +1,43 @@
+# R18 — Build mode + placement UI
+
+**Phase 3 (Sandbox building) · Depends on: R01, R02 · Unblocks: R19, R20**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. Reuse the R02 object channel + `kind` registry. Placement is `obj:spawn kind:'block'`.
+
+## Goal
+
+A "Build" toggle in `/play` that opens a palette of placeable props/blocks. Ghost-preview the piece
+at a snapped position under the cursor/reticle, rotate it, place it, and delete your own pieces.
+Clean enter/exit between movement and build cursor.
+
+## Files
+
+- `src/game/coincommunities-ui.js` — Build toggle + palette UI.
+- `src/game/coincommunities.css` — palette + ghost-preview styling using `cc-*` tokens.
+- `src/game/coincommunities.js` — build-mode state machine, ghost preview, raycast placement,
+ rotate, place (`spawnObject kind:'block'`), delete-own.
+- `src/game/world-objects.js` — register block/prop mesh factories in the R02 `kind` registry.
+
+## Spec
+
+1. **Build toggle** — enters build mode: switches from movement controls to a build cursor/reticle,
+ shows the palette. Exiting restores normal movement. The transition is unambiguous (cursor,
+ HUD hint).
+2. **Palette** — a handful of primitives + a few GLB props (reuse accessory/prop loading patterns).
+ Owned/selected states; hover/active/focus on items.
+3. **Ghost preview** — show a translucent preview of the selected piece at a **snapped** position
+ under the cursor/reticle. Rotate with a key. The preview clearly indicates a valid vs blocked
+ placement.
+4. **Place** — sends `obj:spawn kind:'block'` (via R02 `community-net.spawnObject`); the piece
+ appears for everyone through object sync.
+5. **Delete** — remove **your own** pieces (full server-side ownership enforcement is R19; here,
+ only offer delete on pieces you placed).
+6. **Touch + desktop** — placement, rotate, and delete all work on desktop and touch.
+
+## Definition of done
+
+- You can place, rotate, and remove pieces; preview is clear; placements appear for everyone via
+ object sync. Feels good on desktop and touch.
+- Clean enter/exit of build mode (movement vs build cursor never conflict).
+- No console errors/warnings, no leaks. Verified with two clients. Diff self-reviewed per DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-3/R19-build-netcode-permissions-antigrief.md b/docs/agent-briefs/R-3d-world-fun/phase-3/R19-build-netcode-permissions-antigrief.md
new file mode 100644
index 000000000..b6904f0eb
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-3/R19-build-netcode-permissions-antigrief.md
@@ -0,0 +1,39 @@
+# R19 — Build netcode hardening + permissions + anti-grief
+
+**Phase 3 (Sandbox building) · Depends on: R17, R18 · Server-authoritative**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. All enforcement is server-side. Limits must be **surfaced in the UI — no silent failures.**
+
+## Goal
+
+Server-side validation for builds: ownership, per-player caps, rate limits, bounds, and a simple
+grief guard. Plus a creator "clear area" moderation tool. Griefing is bounded; ownership enforced.
+
+## Files
+
+- `multiplayer/src/rooms/WalkRoom.js` — build validation on `obj:spawn` / `obj:remove`: ownership,
+ caps, rate limits, bounds, grief guard, creator clear-area.
+- `src/game/coincommunities-ui.js` — surface limits/denials to the user; creator clear-area control.
+- `src/game/coincommunities.js` — reflect rejected placements (no ghost left behind) and show why.
+
+## Spec
+
+1. **Ownership** — only the placer may delete a piece, **except** the coin creator, who may delete
+ any piece in their world. Enforce server-side; never trust the client's claim of ownership.
+2. **Caps & limits** — per-player placement cap, per-room density cap, rate limit on spawns, and
+ world-radius bounds. These build on R01's generic caps but add build-specific tuning.
+3. **Grief guard** — disallow burying the spawn point or the totem, and cap density per tile so a
+ single user can't wall off the world.
+4. **Creator moderation** — a creator-only "clear area" action (and/or clear-all-in-radius) for the
+ coin owner, validated server-side.
+5. **Surface everything** — when a placement is rejected (cap hit, too dense, protected zone,
+ rate-limited), the UI tells the user clearly and removes the failed ghost. **No silent failures.**
+
+## Definition of done
+
+- Griefing is bounded; ownership enforced; creator moderation works; all limits are clearly
+ surfaced in the UI with no silent failures.
+- All enforcement is server-side and survives malicious clients. No console/server errors.
+- Verified with two clients (including a non-owner trying to delete and an over-cap user).
+ Diff self-reviewed per the R00 / CLAUDE.md DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-3/R20-structures-snapping-sharing.md b/docs/agent-briefs/R-3d-world-fun/phase-3/R20-structures-snapping-sharing.md
new file mode 100644
index 000000000..267d30e1d
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-3/R20-structures-snapping-sharing.md
@@ -0,0 +1,42 @@
+# R20 — Structures, snapping, and sharing
+
+**Phase 3 (Sandbox building) · Depends on: R18, R19 · Performance-critical**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. Large builds must stay performant — instance/merge static blocks.
+
+## Goal
+
+Level up building: a grid/snap system so blocks align into structures, a few composite pieces, a
+copy/screenshot-a-build share action, and a small "featured builds" surface per coin. Building feels
+satisfying and snaps cleanly; large builds stay smooth.
+
+## Files
+
+- `src/game/coincommunities.js` — grid/snap math, composite-piece placement, static-block
+ instancing/merging, screenshot capture.
+- `src/game/coincommunities-ui.js` — composite-piece palette entries, share action, featured-builds
+ surface.
+- `src/game/coincommunities.css` — styling for the above using `cc-*` tokens.
+- `api/` / `workers/` — a "featured builds" + share endpoint reusing the R17 persistence layer (no
+ new provider).
+
+## Spec
+
+1. **Grid/snap** — blocks snap to a grid so they align into clean structures; snapping is visible in
+ the ghost preview from R18. Rotation snaps too.
+2. **Composite pieces** — a few ready-made pieces (wall, floor, ramp, door) placeable as single
+ units, built on the same `obj:spawn` channel.
+3. **Performance** — instance or merge static blocks so large builds don't tank framerate. No
+ per-block draw-call explosion; no console warnings under a big build.
+4. **Share** — a copy/screenshot-a-build action (capture the canvas + a shareable reference), wired
+ through the R17 persistence layer.
+5. **Featured builds** — a small per-coin "featured builds" surface (designed empty/loading/error
+ states) that links back into the world.
+
+## Definition of done
+
+- Building structures is satisfying and snaps cleanly; composite pieces place as units.
+- Large builds stay performant (instanced/merged); no console warnings.
+- You can share a build; the featured-builds surface is live and links back into worlds.
+- Verified in a real browser with a large build. Diff self-reviewed per the R00 / CLAUDE.md DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-4/R21-cosmetics-catalog-shop-ui.md b/docs/agent-briefs/R-3d-world-fun/phase-4/R21-cosmetics-catalog-shop-ui.md
new file mode 100644
index 000000000..44bc08f83
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-4/R21-cosmetics-catalog-shop-ui.md
@@ -0,0 +1,40 @@
+# R21 — Cosmetics catalog + shop UI
+
+**Phase 4 (Avatar economy) · Depends on: R03 · Unblocks: R22**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. Real endpoint, no sample arrays. Coin references are `$THREE` only. Live preview via R03.
+
+## Goal
+
+Define a cosmetics catalog and a shop UI to browse it, filter by rarity, and **preview cosmetics
+live on your own avatar** before buying — with correct owned vs locked states.
+
+## Files
+
+- A real catalog source — a JSON/API endpoint under `api/` (or the existing data pattern) covering
+ the accessory GLBs in `public/accessories/` + a set of premium emotes/skins. Each item:
+ `id, name, slot, price, rarity, previewImage`. No hardcoded sample arrays in the client.
+- `src/game/coincommunities-ui.js` (or a dedicated shop module) — the shop UI.
+- `src/game/coincommunities.css` — shop styling using the existing `cc-*` tokens.
+- `src/game/coincommunities.js` — live preview hook calling R03's `equipCosmetic` / `unequip`.
+
+## Spec
+
+1. **Catalog** — a real endpoint returns the catalog (accessory GLBs + premium emotes/skins) with
+ `id, name, slot, price, rarity, previewImage`. Client fetches it; no sample fallback array.
+2. **Shop UI** — browse the catalog, filter by rarity, matching the `cc-*` design tokens. Items show
+ hover/active/focus; designed empty/loading (skeletons)/error states.
+3. **Live preview** — selecting an item previews it **live on your own avatar** using the R03 rig
+ (`equipCosmetic`), and reverts on deselect (`unequip`). Preview does not persist a purchase.
+4. **Owned vs locked** — items already owned show as owned; not-yet-owned show locked with price.
+ (Ownership read is wired to real state in R23; here, read whatever ownership source exists and
+ degrade gracefully if empty.)
+5. **Prices** — denominated for the R22 x402 flow. Any coin reference is `$THREE` only.
+
+## Definition of done
+
+- Catalog loads from a real endpoint (no sample array); live preview works on your avatar and
+ reverts cleanly.
+- Owned/locked states correct; rarity filter works; polished empty/loading/error states.
+- No console errors/warnings. Verified in a real browser. Diff self-reviewed per the R00 / CLAUDE.md DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-4/R22-x402-purchase-flow.md b/docs/agent-briefs/R-3d-world-fun/phase-4/R22-x402-purchase-flow.md
new file mode 100644
index 000000000..e5a08b080
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-4/R22-x402-purchase-flow.md
@@ -0,0 +1,41 @@
+# R22 — x402 purchase flow
+
+**Phase 4 (Avatar economy) · Depends on: R21 · Unblocks: R23, R25 · Real payment rail**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. **Real USDC via x402 — no fake "purchased" toasts.** Reuse `api/x402/` + `agent-payments-sdk/`.
+
+## Goal
+
+Wire real purchases: buying a cosmetic triggers an x402 USDC payment, and on success records
+ownership to the player's account/wallet. Handle every payment state honestly at the boundary.
+
+## Files
+
+- `api/x402/` — a cosmetic-purchase endpoint following the existing x402 handler patterns in this
+ folder (e.g. `dance-tip.js`, `asset-download.js`). Reuse `agent-payments-sdk/` for the payment
+ build/verify.
+- A real ownership record store — use the same persistence the rest of the economy uses (inspect;
+ no new provider). Record `(account/wallet, cosmeticId)` on verified payment.
+- `src/game/` shop module from R21 — invoke the x402 flow on "Buy" and react to each state.
+
+## Spec
+
+1. **Buy → x402** — clicking Buy initiates a real x402 USDC payment for the item's price, reusing
+ `api/x402/` + `agent-payments-sdk/`. Follow the existing x402 request/verify contract (see memory
+ `sdk-agentclient-x402-contract` and the sibling handlers).
+2. **On success** — verify the payment server-side, then record ownership to the player's
+ account/wallet in the real store. Ownership must be readable by R21 (owned state) and R23
+ (inventory).
+3. **Honest states at the boundary** — handle and surface: pending, success, failure, and
+ insufficient-funds. No optimistic "purchased" toast before the payment verifies.
+4. **No double-charge / replay** — idempotent on the payment proof (see the x402 hardening invariants
+ in memory `x402-security-hardening`): proof-bound idempotency, fail-closed defaults.
+5. **$THREE only** in any coin-facing copy; USDC is the payment asset via x402.
+
+## Definition of done
+
+- A real USDC payment unlocks the cosmetic; ownership persists and is readable downstream.
+- All payment states (pending/success/failure/insufficient-funds) are handled and surfaced
+ honestly; no fake toasts; idempotent against replay.
+- Verified end-to-end against the real x402 rail. Diff self-reviewed per the R00 / CLAUDE.md DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-4/R23-owned-inventory-equip-persistence.md b/docs/agent-briefs/R-3d-world-fun/phase-4/R23-owned-inventory-equip-persistence.md
new file mode 100644
index 000000000..387b068ed
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-4/R23-owned-inventory-equip-persistence.md
@@ -0,0 +1,41 @@
+# R23 — Owned-cosmetics inventory + equip persistence
+
+**Phase 4 (Avatar economy) · Depends on: R03, R22**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. Ties the R03 rig to durable ownership — equip state persists across sessions AND worlds.
+
+## Goal
+
+A "My Cosmetics" inventory of owned items; equipping persists to the account and re-applies on next
+login and across worlds (`/play` and `/walk`).
+
+## Files
+
+- `src/game/` — a "My Cosmetics" inventory UI (or shop tab) reading the R22 ownership store.
+- The account/equip persistence store (same provider the economy uses) — save equipped slot→item.
+- `src/game/coincommunities.js` and the `/walk` avatar build path — restore equipped cosmetics on
+ load via the R03 `equipCosmetic`.
+- `multiplayer/src/rooms/WalkRoom.js` — ensure restored equip state syncs to other players via the
+ R03 `cosmetics` field.
+
+## Spec
+
+1. **Inventory UI** — "My Cosmetics" lists owned items (from the R22 ownership store) with
+ equipped/unequipped state, rarity, and preview. Designed empty (nothing owned → links to shop)/
+ loading/error states.
+2. **Equip persistence** — equipping writes the equipped slot→item to the account store. On next
+ login, equipped cosmetics are restored automatically via the R03 rig.
+3. **Cross-world** — equip state applies in **both** `/play` and `/walk` (and any world using the
+ shared avatar build path), not just the world it was set in.
+4. **Sync** — restored equip state propagates to other players through the R03 `cosmetics` schema
+ field so everyone sees your fit.
+5. **Consistency** — owned-only can be equipped; unequip persists too; no orphaned attachments on
+ re-login or world switch.
+
+## Definition of done
+
+- Owned cosmetics persist across sessions and worlds; equip state is restored on login; equipping
+ is reflected to other players.
+- Inventory states (empty/loading/error) designed and helpful. No console errors/warnings, no leaks.
+- Verified across a logout/login and a `/play`↔`/walk` switch with two clients. Diff self-reviewed per DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-4/R24-token-gated-worlds.md b/docs/agent-briefs/R-3d-world-fun/phase-4/R24-token-gated-worlds.md
new file mode 100644
index 000000000..c853b1bc9
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-4/R24-token-gated-worlds.md
@@ -0,0 +1,44 @@
+# R24 — Token-gated worlds
+
+**Phase 4 (Avatar economy) · Depends on: existing Solana rails · Server-authoritative balance check**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. Gate against **real on-chain balances** via `solana-agent-sdk/` / RPC. Non-gated worlds unaffected.
+
+## Goal
+
+Let a coin's world optionally require holding the coin to enter. Server-side balance check at join,
+a creator-set threshold per coin, and a clear, actionable client gate screen for users who don't
+qualify.
+
+## Files
+
+- `multiplayer/src/rooms/WalkRoom.js` — on join, read the coin's gating config and check the
+ joining wallet's on-chain balance; reject (with a typed reason) if below threshold.
+- Gating config store — per-coin, creator-set threshold (use the existing per-coin config/economy
+ store; no new provider).
+- `src/game/coincommunities.js` / UI — the gate screen shown when a join is rejected.
+- `solana-agent-sdk/` / RPC — the balance read.
+
+## Spec
+
+1. **Per-coin config** — a creator-set threshold (hold ≥ X of the coin to enter). Default is
+ **ungated** — existing worlds are unaffected unless a creator opts in.
+2. **Server check at join** — when a wallet joins a gated room, the server reads its **real on-chain
+ balance** (via `solana-agent-sdk/` / RPC) and rejects the join with a typed reason if below the
+ threshold. Never trust a client-claimed balance.
+3. **Gate screen** — for users who don't qualify, a clear, helpful screen: "Hold X $THREE to enter —
+ buy here", linking the existing pump swap so they can acquire the coin and retry. (Generic
+ coin-agnostic worlds use the world's own coin; surface `$THREE` only where this platform's coin
+ is referenced.)
+4. **Retry** — after acquiring, the user can re-attempt join and pass without a reload friction wall.
+5. **Robustness** — RPC failure is handled at the boundary (don't hard-fail the whole world; surface
+ a retry); no false rejects from transient RPC errors.
+
+## Definition of done
+
+- Gating works against real on-chain balances; the gate screen is helpful and actionable (links the
+ real swap); non-gated worlds are completely unaffected.
+- Balance check is server-side; RPC errors handled gracefully. No console/server errors.
+- Verified: a qualifying wallet enters, a non-qualifying one is gated and can buy + retry.
+ Diff self-reviewed per the R00 / CLAUDE.md DoD.
diff --git a/docs/agent-briefs/R-3d-world-fun/phase-4/R25-creator-revenue-splits.md b/docs/agent-briefs/R-3d-world-fun/phase-4/R25-creator-revenue-splits.md
new file mode 100644
index 000000000..d675e70af
--- /dev/null
+++ b/docs/agent-briefs/R-3d-world-fun/phase-4/R25-creator-revenue-splits.md
@@ -0,0 +1,44 @@
+# R25 — Creator revenue splits + economy polish
+
+**Phase 4 (Avatar economy) · Depends on: R22 · Real payouts**
+
+> Read [`../R00-program-overview.md`](../R00-program-overview.md) and [`CLAUDE.md`](../../../../CLAUDE.md)
+> first. **Revenue splits must pay out for real** — no simulated earnings. Reuse the R22 x402 rail.
+
+## Goal
+
+On cosmetic sales tied to a coin, split x402 revenue to the coin creator's wallet (configurable %),
+with a creator earnings view in the dashboard. Plus a platform-wide cosmetics leaderboard /
+"rarest fits" flex surface to drive the Roblox-style status loop.
+
+## Files
+
+- `api/x402/` — extend the R22 purchase handler to split the settled payment to the coin creator's
+ wallet by a configurable percentage (real on-chain transfer / settlement, reusing the existing
+ payout rails in `agent-payments-sdk/` / `solana-agent-sdk/`).
+- Split config store — configurable % per coin (existing per-coin config; no new provider).
+- Dashboard — a creator earnings view (reuse the existing dashboard patterns; see memory
+ `studio-fees-rewards` for the fee/earnings UI precedent).
+- A leaderboard endpoint + a "rarest fits" surface in `/play` UI.
+
+## Spec
+
+1. **Split on sale** — when a cosmetic tied to a coin sells via R22, split the revenue to the coin
+ creator's wallet by a configurable percentage. The split is a **real** transfer/settlement — no
+ simulated balance.
+2. **Configurable %** — per-coin split percentage (sane default, creator-adjustable), stored in the
+ existing config layer.
+3. **Creator earnings view** — a dashboard view showing real earnings from cosmetic sales, matching
+ the existing dashboard design + the fee-claim precedent in `studio-fees-rewards`.
+4. **Leaderboard / rarest fits** — a platform-wide cosmetics leaderboard and a "rarest fits" flex
+ surface that drives status; it links back into the worlds where those cosmetics are worn.
+5. **Honesty** — only real, settled numbers are shown; designed empty/loading/error states. `$THREE`
+ only in coin-facing copy.
+
+## Definition of done
+
+- Revenue splits pay out for real to the creator wallet; the creator can see real earnings in the
+ dashboard.
+- The flex/leaderboard surface is live, accurate, and links back into worlds.
+- All states designed; no simulated numbers. Verified end-to-end against the real rail.
+ Diff self-reviewed per the R00 / CLAUDE.md DoD.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/README.md b/docs/agent-briefs/X-prod-errors-2026-06-05/README.md
new file mode 100644
index 000000000..c8734ccde
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/README.md
@@ -0,0 +1,48 @@
+# Production Error Remediation — 2026-06-05
+
+Source: `3dagent-log-export-2026-06-05T10-18-30.json` (Vercel function logs, project `three.ws`).
+Window: **2026-06-04 10:19 UTC → 2026-06-05 10:18 UTC** (24h).
+Volume: **5,945 log lines** — 2,571 `error`, 563 `warning`, plus status-code rollups
+(965×200, 4,030×500, 948×502).
+
+Every line in the export traces back to **~12 distinct root causes**. This document
+groups them, names the source of each, and ships a self-contained fix prompt per issue
+under [`prompts/`](prompts/). Each prompt is written to be handed to one agent and
+executed end-to-end — trace to source, fix properly, wire 100%, verify. No suppression,
+no swallowing errors, no shortcuts.
+
+## How to use this
+
+1. Work the prompts in **priority order** (P0 → P2). P0 issues are taking whole
+ functions down (HTTP 500/502) and dwarf everything else by volume.
+2. One agent per prompt file. Each prompt is the agent's complete brief.
+3. After each fix: the agent must reproduce-or-prove the failure path, fix at the
+ source, redeploy/verify, and confirm the specific log signature can no longer occur.
+4. Push to **both** remotes only on explicit user approval (see `CLAUDE.md`).
+
+## Severity ledger (by blast radius, not just count)
+
+| # | Prompt | Root cause | Endpoints hit | ~Lines | Sev |
+|---|--------|-----------|---------------|-------:|-----|
+| 01 | [`01-jsdom-esm-require-crash.md`](prompts/01-jsdom-esm-require-crash.md) | `jsdom → html-encoding-sniffer → @exodus/bytes` `ERR_REQUIRE_ESM` crashes the bundled function at load | widgets `stats`, `transcripts`, `knowledge`, `chat` | **1,242** | **P0** |
+| 02 | [`02-upstash-request-limit.md`](prompts/02-upstash-request-limit.md) | Upstash Redis monthly request cap (500k) exhausted → every Redis-backed route 500s | explore, marketplace, agents, auth, solana-rpc, +15 more | **737** | **P0** |
+| 03 | [`03-chat-provider-exhaustion.md`](prompts/03-chat-provider-exhaustion.md) | All LLM fallback routes 429/quota-exhausted; OpenAI billing quota hit; free OpenRouter models rate-limited | `/api/chat`, `/api/llm/anthropic` | ~700 | **P0** |
+| 04 | [`04-missing-db-tables.md`](prompts/04-missing-db-tables.md) | Prod DB missing tables: `forge_creations`, `usage_events` (migrations/schema not applied) | forge-gallery, agents/[id] | ~25 | **P1** |
+| 05 | [`05-birdeye-geckoterminal-429.md`](prompts/05-birdeye-geckoterminal-429.md) | Birdeye + GeckoTerminal 429 (no cache/backoff/key) | three-token, ibm/oracle | ~175 | **P1** |
+| 06 | [`06-brain-chat-openrouter-credits.md`](prompts/06-brain-chat-openrouter-credits.md) | `/api/brain/chat` OpenRouter free-tier credit ceiling + invalid Responses-API payloads | `/api/brain/chat` | ~95 | **P1** |
+| 07 | [`07-token-treasury-wallet-unset.md`](prompts/07-token-treasury-wallet-unset.md) | `THREE_TREASURY_WALLET` unset in prod → `/api/token/config` throws (fail-closed, correct, but unconfigured) | `/api/token/[action]` | 18 | **P1** |
+| 08 | [`08-cron-eth-rpc-failures.md`](prompts/08-cron-eth-rpc-failures.md) | `index-delegations` cron: public ETH RPCs 429 / `eth_getLogs` unsupported / time-budget exceeded | `/api/cron/index-delegations` | ~40 | **P1** |
+| 09 | [`09-pump-launch-wasm-and-tx.md`](prompts/09-pump-launch-wasm-and-tx.md) | `/api/pump/launch-agent`: missing bundled `vanity_grinder_bg.wasm`; `encoding overruns Uint8Array` tx serialize; 30s timeouts | `/api/pump/[action]` | ~16 | **P1** |
+| 10 | [`10-skills-pricing-neon-transaction.md`](prompts/10-skills-pricing-neon-transaction.md) | `db.transaction()` called with wrong arg shape (Neon serverless contract) | `/api/agents/[id]/skills-pricing` | 4 | **P2** |
+| 11 | [`11-og-and-url-edge-cases.md`](prompts/11-og-and-url-edge-cases.md) | `/api/play-og` Invalid URL; `agent-og` `:id` literal passed to uuid; `x402-pay/og` Fontconfig | play-og, agent-og, x402-pay/og | ~5 | **P2** |
+| 12 | [`12-misc-data-integrity.md`](prompts/12-misc-data-integrity.md) | `explore` NUL byte in UTF8 insert; `llm/anthropic` double body-read; `tts/edge` ws 200 mishandle | explore, llm/anthropic, tts/edge | ~5 | **P2** |
+
+## Cross-cutting note
+
+Two P0s (01, 02) are responsible for the overwhelming majority of the 500/502 volume.
+Fixing those two will quiet ~2,000 of the ~2,571 error lines. Do them first.
+
+Issue 03 (LLM provider exhaustion) is partly operational (quota/billing) but the logs
+also reveal **fixable** routing bugs (a free model with no tool-capable endpoint is
+retried blindly; `brain/chat` sends payloads the Responses API rejects). The prompts
+separate "add credits" (ops) from "fix the routing" (code) so the code half can ship.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/01-jsdom-esm-require-crash.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/01-jsdom-esm-require-crash.md
new file mode 100644
index 000000000..3513c2184
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/01-jsdom-esm-require-crash.md
@@ -0,0 +1,74 @@
+# Fix 01 — `ERR_REQUIRE_ESM` crashing the widgets function (P0, ~1,242 lines)
+
+## The error (verbatim from prod)
+
+```
+Error [ERR_REQUIRE_ESM]: require() of ES Module
+/var/task/node_modules/@exodus/bytes/encoding-lite.js
+from /var/task/node_modules/html-encoding-sniffer/lib/html-encoding-sniffer.js
+not supported.
+... code: 'ERR_REQUIRE_ESM'
+Node.js process exited with exit status: 1.
+```
+
+Endpoints affected (all return **500**, the process *exits*, so it also poisons sibling
+handlers in the same bundle):
+- `/api/widgets/[id]/stats` (607)
+- `/api/widgets/[id]/transcripts` (562)
+- `/api/widgets/[id]/knowledge` (41)
+- `/api/widgets/[id]/chat` (31)
+
+## Root cause
+
+The widgets function bundle pulls in `jsdom` (via `api/_lib/text-extract.js`, imported by
+the knowledge-ingest path). `jsdom`'s transitive dep `html-encoding-sniffer` does a
+**CommonJS `require()`** of `@exodus/bytes/encoding-lite.js`, which is **ESM-only** in the
+version resolved on the deployed Node runtime. At cold start the bundler/runtime evaluates
+the `require`, throws `ERR_REQUIRE_ESM`, and the **entire serverless function exits(1)** —
+which is why `stats` and `transcripts` (which don't even need jsdom) die too.
+
+There is already a comment in `api/widgets/[id]/[action].js` (lines ~23-25) acknowledging
+this and *intending* to lazy-load `_knowledge.js`. The lazy-load is **not actually
+preventing the crash** — the dependency is still reachable at module-eval / bundle time, so
+verify whether the import is truly deferred or whether Vercel NFT is hoisting it.
+
+## Required fix (trace to source, no shortcuts)
+
+1. **Confirm the real entry point.** In `api/widgets/[id]/[action].js`, trace exactly how
+ `jsdom` enters the bundle for `stats`/`transcripts`. Map the import chain:
+ `[action].js → ? → _knowledge.js → text-extract.js → jsdom → html-encoding-sniffer → @exodus/bytes`.
+ Determine whether it's a static `import`, a hoisted dynamic `import()`, or NFT including
+ it regardless.
+2. **Pick the proper fix, not suppression:**
+ - **Preferred:** eliminate the broken require chain. Pin `@exodus/bytes` (and/or
+ `html-encoding-sniffer`) to a version pair that is internally consistent (CJS-requires-CJS
+ or ESM-imports-ESM) for the deployed Node version. Check `npm ls @exodus/bytes
+ html-encoding-sniffer jsdom whatwg-encoding` and resolve the mismatch at the dependency
+ level. This makes the crash impossible, everywhere.
+ - **If a clean version pin isn't available:** replace `jsdom` for our HTML→text extraction
+ with a lighter, ESM-clean parser. We only use it in `text-extract.js` (`new JSDOM(raw)`
+ then DOM text walk). `@mozilla/readability` needs a DOM, but a `linkedom` or
+ `node-html-parser` based extractor would remove the entire `jsdom` chain. If you swap,
+ reproduce the exact extraction output (readable text, same fields) — no quality
+ regression.
+ - **Genuinely defer** the heavy path: make `stats` and `transcripts` provably independent
+ of the jsdom chain so they can never be taken down by knowledge-ingest, even if ingest
+ itself still needs work. A crash in `knowledge` must not 500 `stats`.
+3. **Do not** wrap the require in try/catch and call it fixed — that hides a broken bundle.
+ The bundle must not contain a `require()` of an ESM module on the deployed runtime.
+
+## Verification (must do all)
+
+- `npm ls @exodus/bytes html-encoding-sniffer jsdom` shows a consistent, resolvable tree.
+- Build the widgets function locally the way Vercel does (or `vercel build`) and confirm no
+ `ERR_REQUIRE_ESM` at function init.
+- Hit `/api/widgets/<real-id>/stats`, `/transcripts`, `/knowledge`, `/chat` against a deploy
+ preview — all return their real payloads, not 500.
+- Exercise the **knowledge ingest** path (the one that genuinely uses HTML extraction) and
+ confirm text extraction still produces correct readable text.
+- Grep new logs after deploy: zero `ERR_REQUIRE_ESM`.
+
+## Definition of done
+
+All four widget sub-routes return real data, the HTML→text extraction still works on a real
+page, the dependency tree is internally consistent, and the crash signature cannot recur.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/02-upstash-request-limit.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/02-upstash-request-limit.md
new file mode 100644
index 000000000..c1f873493
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/02-upstash-request-limit.md
@@ -0,0 +1,69 @@
+# Fix 02 — Upstash Redis request limit exhausted (P0, ~737 lines)
+
+## The error (verbatim)
+
+```
+[api] unhandled UpstashError: Command failed:
+ERR max requests limit exceeded. Limit: 500000, Usage: 500000.
+See https://upstash.com/docs/redis/troubleshooting/max_request_limit_exceeded
+```
+
+Returns **500** on **every Redis-backed route**: `/api/explore`, `/api/marketplace/[action]`,
+`/api/agents/[id]`, `/api/agents/[id]/skill-access`, `/api/auth/*`, `/api/solana-rpc`,
+`/api/pump/*`, `/api/notifications`, `/api/community/*`, `/api/friends/presence-ticket`,
+`/api/avatars/[id]`, `/api/widgets`, `/api/permissions/*`, `/api/erc8004/*`,
+`/api/users/me/purchased-skills`, and more. The cap is account-wide so it takes down the
+whole platform's caching/rate-limit/session layer at once.
+
+## Root cause
+
+Two compounding problems:
+1. **Operational:** the Upstash plan's monthly request quota (500k) is fully consumed.
+2. **Code-level (the part we fix here):** we are spending Redis requests far too liberally —
+ the volume that burned 500k commands in a month points at missing caching discipline:
+ per-request `GET`s with no in-memory/edge memoization, rate-limit checks on read paths,
+ chatty multi-command flows where a pipeline would do, and **hard failures when Redis is
+ unavailable** instead of degrading gracefully.
+
+## Required fix (both halves — code first, it's the durable one)
+
+### A. Fail open, never 500, when Redis is the dependency-not-the-payload
+Audit the shared Redis client (the module every `[api] unhandled UpstashError` flows
+through — find it: `grep -rln "UpstashError\|@upstash/redis\|Redis.fromEnv\|new Redis" api/_lib`).
+- Cache reads (`explore`, `marketplace`, `agents`, `pump/trending`, token caches): on any
+ Redis error, **fall through to the source of truth** (DB / upstream API) and serve the
+ request. A cache miss is not a 500.
+- Rate-limit checks: on Redis error, **fail open** (allow the request) — never block real
+ users because the limiter backend is down. Log once, don't throw.
+- Session/auth: where Redis backs nonce/session, surface a clean 503 with retry semantics,
+ not an unhandled 500, and only where Redis is genuinely required for correctness.
+- The goal: a Redis outage degrades performance, it does **not** take the API down.
+
+### B. Stop burning requests
+- **Memoize hot reads** in function memory with a short TTL (e.g. trending, token config,
+ marketplace listings) so repeated calls within a warm instance don't each hit Redis.
+- **Pipeline / batch** multi-key flows (`MGET`, `redis.pipeline()`) instead of N round-trips.
+- **Drop redundant reads:** trace `explore` (300 lines) and `marketplace` (211) — they are
+ the top burners. Confirm each Redis call is necessary; remove double-fetches and
+ read-after-write reads that can use the value already in hand.
+- **Cap rate-limit writes:** only `INCR` when actually enforcing, not on every read.
+
+### C. Operational (call out to the user, don't silently assume)
+- The plan quota is exhausted. Surface this explicitly: the user must either upgrade the
+ Upstash plan or the usage reduction in (B) must bring monthly commands under 500k.
+ Quantify the expected reduction from (B) so the user can decide.
+
+## Verification
+
+- Force the Redis client to error (temporarily point it at a bad URL locally) and confirm
+ **every** affected route still returns real data (from DB/upstream), not 500.
+- Add a counter/log of Redis commands per request for the top routes; confirm `explore` and
+ `marketplace` drop materially after memoization/pipelining.
+- After deploy, grep logs: `UpstashError ... max requests limit` no longer produces 500s —
+ at most a single warn-level "redis degraded, served from source".
+
+## Definition of done
+
+No route 500s due to Redis being unavailable or over-quota; hot reads are memoized/pipelined;
+the per-month command burn is measurably reduced; the user has the numbers to decide on plan
+upgrade. Graceful degradation is wired everywhere Redis is touched.
diff --git a/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/03-chat-provider-exhaustion.md b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/03-chat-provider-exhaustion.md
new file mode 100644
index 000000000..c8bd4766c
--- /dev/null
+++ b/docs/agent-briefs/X-prod-errors-2026-06-05/prompts/03-chat-provider-exhaustion.md
@@ -0,0 +1,73 @@
+# Fix 03 — `/api/chat` LLM provider fallback exhaustion + routing bugs (P0, ~700 lines)
+
+## The errors (verbatim samples)
+
+```
+[chat:groq] 429 — falling over to groq/llama-3.1-8b-instant: {"error":{"message":"Rate limit reached for model `llama-3.3-70b-versatile`...
+[chat:openrouter] 429 — falling over to openai/gpt-4o-mini: {"error":{"message":"Provider returned error","code":429...
+[chat:openai] 429 (final — all 4 route(s) exhausted) You exceeded your current quota, please check your plan and billing
+[chat:openrouter] meta-llama/llama-3.2-3b-instruct:free has no tool-capable endpoint — retrying without action tools
+[chat:openrouter] 404 — falling over to groq/llama-3.3-70b-versatile: {"error":{"message":"No endpoints found for mistral...
+[chat:openrouter] 403 (final — all 5 route(s) exhausted) openai/gpt-oss-120b:free requires moderation on OpenInference
+```
+
+`/api/chat` and `/api/llm/anthropic`. When the chain is fully exhausted the user gets a
+hard failure. The chain churns through 4-5 providers per request, multiplying latency and
+burning quota on every turn.
+
+## Root cause
+
+1. **Operational:** OpenAI key is over quota/billing (`exceeded your current quota`); free
+ OpenRouter models are aggressively rate-limited and some are gated (403 moderation, 404
+ no-endpoint). Groq free tier 429s under our load.
+2. **Code-level (fix these — they are real bugs, not just quota):**
+ - The fallback ladder **leads with free, rate-limited models** and only reaches paid,
+ reliable models last — so the common path is "try 4 things that fail, then succeed,"
+ paying full latency every time.
+ - Models with **no tool-capable endpoint** are placed in a tool-calling chain and only
+ discovered at call time (`has no tool-capable endpoint — retrying without action
+ tools`). The route table should *know* a model's capabilities and skip it for
+ tool-required requests instead of round-tripping.
+ - **Dead/invalid routes** are in the ladder: `mistralai/mistral-7b-instruct:free` →
+ `404 No endpoints found`; `gpt-oss-120b:free` → `403 requires moderation`. These will
+ *never* succeed and should be removed.
+
+## Required fix
+
+Find the chat routing config (`grep -rln "DEFAULT_PROVIDER_ORDER\|PROVIDER_MODEL_DEFAULTS\|falling over" api/_lib api/chat*`; see `api/_lib/chat-models.js`).
+
+1. **Reorder the ladder by reliability, not by cost-first.** Lead with a model that
+ actually answers under current quota. Keep cheaper/free models as *lower-priority*
+ fallbacks, not the primary path. Document the ordering rationale inline.
+2. **Make routing capability-aware.** Annotate each model with `{ tools: bool, moderationGated: bool }`.
+ For tool-required requests, skip non-tool models entirely instead of calling then
+ retrying-without-tools. Never call a model the request can't use.
+3. **Remove permanently-broken routes** from the table: any model returning `404 No
+ endpoints found` or `403 requires moderation` consistently. Don't carry dead weight.
+4. **Bound the chain.** Cap total fallback attempts and total wall-clock so a request can't
+ churn through 5 providers and still time out at 30s. On full exhaustion, return a clean,
+ actionable error to the client (not a stack trace), and surface *which* providers failed.
+5. **Surface the quota reality to the user (ops):** OpenAI is over quota. The user must
+ top up billing or we must not route to it as a "final" tier. State this explicitly with
+ the failing key/account so they can act.
+
+## `/api/llm/anthropic` specific (2 lines, but a real bug)
+`TypeError: Body is unusable: Body has already been read` — the upstream `Response` body is
+read twice (e.g. `.json()` then `.text()` in the error path). Read it **once** into a
+variable and reuse. See Fix 12 if scoped there; otherwise fix here.
+
+## Verification
+
+- Unit-test the route selector: a tool-required request never returns a non-tool model;
+ removed dead routes never appear; ordering is reliability-first.
+- Drive `/api/chat` with a normal prompt and a tool-using prompt — first-attempt success on
+ the primary model under normal conditions (no 4-deep fallback churn in the happy path).
+- Confirm bounded behavior: simulate all providers 429 → client gets one clean terminal
+ error within the time budget, not a 30s timeout.
+- After deploy, logs show the fallback ladder is *short* in the common case.
+
+## Definition of done
+
+Happy-path chat hits a working model first; tool requests never round-trip through
+non-tool models; dead routes are gone; exhaustion returns a clean bounded error; the user
+knows exactly which provider account needs funding.