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.

Reorganize prompt suites into phase-4-virality; refine KOL leaderboard and vault config

nirholase3ce68a9747b
diff --git a/agent-protocol-sdk/package.json b/agent-protocol-sdk/package.json
index 96b42bf3c..42470fb1f 100644
--- a/agent-protocol-sdk/package.json
+++ b/agent-protocol-sdk/package.json
@@ -14,7 +14,6 @@
},
"files": [
"dist",
- "src",
"README.md",
"LICENSE"
],
diff --git a/packages/react/LICENSE b/packages/react/LICENSE
new file mode 100644
index 000000000..8e2251ab4
--- /dev/null
+++ b/packages/react/LICENSE
@@ -0,0 +1,180 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship made available under
+ the License, as indicated by a copyright notice that is included in
+ or attached to the work (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other transformations
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
+ in the Work by the copyright owner or by an individual or Legal Entity
+ authorized to submit on behalf of the copyright owner. For the purposes
+ of this definition, "submitted" means any form of electronic, verbal,
+ or written communication sent to the Licensor or its representatives,
+ including but not limited to communication on electronic mailing lists,
+ source code control systems, and issue tracking systems that are managed
+ by, or on behalf of, the Licensor for the purpose of discussing and
+ improving the Work, but excluding communication that is conspicuously
+ marked or designated in writing by the copyright owner as "Not a
+ Contribution."
+
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
+ whom a Contribution has been received by the Licensor and included
+ within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by the combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a cross-claim
+ or counterclaim in a lawsuit) alleging that the Work or any
+ Contribution embodied within the Work constitutes direct or contributory
+ patent infringement, then any patent licenses granted to You under
+ this License for that Work shall terminate as of the date such
+ litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or Derivative
+ Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, You must include a readable copy of the
+ attribution notices contained within such NOTICE file, in
+ at least one of the following places: within a NOTICE text
+ file distributed as part of the Derivative Works; within
+ the Source form or documentation, if provided along with the
+ Derivative Works; or, within a display generated by the
+ Derivative Works, if and wherever such third-party notices
+ normally appear. The contents of the NOTICE file are for
+ informational purposes only and do not modify the License.
+ You may add Your own attribution notices within Derivative
+ Works that You distribute, alongside or in addition to the
+ NOTICE text from the Work, provided that such additional
+ attribution notices cannot be construed as modifying the License.
+
+ You may add Your own license statement for Your modifications and
+ may provide additional grant of rights to use, copy, modify, merge,
+ publish, distribute, sublicense, and/or sell copies of the
+ Derivative Works, and to permit persons to whom the Derivative Works
+ are furnished to do so.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or reproducing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or exemplary damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or all other
+ commercial damages or losses), even if such Contributor has been
+ advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may offer only
+ conditions consistent with this License.
+
+ END OF TERMS AND CONDITIONS
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/packages/react/package.json b/packages/react/package.json
index 58fdd121b..496616060 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -7,12 +7,12 @@
"types": "dist/index.d.ts",
"exports": {
".": {
+ "types": "./dist/index.d.ts",
"import": "./dist/index.esm.js",
- "require": "./dist/index.cjs.js",
- "types": "./dist/index.d.ts"
+ "require": "./dist/index.cjs.js"
}
},
- "files": ["dist", "src"],
+ "files": ["dist", "README.md", "LICENSE"],
"sideEffects": false,
"scripts": {
"build": "vite build && node -e \"require('fs').copyFileSync('src/index.d.ts','dist/index.d.ts')\"",
@@ -37,5 +37,5 @@
"directory": "packages/react"
},
"bugs": { "url": "https://github.com/nirholas/three.ws/issues" },
- "license": "MIT"
+ "license": "Apache-2.0"
}
diff --git a/prompts/phase-4-virality/00-README.md b/prompts/phase-4-virality/00-README.md
new file mode 100644
index 000000000..d7664137d
--- /dev/null
+++ b/prompts/phase-4-virality/00-README.md
@@ -0,0 +1,131 @@
+# Phase 4 — Virality Engine (Index — DO NOT DELETE)
+
+> This file is the index and shared context for **Phase 4** of the pump.fun
+> social-trading roadmap. It is NOT a task. Do not delete it. Every numbered
+> prompt in this folder is a self-contained task for one fresh agent chat. When
+> an agent finishes a numbered task (and its self-review pass), it deletes
+> **only its own** numbered prompt file — never this README, never another's.
+
+Roadmap source of truth: `docs/roadmap/pumpfun-social-trading.md` (Prompt E,
+"Phase 4: Social loop & growth") and `docs/roadmap/pumpfun-trading.md`
+(§8, "Phase 4 — Virality engine").
+
+---
+
+## The vision
+
+Phases 0–3 built the truth: a provable, on-chain track record (the leaderboard +
+trader profiles), a non-custodial copy engine, and performance-fee settlement.
+The product is **correct and trustworthy** — but trust alone doesn't grow it.
+
+**Phase 4 makes wins spread.** Every profitable close should be a screenshot worth
+sharing, every shared card should carry a referral link, every follow should feed a
+live activity stream, and every week the platform should hand each trader a recap
+worth posting. The loop we are wiring:
+
+> a trader wins → the win renders as a beautiful, provable card → the card spreads
+> (in-app feed, Telegram, X) with a referral link → a new user lands on a profile
+> that *proves* the track record → they copy or deploy → they win → repeat.
+
+The north star for this phase: a new user can arrive from a shared card, see
+irrefutable proof, and start copying within one session — and the trader who earned
+that follow can *see* their reach (copiers gained, $THREE earned, reputation rising).
+
+This is not growth-hacking spam. Every recommendation is computed from **real copy
+data**, every badge is gated on **attested on-chain metrics**, every card shows
+**real numbers**. Proof, not promises. If a number can't be verified, it doesn't ship.
+
+---
+
+## What already exists (build ON this — do not rebuild it)
+
+Proof / track-record layer (Phases 0–1):
+- `api/sniper/leaderboard.js` — public leaderboard ranked by composite TraderScore
+ over a window; superset rows (`win_rate`, `score`, `verified`, `roi_pct`,
+ `drawdown`, recent closed trades, open positions). The shared trader-stats truth
+ layer feeds this and the profile so they can never disagree.
+- `api/sniper/trader.js` — single-trader stats; `api/sniper/history.js` — trade log.
+- `pages/leaderboard.html`, `pages/trader.html`, `pages/arena.html` — the front door.
+- `api/trader-og.js` — `GET /api/trader-og?agent_id=<uuid>`: dynamic 1200×630 SVG
+ OG card (score gauge, win rate, realized P&L, trades closed, best trade) for
+ `/trader/<id>/share`. The PnL-card work extends this language.
+- Sibling OG generators to match style: `api/og-leaderboard.js`, `api/agent-og.js`.
+
+Copy engine + fees (Phases 2–3):
+- `api/cron/copy-fanout.js`, `api/cron/mirror-fanout.js` — copy/mirror execution.
+- `api/cron/trader-score-attest.js` — on-chain attestation of TraderScore.
+- `pages/vaults.html` + vault APIs — Back-an-Agent copy vaults (the money loop).
+- `pages/feed.html` — "Your Feed" page ("Recent activity from the people and agents
+ you follow"). Currently thin — Phase 4 fills it.
+
+Referrals:
+- `api/_lib/referrals.js` — code generation/normalization/availability/claim
+ (`generateReferralCode`, `setReferralCode`, `getReferralCodeAvailability`, …).
+- `api/_lib/referral-rewards.js`, `api/_lib/activation.js` — reward/activation logic.
+- `api/_lib/migrations/20260628120000_referral_activation.sql`.
+
+Notifications & distribution:
+- `api/_lib/notify.js` — `insertNotification(userId, type, payload)`,
+ `recordEvent(...)`, `emailAllowedForType(...)`.
+- `api/_lib/notify-prefs.js`, `api/notifications/*` (index, preferences, read-all,
+ track, `[id]`), `api/_lib/email.js`.
+- Telegram delivery: `src/pump/telegram-delivery.js`, `api/pump/deliver-telegram.js`,
+ `scripts/changelog-telegram.mjs`, migrations `*_sniper_telegram_notify.sql`,
+ `*_copy_telegram.sql`, `*_oracle_watch_telegram.sql`.
+- Cron pattern to copy: `api/cron/rewards-distribute.js` (scheduled, idempotent).
+
+KOL pre-seed:
+- `api/kol/[action].js` (Birdeye/GMGN proxy), `api/kol/trades.js`,
+ `src/kol/leaderboard.js`, `src/kol/wallet-pnl.js`, `src/kol/wallets.js`,
+ `src/kol/wallets.json`, `src/kol/gmgn-parser.js`, `src/kol/kolscan-live.js`.
+
+Schema & infra:
+- `api/_lib/schema.sql` + `api/_lib/migrations/` — add new tables here (timestamped).
+- `vercel.json` — register any new cron + route.
+- `api/_lib/db.js` (`sql`), `api/_lib/http.js` (`cors`, `wrap`), `api/_lib/validate.js`.
+
+---
+
+## The prompts
+
+| # | Prompt | Builds on |
+|---|---|---|
+| 01 | PnL & trade share cards | `api/trader-og.js`, OG siblings, history |
+| 02 | The Feed (follow-graph activity + recommendations) | `pages/feed.html`, copy data |
+| 03 | Referral wiring everywhere | `api/_lib/referrals.js`, share cards |
+| 04 | Trader Wrapped — weekly recap (cron) | `rewards-distribute.js`, notify, Telegram |
+| 05 | Proven-track-record verification badge | `trader-score-attest.js`, leaderboard |
+| 06 | KOL pre-seed + "claim this profile" | `api/kol/*`, `src/kol/*`, leaderboard |
+| 07 | Telegram / X distribution bots | telegram-delivery, share cards |
+| 08 | Integration QA & polish (run last) | all of the above |
+
+Run 01 first (cards are the unit of virality everything else carries). 02–07 can run
+in parallel chats once 01 lands. Run 08 last, after the others merge.
+
+---
+
+## Global operating rules (every prompt repeats these — non-negotiable)
+
+- Read `CLAUDE.md` and `STRUCTURE.md` first; **CLAUDE.md overrides defaults.**
+- **No mocks / fake data / placeholders / TODOs / stubs.** Real APIs, real on-chain
+ data, real implementations. Every number on a card or in the feed is verifiable.
+- **$THREE is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
+ Never reference any other token anywhere — code, copy, fixtures, cards, bot posts.
+ The two runtime-data-only exceptions in CLAUDE.md still apply (user-supplied mints
+ in the launcher; platform launch directories rendering real launch records).
+- **Every state is designed** — loading (skeletons), empty (tells the user what to
+ do next), error (actionable + recoverable), populated, overflow. Mobile-first.
+- **No errors without solutions.** Ship working fallbacks and failsafes.
+- Concurrent agents share this worktree — **stage explicit paths only** (never
+ `git add -A`/`.`); re-check `git status` and `git diff --staged` before committing.
+- **esbuild trap:** never commit `api/*.js` starting with `__defProp`/`createRequire`;
+ recover with `git restore -- api/ public/`.
+- Every user-visible change → an entry in `data/changelog.json`, then
+ `npm run build:pages`. New page → the `added` date in `data/pages.json` feeds it.
+- DB changes go in a **new timestamped migration** under `api/_lib/migrations/` and
+ are reflected in `api/_lib/schema.sql`. New crons/routes → `vercel.json`.
+- Tests: `npm test` (vitest + playwright) and `npm run typecheck` must pass. Add
+ tests for new logic (truth-layer math, dedup, gating, idempotency).
+- Push to BOTH remotes when asked (`git push threeD main && git push threews main`);
+ never pull/fetch/merge from `threeD`.
+- **Definition of done = CLAUDE.md's checklist.** If you can't verify a step, say so.
diff --git a/prompts/phase-4-virality/01-pnl-share-cards.md b/prompts/phase-4-virality/01-pnl-share-cards.md
new file mode 100644
index 000000000..d5b285ab6
--- /dev/null
+++ b/prompts/phase-4-virality/01-pnl-share-cards.md
@@ -0,0 +1,64 @@
+# Phase 4 · 01 — PnL & trade share cards
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, the
+existing files, and the non-negotiable operating rules live there. This task assumes
+them.
+
+## Goal
+
+Make every win shareable. A profitable closed trade — and a trader's overall track
+record — must render as a beautiful, **provable** card that previews perfectly when
+pasted into X, Telegram, Discord, or iMessage, and that carries a referral link back
+to a page that proves the numbers. Cards are the atomic unit of virality; everything
+else in Phase 4 carries them.
+
+## Build on (do not rebuild)
+
+- `api/trader-og.js` — the existing `/api/trader-og?agent_id=` 1200×630 SVG card
+ (score gauge, win rate, realized P&L, trades closed, best trade) for
+ `/trader/<id>/share`. Extend this visual language; do not fork a new style.
+- OG siblings for consistent typography/gradients: `api/og-leaderboard.js`,
+ `api/agent-og.js`.
+- `api/sniper/history.js` / `api/sniper/trader.js` — the real closed-trade + stats
+ source. The shared trader-stats truth layer is the only number source.
+- `pages/trader.html` — where the share affordance lives.
+
+## Deliver
+
+1. **Per-trade PnL card.** A new dynamic OG endpoint (e.g. `api/trade-og.js`,
+ `GET /api/trade-og?trade=<id>`) rendering a single closed trade: coin (ticker +
+ thumbnail if available), entry/exit, ROI %, realized P&L in SOL and USD, hold
+ time, the trader's name/avatar, and a small "verified on-chain — view the tx"
+ proof line. Same dark card anatomy as `trader-og.js`. Must 404 cleanly for
+ unknown/open trades and degrade gracefully if the thumbnail is missing.
+2. **Share routes + meta.** `/trade/<id>/share` and the existing `/trader/<id>/share`
+ serve HTML with correct `og:image`, `twitter:card=summary_large_image`,
+ `og:title`/`og:description` populated from real data, plus a visible
+ human-facing card and a prominent CTA ("Copy this trader" / "See full track
+ record"). The referral link (see prompt 03) is embedded in every share URL.
+3. **One-tap share UI.** On `pages/trader.html` and anywhere a closed trade renders
+ (history rows, the feed from prompt 02), a share control that: copies the share
+ URL, opens native share sheet on mobile (`navigator.share` with graceful
+ fallback), and offers "share to X" / "copy for Telegram" intents. Hover/active/
+ focus states, keyboard-operable, ARIA-labeled.
+4. **Caching & cost.** OG endpoints set sensible cache headers (match `trader-og.js`
+ `s-maxage`/`stale-while-revalidate`), and never trigger an expensive recompute on
+ every crawler hit. SVG only — no headless browser.
+
+## Acceptance
+
+- Pasting a `/trade/<id>/share` or `/trader/<id>/share` link into a link-preview
+ validator shows the card with **real** numbers; no placeholder values.
+- The card's numbers match the trader profile exactly (same truth layer).
+- Unknown trade id, open (unclosed) trade, and missing-avatar cases all render a
+ clean state — never a broken image or a 500.
+- Share control works on mobile (native sheet) and desktop (copy + intents), with
+ full hover/active/focus states.
+- `npm test` + `npm run typecheck` green; a test asserts the OG endpoint's numbers
+ equal the trader-stats truth layer for a fixture trade.
+- `data/changelog.json` entry added (`feature`), `npm run build:pages` run.
+
+## When done
+
+Run the self-review protocol in `/CLAUDE.md`, then delete **only this file**
+(`01-pnl-share-cards.md`). Leave `00-README.md` and all other prompts intact.
diff --git a/prompts/phase-4-virality/02-the-feed.md b/prompts/phase-4-virality/02-the-feed.md
new file mode 100644
index 000000000..3fa9961dd
--- /dev/null
+++ b/prompts/phase-4-virality/02-the-feed.md
@@ -0,0 +1,60 @@
+# Phase 4 · 02 — The Feed (follow-graph activity + recommendations)
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing
+files, and non-negotiable operating rules. This task assumes them.
+
+## Goal
+
+Turn `pages/feed.html` from a thin shell into the platform's living activity stream:
+a real-time, mobile-first feed of what the traders and agents you follow (and copy)
+are doing — scoped to **your** follow graph — plus recommendations computed from
+**real copy data**, not influencer noise. The feed is where shared cards (prompt 01)
+get their second life and where "who should I copy next" gets answered honestly.
+
+## Build on (do not rebuild)
+
+- `pages/feed.html` — "Your Feed" page already exists ("Recent activity from the
+ people and agents you follow"). Fill it; keep the route.
+- `api/sniper/leaderboard.js`, `api/sniper/history.js`, `api/sniper/trader.js` — the
+ trade + stats truth layer.
+- Copy data from the copy engine (`api/cron/copy-fanout.js`,
+ `api/cron/mirror-fanout.js` and their tables) — the source for "who copies whom".
+- `api/_lib/db.js`, `api/_lib/http.js`, `api/_lib/validate.js`.
+- PnL/trade cards from prompt 01 — feed items embed/link them.
+
+## Deliver
+
+1. **Feed API.** `GET /api/feed?cursor=…` returning the authenticated user's
+ follow-graph activity (followed/copied traders' opens, closes, big wins, vault
+ deposits/withdrawals, graduations), newest first, cursor-paginated. Each item
+ carries enough to render without an N+1 fan-out. IP + auth rate-limited.
+2. **Recommendations from real copy data.** A "traders you follow also copy X"
+ strip computed from the actual copy graph (co-copy / collaborative signal), not a
+ hardcoded list. Exclude already-followed traders; rank by a defensible signal
+ (co-copy count × recent realized PnL). Show *why* it's recommended ("copied by 4
+ traders you follow").
+3. **Feed UI.** Render in `pages/feed.html`: trade-close items show the PnL card
+ inline with a share control (prompt 01); each item links to the trader profile and
+ a one-tap "Copy" / "Back this agent" CTA. Live updates via the existing stream
+ mechanism if one is wired (e.g. `api/sniper/stream.js`/`trades-stream.js`),
+ otherwise poll-on-focus — no fake "live" indicator without a real source.
+4. **Every state designed.** Empty (not following anyone yet → surface the
+ leaderboard + top recommendations as the onboarding path), loading (skeleton
+ rows), error (retry), overflow (long names/large numbers truncate cleanly),
+ end-of-feed.
+
+## Acceptance
+
+- The feed shows only the signed-in user's graph; a fresh account with no follows
+ gets the designed empty/onboarding state, not a blank page.
+- Recommendations are reproducibly derived from real copy rows (a test asserts the
+ ranking against a fixture copy graph); no hardcoded trader arrays.
+- Pagination is stable under new inserts (cursor, not offset); no dupes/skips.
+- Mobile-first; hover/active/focus on every interactive element; keyboard navigable.
+- `npm test` + `npm run typecheck` green. `data/changelog.json` entry (`feature`);
+ `npm run build:pages` run.
+
+## When done
+
+Run the `/CLAUDE.md` self-review protocol, then delete **only this file**
+(`02-the-feed.md`).
diff --git a/prompts/phase-4-virality/03-referral-wiring.md b/prompts/phase-4-virality/03-referral-wiring.md
new file mode 100644
index 000000000..2ca68334a
--- /dev/null
+++ b/prompts/phase-4-virality/03-referral-wiring.md
@@ -0,0 +1,57 @@
+# Phase 4 · 03 — Referral wiring everywhere
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing
+files, non-negotiable rules. This task assumes them.
+
+## Goal
+
+The referral primitives exist but are not woven into the viral surfaces. Wire them so
+**every shared card, every invite, every win** carries the sharer's referral code,
+attribution survives the signup → activation → copy journey, and the referrer can
+*see* their reach and earnings. Referrals are how a shared card converts into a
+tracked, rewardable new user.
+
+## Build on (do not rebuild)
+
+- `api/_lib/referrals.js` — `generateReferralCode`, `normalizeReferralCode`,
+ `getReferralCodeAvailability`, `setReferralCode`, code regex/reserved checks.
+- `api/_lib/referral-rewards.js`, `api/_lib/activation.js` — reward + activation.
+- `api/_lib/migrations/20260628120000_referral_activation.sql` — existing schema.
+- Share cards/routes from prompt 01; the feed from prompt 02; notifications
+ (`api/_lib/notify.js`).
+
+## Deliver
+
+1. **Code in every share link.** Every share URL produced in prompt 01/02 and across
+ profiles, leaderboard, vaults, and the feed embeds the signed-in user's referral
+ code (e.g. `?ref=<code>`). Anonymous/logged-out sharers fall back to a neutral
+ link (no broken `?ref=undefined`).
+2. **Attribution capture & persistence.** Landing with `?ref=` captures the code
+ (cookie/storage), survives navigation, and is bound to the new account at signup —
+ then to activation (first copy / first vault deposit / first deploy) via
+ `activation.js`. Self-referral and code re-binding are rejected. No double-credit.
+3. **"Your referral code" surface.** A real UI (settings/profile) to claim a custom
+ code (`getReferralCodeAvailability` + `setReferralCode`), copy the link, and see a
+ QR. Validation messages for taken/reserved/invalid codes, all states designed.
+4. **Earnings & reach dashboard.** Show the referrer their funnel from real data:
+ clicks → signups → activations → $THREE earned (from `referral-rewards.js`). No
+ vanity numbers — every figure traces to a row. Notify on a successful activation
+ ("X joined from your link and made their first copy").
+5. **Reward integrity.** Rewards are idempotent and only fire on genuine activation,
+ not signup. Document the split/rules inline where they're computed.
+
+## Acceptance
+
+- A shared card link carries the sharer's code; following it through signup +
+ first-copy credits the referrer exactly once (test covers the full chain +
+ self-referral rejection + idempotency).
+- Custom-code claim flow handles taken/reserved/invalid with designed states.
+- Earnings dashboard numbers reconcile to `referral-rewards.js` rows.
+- `$THREE` is the only token referenced in any reward copy.
+- `npm test` + `npm run typecheck` green. `data/changelog.json` entry
+ (`feature`/`improvement`); `npm run build:pages` run.
+
+## When done
+
+Run the `/CLAUDE.md` self-review protocol, then delete **only this file**
+(`03-referral-wiring.md`).
diff --git a/prompts/phase-4-virality/04-trader-wrapped-recap.md b/prompts/phase-4-virality/04-trader-wrapped-recap.md
new file mode 100644
index 000000000..aa9b7ab7c
--- /dev/null
+++ b/prompts/phase-4-virality/04-trader-wrapped-recap.md
@@ -0,0 +1,59 @@
+# Phase 4 · 04 — Trader Wrapped (weekly recap)
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing
+files, non-negotiable rules. This task assumes them.
+
+## Goal
+
+Once a week, hand every active trader a recap worth posting: their best calls,
+copiers gained, $THREE earned, reputation movement — delivered in-app and (opt-in)
+to Telegram, each with a one-tap share card (prompt 01) carrying their referral link
+(prompt 03). This is recurring, self-propagating content: the platform manufactures a
+shareable moment for every trader, every week.
+
+## Build on (do not rebuild)
+
+- `api/cron/rewards-distribute.js` — the canonical scheduled, idempotent cron
+ pattern. Copy its structure (windowing, idempotency key, batch, logging).
+- `api/_lib/notify.js` (`insertNotification`), `api/_lib/notify-prefs.js`,
+ `api/notifications/*` — in-app delivery + per-type prefs.
+- `src/pump/telegram-delivery.js`, `api/pump/deliver-telegram.js` — Telegram delivery.
+- The trader-stats truth layer (`api/sniper/trader.js`/`history.js`) — recap numbers.
+- Share-card endpoints from prompt 01; referral link from prompt 03.
+- `vercel.json` — register the new weekly cron.
+
+## Deliver
+
+1. **Recap computation.** A function that, for a given week window, computes per
+ active trader: best trade(s), realized PnL, win rate delta vs prior week, copiers
+ gained/lost, $THREE earned (perf fees + referrals), reputation/score movement, and
+ a headline ("Your sharpest week yet" / "First week in the green"). All from real
+ rows; skip traders with no activity (no empty "you did nothing" spam).
+2. **Weekly cron.** `api/cron/trader-wrapped.js` registered in `vercel.json`,
+ idempotent per (trader, week) so a re-run never double-sends. Batched, with
+ structured logging and a dead-letter-safe path on partial failure.
+3. **In-app recap.** A notification (`insertNotification`) linking to a recap view
+ (a `/wrapped/<week>` route or modal) that renders the week as a designed,
+ screenshot-worthy card with a share control + referral link. Respects notify-prefs.
+4. **Telegram recap.** Opt-in delivery via the existing Telegram path to traders who
+ linked Telegram, gated on their notification preferences. Plain-language, links
+ back with `?ref=`.
+5. **Idempotency & cost.** One recap per trader per week; cron is cheap (aggregate
+ queries, not per-trader fan-out where avoidable).
+
+## Acceptance
+
+- Running the cron twice for the same week sends exactly one recap per trader (test
+ asserts idempotency key behavior).
+- Recap numbers reconcile to the trader-stats truth layer; inactive traders are
+ skipped, not spammed.
+- Telegram delivery only to opted-in, linked traders; in-app respects notify-prefs.
+- Recap card is mobile-first, fully designed, shareable with referral link embedded.
+- `$THREE` is the only token in any recap copy.
+- `npm test` + `npm run typecheck` green. `data/changelog.json` entry (`feature`);
+ `npm run build:pages` run. New cron present in `vercel.json`.
+
+## When done
+
+Run the `/CLAUDE.md` self-review protocol, then delete **only this file**
+(`04-trader-wrapped-recap.md`).
diff --git a/prompts/phase-4-virality/05-verification-badge.md b/prompts/phase-4-virality/05-verification-badge.md
new file mode 100644
index 000000000..bc6ff88ca
--- /dev/null
+++ b/prompts/phase-4-virality/05-verification-badge.md
@@ -0,0 +1,58 @@
+# Phase 4 · 05 — Proven-track-record verification badge
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing
+files, non-negotiable rules. This task assumes them.
+
+## Goal
+
+When a shared card brings a stranger to a profile, the single most important question
+is "can I trust this track record?" Ship a **verification badge** that answers it —
+gated on attested, on-chain metrics, not self-claims — and surface it everywhere a
+trader is represented (profile, leaderboard, feed, share cards, vaults). The badge is
+the trust primitive the whole viral loop depends on; it must be impossible to fake.
+
+## Build on (do not rebuild)
+
+- `api/cron/trader-score-attest.js` — existing on-chain attestation of TraderScore.
+ The badge is gated on attested values, not raw API reads.
+- `api/sniper/leaderboard.js` / `api/sniper/trader.js` — the truth layer that exposes
+ `verified`, `win_rate`, `score`, closed-trade count, etc.
+- `api/trader-og.js` and share cards (prompt 01); leaderboard/profile/feed surfaces.
+- `api/_lib/db.js`, `api/_lib/http.js`; a new migration for any badge state.
+
+## Deliver
+
+1. **Gating rule (explicit, tested).** Define the badge eligibility from attested
+ metrics: e.g. min closed trades, min realized PnL, min unique coins traded, and a
+ wash-trading ratio below a threshold (self-trades / circular volume). Encode the
+ exact thresholds in one place, derived from attested data only. A trader who
+ degrades below threshold loses the badge — it is a live status, not a one-time
+ stamp.
+2. **Badge evaluation.** A function/endpoint that computes badge status for a trader
+ from attested rows, with the *reasons* (which criteria pass/fail) so a profile can
+ show "3/4 criteria met — needs 2 more closed trades". No badge without attestation.
+3. **Surface everywhere.** Render the badge consistently on `pages/trader.html`,
+ `pages/leaderboard.html`, the feed (prompt 02), share/OG cards (prompt 01), and
+ vault rows. One component/style; tooltip explains what it means and links to the
+ criteria.
+4. **Anti-gaming.** The wash% / circular-volume check must use real on-chain data and
+ be documented inline. Make it auditable: a profile can show the proof (tx
+ signatures) behind the verified status.
+5. **States.** Verified, eligible-soon (progress shown), not-eligible, and
+ attestation-pending all designed.
+
+## Acceptance
+
+- Badge status is computed only from attested metrics; a fixture trader below any
+ threshold is correctly denied, and losing eligibility revokes the badge (tests
+ cover each criterion boundary + wash% gate).
+- The badge renders identically across profile, leaderboard, feed, cards, vaults.
+- Tooltip/criteria view explains the gate; verified status links to on-chain proof.
+- No self-claimed or unverifiable path to the badge exists.
+- `npm test` + `npm run typecheck` green. `data/changelog.json` entry
+ (`feature`/`security`); `npm run build:pages` run.
+
+## When done
+
+Run the `/CLAUDE.md` self-review protocol, then delete **only this file**
+(`05-verification-badge.md`).
diff --git a/prompts/phase-4-virality/06-kol-claim-flow.md b/prompts/phase-4-virality/06-kol-claim-flow.md
new file mode 100644
index 000000000..0c8869717
--- /dev/null
+++ b/prompts/phase-4-virality/06-kol-claim-flow.md
@@ -0,0 +1,62 @@
+# Phase 4 · 06 — KOL pre-seed + "claim this profile"
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing
+files, non-negotiable rules. This task assumes them.
+
+## Goal
+
+Solve cold-start on the *demand* side: pre-seed the leaderboard with real, well-known
+on-chain traders (KOLs) rendered as **unclaimed** profiles built from their actual
+trade history, each with a "claim this profile" flow. New visitors arrive to a board
+full of recognizable, provable track records; the KOLs themselves have a reason to
+show up and claim. Every number is real on-chain data — no invented stats, and never
+any token other than `$THREE` referenced anywhere in copy.
+
+## Build on (do not rebuild)
+
+- `api/kol/[action].js` — Birdeye/GMGN proxy for on-chain histories.
+- `api/kol/trades.js`, `src/kol/leaderboard.js`, `src/kol/wallet-pnl.js`,
+ `src/kol/wallets.js`, `src/kol/wallets.json` (the curated wallet set),
+ `src/kol/gmgn-parser.js`, `src/kol/kolscan-live.js`.
+- `api/sniper/leaderboard.js` / `pages/leaderboard.html` — where unclaimed profiles
+ render alongside platform traders.
+- The verification-badge logic (prompt 05) and the trader-stats truth layer.
+
+## Deliver
+
+1. **Pre-seed pipeline.** Import real on-chain histories for the curated wallet set
+ (`src/kol/wallets.json`) into trader profiles flagged `unclaimed`, with stats
+ computed by the **same truth layer** as platform traders so an unclaimed KOL and a
+ real agent are ranked apples-to-apples. Cache/refresh on a schedule (reuse the
+ cron pattern); respect provider rate limits with backoff — no errors without
+ fallbacks.
+2. **Unclaimed profile rendering.** Unclaimed profiles appear on the leaderboard and
+ have their own profile view clearly marked "Unclaimed — real on-chain history" with
+ a prominent "Is this you? Claim this profile" CTA. They are watch-only (no copy
+ button until claimed, or copy points at the read-only history — your call, but
+ designed and explained).
+3. **Claim flow.** A real claim path: the wallet owner proves control (sign a message
+ with the wallet, the standard Solana ownership proof) → the profile is bound to
+ their account, badge re-evaluated, copy/vault features unlocked. Reject claims that
+ fail the signature check. One claim per wallet; no claim-jacking.
+4. **States & integrity.** Designed loading/empty/error for the import; a profile that
+ fails to import data is hidden, not shown broken. Make clear these are real public
+ histories, not endorsements.
+
+## Acceptance
+
+- Curated KOL wallets render as unclaimed profiles with real, truth-layer-consistent
+ stats; ranking is comparable to platform traders.
+- The claim flow verifies wallet ownership via signature and binds the profile;
+ forged/failed signatures are rejected (test covers verify + reject + single-claim).
+- No token other than `$THREE` is named in any KOL profile/copy; wallet addresses are
+ rendered as data, never marketed.
+- Provider failures degrade gracefully (cached/last-known or hidden), never a broken
+ card or 500.
+- `npm test` + `npm run typecheck` green. `data/changelog.json` entry (`feature`);
+ `npm run build:pages` run.
+
+## When done
+
+Run the `/CLAUDE.md` self-review protocol, then delete **only this file**
+(`06-kol-claim-flow.md`).
diff --git a/prompts/phase-4-virality/07-telegram-x-bots.md b/prompts/phase-4-virality/07-telegram-x-bots.md
new file mode 100644
index 000000000..c6a7cafd8
--- /dev/null
+++ b/prompts/phase-4-virality/07-telegram-x-bots.md
@@ -0,0 +1,58 @@
+# Phase 4 · 07 — Telegram / X distribution bots
+
+Read `00-README.md` in this folder and `/CLAUDE.md` first — shared context, existing
+files, non-negotiable rules. This task assumes them.
+
+## Goal
+
+Push wins off-platform to where the audience already is. A Telegram channel (and an X
+poster) that broadcasts notable, provable events — big closes, new graduations,
+leaderboard moves, weekly Wrapped highlights — each as a PnL card (prompt 01) with a
+referral-tagged link back (prompt 03). Distribution, not spam: only verified,
+genuinely notable events, rate-limited, with clear unsubscribe/opt-in semantics.
+
+## Build on (do not rebuild)
+
+- `src/pump/telegram-delivery.js`, `api/pump/deliver-telegram.js`,
+ `scripts/changelog-telegram.mjs` — existing Telegram delivery + the bot token
+ convention (`TELEGRAM_BOT_TOKEN`, channel/chat id env vars). Reuse, don't reinvent.
+- Migrations `*_sniper_telegram_notify.sql`, `*_copy_telegram.sql` — existing
+ Telegram link state.
+- Share-card endpoints (prompt 01), referral links (prompt 03), the verification
+ badge (prompt 05 — only broadcast verified traders), `api/cron/rewards-distribute.js`
+ cron pattern.
+
+## Deliver
+
+1. **Event selection.** A defensible "is this notable?" filter from real data: e.g.
+ realized PnL above a threshold, ROI above X%, a graduation, a top-N leaderboard
+ entry, or a Wrapped highlight — and **only from verified traders** (prompt 05).
+ No threshold-gaming: dedupe per trade/event, cap posts per trader per window.
+2. **Telegram broadcaster.** A scheduled job (cron, idempotent like
+ `rewards-distribute.js`) or hook off the close path that posts the card image +
+ caption + referral link to the channel via the existing delivery module. One post
+ per event (idempotency key), structured logging, graceful skip if creds absent
+ locally (mirror the changelog-telegram `--dry-run` convention).
+3. **X poster (real or cleanly gated).** If X/Twitter API creds are configured, post
+ the same card + link. If creds are absent, the path is a no-op that logs why —
+ never a fake "posted" success and never a hardcoded credential. Document the env
+ vars needed.
+4. **Controls.** Per-trader opt-out (don't broadcast me), global kill switch via env,
+ and rate limits enforced server-side. All copy plain-language; `$THREE` only.
+
+## Acceptance
+
+- Only verified, genuinely-notable, deduped events are broadcast; per-trader and
+ global caps enforced (test covers selection + dedup + opt-out).
+- Telegram posts carry the real PnL card + a `?ref=` link; re-running the job never
+ double-posts (idempotency).
+- Missing Telegram/X creds → clean dry-run/no-op with a log line, not a crash or a
+ fake success. No credentials committed.
+- No token other than `$THREE` appears in any post.
+- `npm test` + `npm run typecheck` green. `data/changelog.json` entry
+ (`feature`/`infra`); `npm run build:pages` run. New cron (if any) in `vercel.json`.
+
+## When done
+
+Run the `/CLAUDE.md` self-review protocol, then delete **only this file**
+(`07-telegram-x-bots.md`).
diff --git a/prompts/samples/00-README.md b/prompts/samples/00-README.md
deleted file mode 100644
index 61e535f9a..000000000
--- a/prompts/samples/00-README.md
+++ /dev/null
@@ -1,145 +0,0 @@
-# three.ws — Production → $1B Program
-
-> **Read this file in full before running any prompt in this folder.** Every prompt
-> here (`01-*` … `44-*`) assumes the context below — do not re-derive it. Each prompt
-> is a single, self-contained task meant to be pasted into its own fresh agent chat.
-
-## What this is
-
-A sequenced program to take **three.ws** from "feature-rich but uneven" to
-**production-grade and ready to scale to a $1B platform**. Each numbered file is one
-self-contained task. Run them roughly in phase order — later phases assume earlier
-ones are done — but any single prompt can be run independently.
-
-This program is about **finishing, hardening, polishing, and growing what already
-exists** so the platform is correct, reliable, fast, accessible, secure, observable,
-and conversion-optimized. Net-new feature invention lives in the sibling folders
-(`feature-innovation/`, `moonshots/`, `inventions/`).
-
-## The bar (non-negotiable — applies to every prompt)
-
-Every prompt inherits the operating rules in **`/CLAUDE.md`**. Re-read it. The rules
-that matter most here:
-
-- **No mocks, no fake data, no placeholders, no TODOs, no stubs.** If you touch it,
- finish it. Real APIs, real endpoints, real data.
-- **No "good enough."** Fix mediocrity the moment you see it.
-- **No errors without solutions.** Every error has a root cause; find it and fix it.
- Ship working fallbacks and failsafes, never lazy propagation. Never leak a vendor's
- internal state (e.g. a provider's billing page) to an end user.
-- **Every state is designed** — loading, empty, error, populated, overflow.
-- **The only coin is `$THREE`** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
- Never reference any other coin anywhere. See `/CLAUDE.md` for the two
- runtime-data-only mechanical exceptions.
-- **Adopt vetted OSS over hand-rolling**; add hardening to new/unprotected paths
- rather than refactoring working code. Prefer the existing **cockatiel** resilience
- helper for retries/circuit-breakers.
-- **Definition of done**: the checklist in `/CLAUDE.md` must be true. If you can't
- verify a step, say so explicitly — never claim done you can't verify.
-
-## How to run a prompt
-
-1. Open a fresh chat in this repo.
-2. Paste the prompt file contents, or reference it: "Execute
- `prompts/production-1b/NN-*.md`".
-3. Let the agent work end-to-end. It should use `TodoWrite` for multi-step work,
- exercise UI in a real browser (`npm run dev`, port 3000), and run the relevant tests.
-4. Spot-check against the prompt's **Acceptance** section.
-5. Commit + push only when the user asks (the agent pushes to **both** remotes,
- `threeD` and `threews`, per `/CLAUDE.md`).
-
-## Repository orientation (so every prompt starts from truth)
-
-- **`STRUCTURE.md`** maps every product surface to its directory. Read it before
- exploring the ~60 top-level dirs.
-- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000). `pages/*.html`
- (~168 pages), `src/` (~810 modules), `public/`.
-- Backend: Vercel functions in `api/` (~960 handlers), Cloudflare workers in
- `workers/` (18). Routing, functions, crons, headers, env all in `vercel.json`.
-- 3D: Three.js + glTF/GLB. Avatar/animation pipeline under `public/animations/`,
- `src/glb-canonicalize.js`, `src/animation-retarget.js`. Model workers in
- `workers/model-*`. The avatar rule in `/CLAUDE.md` is law (no rig allowlist).
-- Tests: `npm test` = `vitest run && playwright test` (456 vitest files). `npm run
- lint` (eslint), `npm run typecheck` (tsc on jsconfig). CI is `.github/workflows/ci.yml`
- with jobs: **lint**, **test**, **guards** (`check-api-not-bundled`, `check:images`,
- `build:pages`), **typecheck** (advisory).
-- Changelog: every user-visible change gets an entry in `data/changelog.json`, then
- `npm run build:pages` regenerates `CHANGELOG.md` + `public/changelog.{json,xml}`.
-- **Lean on the existing audit tooling — do not reinvent it:** `audit:deploy`,
- `audit:pages`, `audit:handlers`, `audit:web`, `audit:mcp`, `check:images`,
- `seo:meta`, `verify`, `verify:solana`, `verify:onchain`, `smoke:onchain`,
- `smoke:mcp`, `snapshot`. (See `package.json` scripts.)
-- Resilience helpers and payments plumbing already exist in `api/_lib/` (x402-spec,
- x402-paid-endpoint, agent-wallet, secret-box, rate-limit, forge-health). Build on them.
-
-## Known traps (from `/CLAUDE.md`)
-
-- **Concurrent agents share this worktree.** Stage explicit paths only (never
- `git add -A`). Re-check `git status` before committing.
-- **`npx vercel build` overwrites `api/*.js` in place** with esbuild bundles. Check
- `head -1` for `__defProp`/`createRequire` before committing a large `api/` diff.
-- **Never pull/fetch/merge from the `threeD` remote** — it is push-only.
-
-## Phases & index
-
-**Phase 0 — Foundation (stop the platform from lying about "done")**
-- `01` Test suite green + CI gate
-- `02` Dead paths & broken links — every button works, every link resolves
-- `03` Zero console errors & warnings across all pages
-- `04` No-mocks / no-fake-data / no-TODO / no-stub sweep
-- `05` Secrets & env hygiene
-
-**Phase 1 — Cross-cutting production hardening**
-- `06` Error handling & resilience (`api/` + `workers/`)
-- `07` Security hardening (authz, input validation, headers, SSRF)
-- `08` Rate limiting & abuse prevention
-- `09` Accessibility (WCAG 2.2 AA)
-- `10` Performance & Core Web Vitals
-- `11` Mobile responsiveness (320 / 768 / 1440)
-- `12` Every state designed (loading / empty / error / overflow)
-- `13` Design-system consistency (tokens, spacing, typography, theming)
-- `14` SEO & structured data
-
-**Phase 2 — Product surface completeness (each end-to-end)**
-- `15` Forge / Text→3D / Avatar generation pipeline
-- `16` Marketplace
-- `17` Agent profiles, Agent Studio & economy
-- `18` Wallet & x402 payments
-- `19` Walk companion, Page-Agent & Feature Tour
-- `20` Scene Studio & Animation Studio
-- `21` Avatar creator / Character Studio / Selfie→avatar
-- `22` Pump.fun launch, Oracle, trading & $THREE surfaces
-- `23` MCP servers (production-ready)
-- `24` SDK publishing & docs
-- `25` Worlds & Coin Clash (token-gated 3D)
-
-**Phase 3 — Scale, infra, observability**
-- `26` Observability (logging, metrics, error tracking)
-- `27` Database integrity & migrations
-- `28` Deploy pipeline & rollback safety
-- `29` Uptime monitoring & public status page
-- `30` Load & stress testing
-- `31` Solana RPC & on-chain resilience
-- `32` Caching, CDN & R2 asset strategy
-
-**Phase 4 — Growth to $1B**
-- `33` Onboarding & activation funnel
-- `34` Home / landing conversion
-- `35` Pricing & monetization surfaces
-- `36` Growth analytics instrumentation
-- `37` Developer experience & docs site
-- `38` Referral & virality loops
-- `39` Trust, safety & moderation
-- `40` Legal, compliance, ToS & privacy
-- `41` i18n completion
-- `42` PWA & offline & notifications
-- `43` Brand, press & social proof
-- `44` Launch-readiness review (the final gate)
-
-## Prompt anatomy
-
-Each file has: **Why this matters for $1B**, **Mission**, **Map** (where things
-live — trust but verify; files move), **Do this** (ordered steps), **Must-not**
-(guardrails), and **Acceptance** (a checklist that must be all-true before claiming
-done). If a path is stale, find the real one and proceed — never stop because a path
-was wrong.
diff --git a/prompts/samples/01-test-suite-green-and-ci-gate.md b/prompts/samples/01-test-suite-green-and-ci-gate.md
deleted file mode 100644
index 448e2c254..000000000
--- a/prompts/samples/01-test-suite-green-and-ci-gate.md
+++ /dev/null
@@ -1,92 +0,0 @@
-# 01 — Test suite green + CI gate
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-CI is the only thing standing between a green checkmark and a money-path
-regression reaching production. Right now the suite is large (458 vitest files +
-a Playwright e2e set) but the gate is soft: lint allows the warning backlog and
-typecheck is advisory (`continue-on-error: true`). A platform that ships real
-USDC payments cannot tolerate "passing" CI that lets type errors and lint
-warnings through. Make the suite genuinely green and reliable, then ratchet the
-gate so "green" actually means "safe to merge."
-
-## Mission
-
-Get `npm test` (`vitest run && playwright test`) fully green and non-flaky, then
-deliver a concrete, staged plan (and the first ratchet step) to flip the advisory
-typecheck job to a hard gate and tighten eslint to `--max-warnings 0`.
-
-## Map (trust but verify — files move)
-
-- **CI definition** — [.github/workflows/ci.yml](../../.github/workflows/ci.yml).
- Jobs: `lint` (`npx eslint .`), `test` (`npx vitest run`), `guards`
- (`check-api-not-bundled` + `check:images` + `build:pages`), `typecheck`
- (advisory, `continue-on-error: true`).
-- **Vitest config** — [vitest.config.js](../../vitest.config.js). Note the
- 120s test/hook timeouts and `MAX_FORKS` cap for small CI/Codespace hosts.
-- **Playwright config** — [playwright.config.js](../../playwright.config.js).
- `testDir: tests/e2e`, `retries: 1`, `fullyParallel: false`, dev-server cold
- budget 180s. Specs in [tests/e2e/](../../tests/e2e).
-- **Scripts** — [package.json](../../package.json): `test`, `test:core`
- (`--maxWorkers=1`), `test:gate` ([scripts/test-gate.mjs](../../scripts/test-gate.mjs),
- the curated deploy-critical subset), `lint`, `lint:fix`, `typecheck`
- (`tsc -p jsconfig.json`).
-- **Typecheck scope** — [jsconfig.json](../../jsconfig.json): `checkJs: false`,
- opt-in via `// @ts-check` pragma; `include` is the ratchet allowlist.
-- **Lint config** — [eslint.config.js](../../eslint.config.js).
-- **Source guards** — [scripts/check-api-not-bundled.mjs](../../scripts/check-api-not-bundled.mjs),
- [scripts/audit-image-loading.mjs](../../scripts/audit-image-loading.mjs) (`check:images`).
-
-## Do this
-
-1. Run `npx vitest run` and capture every failure. Fix each at the root — never
- `.skip` a real test to go green. If a test depends on live credentials that
- are absent locally, confirm it is already guarded; if not, gate it cleanly on
- env presence rather than deleting it.
-2. Re-run failing files in isolation (`npx vitest run path/to/file.test.js`) and
- 3x in a row to separate true failures from flakes. For flakes, find the cause
- (shared global state, real timers, unmocked I/O, fork contention) and fix it —
- do not just bump a timeout. `vitest.config.js` already sets generous ceilings.
-3. Start the dev server (`npm run dev`, port 3000) and run `npx playwright test`.
- Fix e2e failures at the source. Honor `fullyParallel: false` and the cold-start
- budget; do not lower assertions to pass.
-4. Confirm the guards job is green: `node scripts/check-api-not-bundled.mjs`,
- `npm run check:images`, `npm run build:pages`.
-5. Run `npm run lint` and count warnings. Burn the backlog down with `npm run
- lint:fix` for auto-fixables, then hand-fix the rest — no blanket
- `eslint-disable` of whole files. Track the count before and after.
-6. Run `npm run typecheck`. Catalog the errors by file. Fix the cheap ones now
- and add `// @ts-check` + the file to `jsconfig.json` `include` as you bring each
- clean (the ratchet rule the jsconfig comment describes).
-7. Write the staged ratchet plan into this task's report: (a) flip eslint to
- `--max-warnings 0` in `ci.yml` once the count hits 0; (b) flip typecheck's
- `continue-on-error` to `false` once `npm run typecheck` is clean. Land whichever
- ratchet is already achievable (likely eslint) in `ci.yml` now.
-8. Re-run the full `npm test` once more end-to-end to confirm a clean, repeatable
- green before claiming done.
-
-## Must-not
-
-- Do not skip, delete, or weaken a test to make CI green — fix the code or the test.
-- Do not flip typecheck/eslint to a hard gate while errors/warnings remain; that
- breaks every other agent's PR. Ratchet only when the count is actually zero.
-- Do not commit a `vercel build`-bundled `api/*.js` (check `head -1` for `__defProp`).
-- Do not reference any coin other than `$THREE` in any test or fixture.
-- Do not mask flakiness with retries or longer timeouts in place of a real fix.
-
-## Acceptance (all true before claiming done)
-
-- [ ] `npx vitest run` passes locally with zero failures, repeatable across 3 runs.
-- [ ] `npx playwright test` passes against `npm run dev` with no skipped real specs.
-- [ ] `guards` job commands all pass (`check-api-not-bundled`, `check:images`, `build:pages`).
-- [ ] Current eslint warning count is recorded and reduced (target 0); any
- achievable ratchet (`--max-warnings 0`) is landed in `ci.yml`.
-- [ ] A concrete, staged plan to flip the typecheck gate is documented, with the
- first ratchet step applied or explicitly blocked-and-explained.
-- [ ] No coin other than `$THREE` introduced; no new mocks/stubs/TODOs.
-- [ ] If a step could not be verified locally (e.g. live-cred e2e), it is called
- out explicitly rather than claimed.
diff --git a/prompts/samples/02-dead-paths-and-broken-links.md b/prompts/samples/02-dead-paths-and-broken-links.md
deleted file mode 100644
index db172a3dd..000000000
--- a/prompts/samples/02-dead-paths-and-broken-links.md
+++ /dev/null
@@ -1,90 +0,0 @@
-# 02 — Dead paths & broken links
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Nothing kills trust faster than a button that does nothing or a link that 404s.
-With ~125 pages, ~810 src modules, and ~961 api handlers, dead-ends accumulate
-silently — a nav entry to a page that no longer exists, an `<a href="#">` that
-was never wired, a CTA whose handler was deleted. Every dead path is a leak in
-the conversion funnel and a screenshot of brokenness. `/CLAUDE.md` is explicit:
-"If a button exists, it must work. If a link exists, it must go somewhere."
-
-## Mission
-
-Audit every interactive element and route so that every button does something,
-every `<a href>`/route resolves to a live destination, and every nav entry goes
-somewhere real — then fix or remove every dead-end found.
-
-## Map (trust but verify — files move)
-
-- **Full-site audit harness** — [scripts/page-audit.mjs](../../scripts/page-audit.mjs)
- (`npm run audit:web`). Drives real Chromium over every page in desktop + mobile,
- records failed network requests, HTTP >= 400, missing `<title>`, and **empty
- links/buttons**. Writes `reports/page-audit-<ts>.{json,md}`.
-- **Route-documentation guard** — [scripts/audit-page-index.mjs](../../scripts/audit-page-index.mjs)
- (`npm run audit:pages`). Cross-checks `vercel.json` routes against
- [data/pages.json](../../data/pages.json); flags pages with no manifest entry.
-- **Empty-handler guard** — [scripts/audit-empty-handlers.mjs](../../scripts/audit-empty-handlers.mjs)
- (`npm run audit:handlers`). Fails on any `api/*.js` that is empty or exports
- nothing (Vercel routes to it but it can never respond).
-- **Routing & headers** — [vercel.json](../../vercel.json) (rewrites/routes for
- pretty paths and dynamic routes).
-- **Navigation source of truth** — [public/nav-data.js](../../public/nav-data.js)
- (`NAV_GROUPS`, every menu item's `href`), rendered by
- [public/nav.js](../../public/nav.js), styled by [public/nav.css](../../public/nav.css).
-- **Surfaces to crawl** — [pages/](../../pages) (~125 `*.html`), [src/](../../src)
- (~810 modules), [public/](../../public).
-
-## Do this
-
-1. Start `npm run dev` (port 3000) and run `BASE_URL=http://localhost:3000 npm run
- audit:web`. Open the generated `reports/page-audit-*.md` and triage every
- empty-link/empty-button finding and every HTTP >= 400 / requestfailed entry.
-2. Run `npm run audit:pages --strict` and `npm run audit:handlers`. Fix every gap:
- a flagged empty handler is either implemented (real response) or deleted with
- its route; a route missing from `data/pages.json` gets a manifest entry.
-3. Walk every `href` in [public/nav-data.js](../../public/nav-data.js) `NAV_GROUPS`
- and the top-level links. For each, confirm the destination resolves to a live
- page (in the browser, not just file existence). Fix or remove dead entries —
- nav is the single source of truth, so a broken entry breaks it everywhere.
-4. Grep the codebase for placeholder links and no-op handlers and resolve each:
- `href="#"`, `href="javascript:void(0)"`, `onclick=""`, `<a>` with no href,
- `<button>` with no listener. Wire the real action or remove the element.
-5. Cross-check dynamic routes (agent profiles, dashboards, `/launches`, marketplace
- detail pages) — click through from a list view into a detail view and back.
- The "list links to detail" connection in `/CLAUDE.md` must hold.
-6. For any page that legitimately can't resolve yet (e.g. a feature behind auth or
- a not-yet-built surface), make the entry point honest: gate it, label it, or
- remove it — never leave a live link to a dead place.
-7. Exercise the primary CTAs in a real browser (Forge "Generate", marketplace
- "Buy", wallet "Connect", launch flow): every one performs a real action, not a
- silent failure. Watch the Network tab to confirm real calls fire.
-8. Re-run `npm run audit:web`, `npm run audit:pages --strict`, and `npm run
- audit:handlers`; confirm the dead-path findings are cleared. Add a
- `data/changelog.json` entry for any user-visible fix, then `npm run build:pages`.
-
-## Must-not
-
-- Do not "fix" a broken link by pointing it at the homepage — route it to the
- correct destination or remove the element.
-- Do not delete a working feature to silence an audit finding; understand first.
-- Do not introduce mocks, stubs, TODOs, or `href="#"` placeholders.
-- Do not reference any coin other than `$THREE` in nav, copy, or links.
-- Do not edit working code paths you didn't need to touch — additive fixes only.
-
-## Acceptance (all true before claiming done)
-
-- [ ] `npm run audit:web` reports zero empty-link / empty-button findings and no
- unexplained HTTP >= 400 across the crawled pages.
-- [ ] `npm run audit:pages --strict` and `npm run audit:handlers` both exit clean.
-- [ ] Every `href` in `public/nav-data.js` resolves to a live page in the browser.
-- [ ] No `href="#"`, `javascript:void(0)`, or no-op handler remains on a shipped
- interactive element.
-- [ ] Primary CTAs (Forge, marketplace, wallet, launch) perform real actions with
- real network calls, verified in a real browser.
-- [ ] Existing tests still pass (`npm test`); changelog updated for visible fixes
- and `npm run build:pages` is clean.
diff --git a/prompts/samples/03-zero-console-errors.md b/prompts/samples/03-zero-console-errors.md
deleted file mode 100644
index 42757410d..000000000
--- a/prompts/samples/03-zero-console-errors.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# 03 — Zero console errors & warnings
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-A console full of red is a tell that the team doesn't sweat the details — and
-the warnings are often real bugs wearing a yellow coat (a 404'd asset, a failed
-fetch with a swallowed error, a React/Three.js misuse that leaks memory). Across
-~125 pages, every console error is a paper cut on the perceived quality of the
-platform and a hint to a savvy user that something is broken under the hood.
-`/CLAUDE.md`'s definition of done requires "No console errors. No console
-warnings from your code."
-
-## Mission
-
-Load every page, capture all console errors and warnings (plus uncaught
-exceptions and failed requests), and fix each at the source — no suppression,
-no `console.warn` muting, no try/catch that just swallows.
-
-## Map (trust but verify — files move)
-
-- **Full-site console audit** — [scripts/page-audit.mjs](../../scripts/page-audit.mjs)
- (`npm run audit:web`). Drives real Chromium over every page (desktop + mobile)
- and records `console.error`/`console.warn`, `pageerror` (uncaught exceptions),
- `requestfailed`, and HTTP >= 400. Output: `reports/page-audit-<ts>.{json,md}`.
- Targets via `BASE_URL` (default `https://three.ws`; use `http://localhost:3000`).
-- **Visual snapshot harness** — [scripts/page-snapshot.mjs](../../scripts/page-snapshot.mjs)
- (`npm run snapshot`). Full-page Chromium screenshots of every page — useful to
- confirm a console fix didn't break the render.
-- **Page manifest (the page list both harnesses crawl)** — [data/pages.json](../../data/pages.json).
-- **e2e specs** — [tests/e2e/](../../tests/e2e) (Playwright). Existing specs like
- `club.spec.js`, `nav-auth.spec.js` already assert no page errors on key flows.
-- **Surfaces** — [pages/](../../pages) (~125 `*.html`), [src/](../../src) (~810
- modules), [public/](../../public). Shared boot/nav: [public/nav.js](../../public/nav.js).
-
-## Do this
-
-1. Start `npm run dev` (port 3000) and run `BASE_URL=http://localhost:3000 npm run
- audit:web`. Read `reports/page-audit-*.md` and build a per-page list of every
- console error, warning, uncaught exception, and failed request.
-2. Triage by root cause, not by page. The same offender (a missing favicon, a bad
- import, a deprecated Three.js API, an unguarded `null` access) usually fires on
- many pages — fix it once at the source.
-3. For each finding, fix the cause: 404'd asset → correct the path or ship the
- asset; failed fetch → handle the error at the boundary with a designed error
- state (per `/CLAUDE.md`), never an empty catch; deprecation warning → migrate to
- the current API; `null`/`undefined` access → guard the real data flow.
-4. Never silence. Do not delete `console.warn` calls, wrap noise in
- `try{}catch{}`, or filter the audit's output to hide a finding. The bar is no
- warnings *from our code*; legitimate third-party noise must be understood and
- documented, not blanket-suppressed.
-5. Pay special attention to the heavy 3D pages (Forge, Scene Studio, Club, Walk):
- WebGL context warnings, texture/format issues, and animation-retarget warnings
- are real signals. Cross-check against the avatar rule in `/CLAUDE.md`.
-6. Re-run `npm run audit:web` after each batch of fixes and confirm the count
- drops toward zero. Spot-check fixed pages live with the browser console open.
-7. Run `npm run snapshot` on the pages you changed and eyeball the screenshots to
- confirm no fix introduced a visual regression.
-8. Run the e2e specs that assert clean console (`npx playwright test`) and the unit
- suite (`npx vitest run`). Add a `data/changelog.json` entry if any fix is
- user-visible (e.g. a previously-broken feature now works), then `npm run build:pages`.
-
-## Must-not
-
-- Do not suppress, filter, or delete console output to make the count drop — fix
- the cause.
-- Do not wrap errors in empty `try/catch` or swallow rejected promises.
-- Do not introduce mocks, stubs, fake data, or TODOs while fixing.
-- Do not reference any coin other than `$THREE` in any copy or asset you touch.
-- Do not refactor working modules beyond what the fix requires — additive, surgical.
-
-## Acceptance (all true before claiming done)
-
-- [ ] `npm run audit:web` reports zero `console.error`, zero `console.warn` from
- our code, zero `pageerror`, and no unexplained failed requests across pages.
-- [ ] Every fix addresses a root cause; no suppression, output filtering, or empty
- catch was used to hide a finding.
-- [ ] Heavy 3D pages (Forge, Scene Studio, Club, Walk) load clean in a real browser
- with the console open.
-- [ ] `npm run snapshot` of changed pages shows no visual regression.
-- [ ] `npx vitest run` and `npx playwright test` pass.
-- [ ] Changelog updated for any user-visible fix and `npm run build:pages` is clean.
diff --git a/prompts/samples/04-no-mocks-no-stubs-sweep.md b/prompts/samples/04-no-mocks-no-stubs-sweep.md
deleted file mode 100644
index df0a34baa..000000000
--- a/prompts/samples/04-no-mocks-no-stubs-sweep.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# 04 — No-mocks / no-fake-data / no-TODO / no-stub sweep
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-`/CLAUDE.md`'s hard rules are absolute: no mocks, no fake data, no placeholders,
-no TODOs, no stub functions, no `setTimeout` fake-loading, no fallback sample
-arrays shipped to production. Every one of these is a promise the product can't
-keep — a "feature" that secretly renders canned data, a progress bar that fakes
-work, a handler that quietly does nothing. A $1B platform cannot ship a single
-one. This sweep finds and eliminates them across the real source tree.
-
-## Mission
-
-Quantify every shortcut marker in shipped source, then fix or delete each one so
-the codebase contains no TODO/FIXME, no `not implemented`, no production
-mock/fake/sample arrays, and no fake `setTimeout` loading — per `/CLAUDE.md`.
-
-## Map (trust but verify — files move)
-
-- **Shipped source to sweep** — [api/](../../api) (~961 handlers), [src/](../../src)
- (~810 modules), [public/](../../public), [workers/](../../workers) (18). Exclude
- test files (`*.test.js`, `*.spec.js`), `node_modules`, and vendored dirs.
-- **Hard rules reference** — [/CLAUDE.md](../../CLAUDE.md) "Hard rules
- (non-negotiable)" §1–6 and "The only coin — $THREE".
-- **Empty-handler guard (catches stub handlers)** — [scripts/audit-empty-handlers.mjs](../../scripts/audit-empty-handlers.mjs)
- (`npm run audit:handlers`): fails on any `api/*.js` that exports nothing.
-- **Resilience helpers to use instead of fakes** — [api/_lib/](../../api/_lib)
- (`forge-health.js`, `x402-spec.js`, `rate-limit.js`; `cockatiel` for real
- retries/circuit-breakers — never a `setTimeout` stand-in).
-- **Baseline marker counts (re-measure first — they drift):** ~62 `// TODO`
- comments, ~6 `FIXME`, ~2 `const sample|mock|fake = [...]` arrays, ~7
- `setTimeout` calls near `progress`/`loading`/`width` in `src/`, 0
- `throw … not implemented`. Confirm with the greps below before you start.
-
-## Do this
-
-1. **Quantify first.** Run, and record the exact counts (re-run at the end to
- prove zero):
- - TODO/FIXME: `grep -rIn --include='*.js' --include='*.mjs' --include='*.html' -E 'TODO|FIXME' api src public workers | grep -v node_modules`
- - not implemented: `grep -rIn -iE "not implemented|notImplemented|throw new Error\(['\"\`].*not impl" api src public workers`
- - prod sample/mock/fake arrays: `grep -rIn -E 'const (sample|mock|fake|dummy)[A-Za-z]*\s*=\s*\[' api src public workers`
- - fake loading: `grep -rIn -E 'setTimeout' src | grep -iE 'progress|loading|fake|width'`
- - commented-out code blocks and `implement later`/`stub`/`placeholder`.
-2. **TODO/FIXME — implement or delete.** For each, either build the real behavior
- the comment describes, or remove it if it's stale. No TODO survives. If a
- comment documents a genuine known limitation, convert it to honest user-facing
- handling (designed error/empty state), not a silent gap.
-3. **Stub functions / empty handlers — finish them.** Run `npm run audit:handlers`;
- any flagged file gets a real implementation or is deleted along with its route.
- Hunt for functions that `return null`/`return []`/do nothing where the caller
- expects real data, and wire them to the real API.
-4. **Production sample/mock/fake arrays — replace with real fetch.** Any
- `const sampleAgents = [...]` or fallback array rendered to users must become a
- real call to the live endpoint, with designed loading/empty/error states.
- Mocks belong only in `tests/` — leave those alone.
-5. **Fake `setTimeout` loading/progress — make it real.** Replace simulated
- progress and `setTimeout` "loading" with progress driven by the actual async
- operation (real fetch/stream/poll). If the operation has no progress signal,
- use an honest indeterminate indicator (skeleton/spinner), not a faked bar.
-6. **Commented-out code — delete or implement.** Per `/CLAUDE.md` §3, no
- commented-out code in committed work.
-7. **`throw new Error("not implemented")` — implement it.** None should exist; if
- the grep surfaces any, build the real path.
-8. **Verify and log.** Re-run every grep from step 1 and confirm zero in shipped
- source. Run `npm run audit:handlers`, `npx vitest run`, and exercise any
- surface you changed in a real browser (`npm run dev`). Add a `data/changelog.json`
- entry for any user-visible change (e.g. a screen that now shows real data), then
- `npm run build:pages`.
-
-## Must-not
-
-- Do not touch or remove mocks inside `tests/` — those are legitimate test doubles.
-- Do not delete a feature to make a marker disappear; build the real version.
-- Do not swap one shortcut for another (e.g. a sample array for a hardcoded
- constant) — wire the real data source.
-- Do not reference any coin other than `$THREE` in any replacement data, fixture,
- or copy; use the $THREE CA or a clearly-synthetic placeholder.
-- Do not refactor working code beyond what removing the marker requires.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Start-of-task marker counts are recorded; end-of-task re-run shows **zero**
- TODO/FIXME/`not implemented`/prod sample-array/fake-`setTimeout` markers in
- `api`, `src`, `public`, `workers` (tests excluded).
-- [ ] `npm run audit:handlers` exits clean (no empty/export-less handlers).
-- [ ] Every former mock/sample surface now fetches real data with designed
- loading/empty/error states, verified in a real browser.
-- [ ] No commented-out code remains in the files touched.
-- [ ] No coin other than `$THREE` introduced anywhere.
-- [ ] `npx vitest run` passes; changelog updated for user-visible changes and
- `npm run build:pages` is clean.
diff --git a/prompts/samples/05-secrets-and-env-hygiene.md b/prompts/samples/05-secrets-and-env-hygiene.md
deleted file mode 100644
index 2c2fbe1eb..000000000
--- a/prompts/samples/05-secrets-and-env-hygiene.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# 05 — Secrets & env hygiene
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-This platform holds custody keys, x402 payment routing addresses, RPC and AI
-provider credentials, and a Telegram bot token. A single leaked secret in git
-history is a wallet drain or a takeover — the kind of incident that ends a $1B
-trajectory overnight. Equally damaging in slow motion: an undocumented env var
-that makes a surface silently fail in production because nobody knew to set it.
-Both must be closed: nothing secret committed, everything required documented.
-
-## Mission
-
-Ensure `.env.example` documents every env var the code actually reads, no secret
-is committed or sits in git history, anything ever exposed is rotated, and the
-required env per surface is documented.
-
-## Map (trust but verify — files move)
-
-- **Centralized env access** — [api/_lib/env.js](../../api/_lib/env.js). Lazy by
- design: `req()` throws at first use on a missing var, `opt()`/`addr()` for
- optional/address values. This is the canonical inventory of what the backend reads.
-- **Env template** — [.env.example](../../.env.example) (~246 documented vars,
- grouped by surface; copy to `.env.local` for dev). The doc that must stay in
- sync with what the code reads.
-- **Secret handling** — [api/_lib/secret-box.js](../../api/_lib/secret-box.js)
- (encryption at rest), [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js)
- (custody key derivation/spend guards).
-- **Deploy env surface** — [vercel.json](../../vercel.json) (functions, crons,
- headers; env is set in the Vercel dashboard, not committed).
-- **Ignore rules (already block .env files)** — [.gitignore](../../.gitignore)
- (lines for `.env`, `.env.local`, `.env*.local`, `.env*`, etc.).
-- **Note:** there is currently **no** dedicated secret-scan workflow in
- [.github/workflows/](../../.github/workflows) — installing one is in scope.
-
-## Do this
-
-1. **Build the read-set.** Grep every `process.env.X`, `req('X')`, `opt('X')`,
- `addr(env.X)` across [api/](../../api), [src/](../../src), [workers/](../../workers),
- and [scripts/](../../scripts). Dedupe into the authoritative list of vars the
- code reads. `api/_lib/env.js` is the spine; capture the rest too.
-2. **Reconcile with `.env.example`.** Diff the read-set against
- [.env.example](../../.env.example). Add every read-but-undocumented var with a
- one-line comment (purpose, format, whether required), grouped under its surface.
- Mark each as required/optional. Remove entries for vars no longer read.
-3. **Scan working tree + history for committed secrets.** Run a real scanner —
- `npx gitleaks detect --no-banner` (or `npx --yes @trufflesecurity/trufflehog
- git file://. --only-verified`). Triage every hit: real secret vs. test fixture
- vs. example placeholder. Treat the $THREE CA and clearly-synthetic placeholders
- as non-secrets.
-4. **For any real secret found committed or in history:** rotate it at the provider
- immediately, update the value in Vercel/Upstash/etc. (never in the repo), and
- document the rotation in this task's report. A scrubbed value that was ever
- pushed is already compromised — rotation is non-negotiable; removal alone is not.
-5. **Confirm `.gitignore` coverage.** Verify every `.env*` variant and any local
- key/credential file is ignored (`git check-ignore .env .env.local`). Add any
- gap. Ensure no `.env*` file is currently tracked (`git ls-files | grep -E '\.env'`).
-6. **Document required env per surface.** For each major surface (Forge/text→3D,
- wallet/x402, pump.fun/Oracle, MCP, Solana RPC), list the vars it needs to
- function so an operator knows what to set. Keep this in `.env.example` group
- comments — the existing file is already grouped by surface; extend that pattern.
-7. **Verify graceful degradation.** Confirm a surface with a missing optional var
- fails honestly (designed error/clear log) rather than crashing unrelated
- endpoints — the lazy `req()` pattern in `env.js` exists for exactly this; check
- it holds for any var you add.
-8. **Add a secret-scan CI gate** (no GitHub Actions secret scan exists today): a
- `gitleaks` job in [.github/workflows/ci.yml](../../.github/workflows/ci.yml) so
- future pushes are blocked on a committed secret. Run `npx vitest run` to confirm
- nothing broke. Add a `data/changelog.json` entry only if a user-visible/security
- change resulted, then `npm run build:pages`.
-
-## Must-not
-
-- Do not commit any real secret, key, or token — values live in Vercel/Upstash,
- not the repo. `.env.example` holds placeholders only.
-- Do not "fix" an exposed secret by deleting it from the file without rotating it
- at the provider — an exposed secret is a compromised secret.
-- Do not paste a real coin's mint/creator/holder address anywhere; the only coin
- is `$THREE` (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
-- Do not introduce mocks, stubs, or TODOs; do not weaken `env.js` guards.
-- Do not log secret values in any new error path you add.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every env var read by `api/`, `src/`, `workers/`, `scripts/` is documented in
- `.env.example` (purpose + format + required/optional), grouped by surface.
-- [ ] `gitleaks`/`trufflehog` scan of working tree **and** history is clean (or
- every finding triaged as a non-secret placeholder, documented).
-- [ ] Any real secret ever committed is rotated at the provider and the rotation
- is recorded; no secret value sits in the repo or history.
-- [ ] No `.env*`/credential file is tracked; `.gitignore` covers all variants.
-- [ ] Required-env-per-surface is documented so an operator can configure cleanly.
-- [ ] A secret-scan CI gate is added to `ci.yml`; `npx vitest run` passes.
-- [ ] Only `$THREE` referenced; changelog updated if any user-visible/security
- change resulted and `npm run build:pages` is clean.
diff --git a/prompts/samples/06-error-handling-resilience.md b/prompts/samples/06-error-handling-resilience.md
deleted file mode 100644
index a09599b0e..000000000
--- a/prompts/samples/06-error-handling-resilience.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# 06 — Error handling & resilience (api/ + workers/)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-A $1B platform never dies because an upstream blinked. Solana RPC throttles, OpenAI
-returns a 529, pump.fun times out, an image provider 502s — and the user must still
-get a fast, honest, recoverable result, never a hung spinner or a leaked vendor stack
-trace. `/CLAUDE.md` is explicit: **no errors without solutions; ship working fallbacks
-and failsafes; lazy error propagation is not engineering.** Resilience is what turns
-demo-grade into platform-grade.
-
-## Mission
-
-Wrap every external call in `api/` and `workers/` in a timeout + retry + circuit
-breaker via the existing **cockatiel** helper, handle errors only at the boundaries
-(network, user input) while internal code trusts itself, and guarantee no unhandled
-promise rejection and no provider internals ever reach a user.
-
-## Map (trust but verify — files move)
-
-- **Resilience helper (build on this — do not re-roll)** — [api/_lib/resilience.js](../../api/_lib/resilience.js):
- `withBreaker(name, fn, { fallback, threshold, halfOpenAfterMs })`, `isCircuitError`.
- It is the ONLY current cockatiel consumer — that is the gap this prompt closes.
-- **Boundary error envelope** — [api/_lib/http.js](../../api/_lib/http.js): `wrap()`
- (catches unhandled rejections, redacts keyed RPC URLs from 5xx bodies, emits a
- correlation `ref`), `serverError`, `respondError`, `redactUrl`.
-- **LLM provider chain** — [api/_lib/llm.js](../../api/_lib/llm.js) (`llmComplete`,
- anthropic/openai/nvidia/groq fetch at lines ~95/169/183/238),
- [api/_lib/llm-health.js](../../api/_lib/llm-health.js) (probe timeouts).
-- **Solana RPC failover** — [api/_lib/solana/rpc-fallback.js](../../api/_lib/solana/rpc-fallback.js)
- (`createRpcFallback`, rotation + cooldown), [api/_lib/solana/connection.js](../../api/_lib/solana/connection.js),
- [api/_lib/helius.js](../../api/_lib/helius.js), [api/_lib/onchain.js](../../api/_lib/onchain.js).
-- **Other upstreams** — pump.fun (`frontend-api-v3.pump.fun`, `gmgn.ai`),
- [api/_lib/birdeye.js](../../api/_lib/birdeye.js), [api/_lib/aixbt.js](../../api/_lib/aixbt.js),
- Telegram/IPFS/Pinata. Image/3D providers in [workers/](../../workers): `model-trellis`,
- `model-hunyuan3d`, `model-triposg`, `rembg`, `texture`, `unirig`.
-- **MCP error masking** — [api/_lib/mcp-error-sanitize.js](../../api/_lib/mcp-error-sanitize.js)
- (`sanitizeToolError`), used by [api/_lib/mcp-dispatch.js](../../api/_lib/mcp-dispatch.js).
-- **Tests** — [tests/resilience.test.js](../../tests/resilience.test.js),
- [tests/api/mcp-resilience.test.js](../../tests/api/mcp-resilience.test.js),
- [tests/api/pump-trending-resilience.test.js](../../tests/api/pump-trending-resilience.test.js).
-
-## Do this
-
-1. **Inventory raw external calls.** `grep -rnE "fetch\(|new Connection\(|axios" api/
- workers/` and cross-reference the host list (`grep -rhoE "https://[a-z.-]+" api/
- workers/`). Mark every site that hits Solana RPC, an LLM proxy, an image/3D
- provider, pump.fun/gmgn, Birdeye, or Telegram/IPFS. That set is your work queue.
-2. **Every external call gets a timeout.** Any `fetch` without `signal:
- AbortSignal.timeout(ms)` (or equivalent) is a bug — a hung socket stalls the lambda.
- Add a tight, intent-appropriate timeout (probes ~5s, generations longer).
-3. **Wrap each upstream in a named breaker.** Use `withBreaker('pumpfun:trending',
- () => …, { fallback, threshold, halfOpenAfterMs })` so an outage fails fast instead
- of every request paying the full timeout. Name breakers per logical upstream.
- Provide a real `fallback` (cached value, neutral empty result) — never silently null.
-4. **Solana goes through the failover path.** Confirm RPC reads/writes use
- `createRpcFallback`/`rpc-fallback.js` (rotation + cooldown), not a bare
- `new Connection(url)`. Retire any one-off connection that bypasses rotation.
-5. **No unhandled promise rejections.** Verify every Vercel handler is wrapped by
- `wrap()` (or equivalent try/catch at the boundary). Audit fire-and-forget calls
- (`void something()`, background telemetry) — every floating promise needs a
- `.catch`. Internal pure functions stay un-try/catched; trust them.
-6. **Mask every vendor internal.** Boundary errors must map to neutral, actionable
- copy via the `http.js` envelope (and `sanitizeToolError` for MCP). No raw stack,
- no keyed RPC URL, no provider billing/quota text, no 402/credit message reaches the
- client. Raw detail lives only in `console.error` + the `ref`.
-7. **Add coverage for each new failure mode.** Extend `tests/resilience.test.js` (and
- the mcp/pump resilience tests) so timeout, open-circuit, 429/529, and fallback are
- asserted. Run `npx vitest run tests/resilience.test.js tests/api/*resilience*.test.js`.
-8. **Sanity-check live.** `npm run dev`, exercise a forge generation and a pump/oracle
- read with the network throttled; confirm graceful degrade, no console errors, real
- elapsed time. If anything is user-visible, add a `data/changelog.json` entry (tag
- `infra` or `improvement`) and run `npm run build:pages`.
-
-## Must-not
-
-- Do not hand-roll a new retry/cooldown/breaker — extend `withBreaker`/cockatiel.
-- Do not swallow errors into silent nulls without a designed fallback or a log line.
-- Do not let any vendor stack, keyed URL, billing/quota/credit message, or 402 detail
- reach a user — mask at the boundary, log raw server-side with a `ref`.
-- Do not add try/catch to internal pure code — handle at boundaries only.
-- Do not break working failsafes (the Solana rotation, `wrap()` redaction, fail-closed
- limiters). Add resilience; never weaken what already protects money paths.
-- Do not reference any coin other than `$THREE`.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every external call site in `api/` + `workers/` has a timeout and a named
- `withBreaker` (or the existing Solana failover) — verified by grep, no bare
- timeout-less `fetch` to a third party remains.
-- [ ] No unhandled promise rejection path: every handler is `wrap()`-ed, every
- fire-and-forget promise has a `.catch`.
-- [ ] Throttling/killing an upstream degrades gracefully in a real browser — no hung
- spinner, no console error, neutral copy, real elapsed time.
-- [ ] No vendor internals (stack, keyed URL, billing/quota/402) appear in any client
- response; raw detail is logged with a correlation `ref`.
-- [ ] `tests/resilience.test.js` + the mcp/pump resilience tests pass, with new cover
- for timeout, open-circuit, 429/529, and fallback.
-- [ ] Any user-visible change has a `data/changelog.json` entry and `npm run
- build:pages` is clean.
diff --git a/prompts/samples/07-security-hardening.md b/prompts/samples/07-security-hardening.md
deleted file mode 100644
index 20379d9c7..000000000
--- a/prompts/samples/07-security-hardening.md
+++ /dev/null
@@ -1,117 +0,0 @@
-# 07 — Security hardening (authz, validation, headers, SSRF)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-The platform moves real value: custodial wallet payouts, x402 USDC settlement, $THREE
-gating, on-chain launches. One missing authorization check, one unvalidated body, one
-server-side fetch that follows an attacker URL, and a $1B platform becomes a breach
-headline. Security is not a phase you bolt on — it is the precondition for every dollar
-that flows through three.ws. This prompt hardens the four highest-leverage classes:
-authorization, input validation, response headers, and SSRF.
-
-## Mission
-
-Confirm every endpoint authorizes its caller, every input is zod-validated at the
-boundary, security headers (CSP, HSTS, X-Frame-Options, Referrer-Policy,
-Permissions-Policy) are correct in `vercel.json`, CORS is allowlisted, and every
-server-side URL/image fetch is SSRF-guarded — then run `/security-review` and fix
-everything it surfaces.
-
-## Map (trust but verify — files move)
-
-- **Input validation (zod — ~123 files use it)** — [api/_lib/validate.js](../../api/_lib/validate.js):
- shared schemas (`email`, `slug`, `httpUrl`, `createAvatarBody`, …) + helpers
- `parse(schema, input)`, `validateQuery(req, schema)`, `isValidSolanaAddress`,
- `isValidEvmAddress`, `isUuid`. Validation 400s go through
- [api/_lib/http.js](../../api/_lib/http.js) `validationError`.
-- **AuthZ helpers** — [api/_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`,
- `authenticateBearer`, `verifyCsrfToken`, `isSameSiteOrigin`, `hasScope`),
- [api/_lib/account-auth.js](../../api/_lib/account-auth.js) (`resolveAccount`),
- [api/_lib/admin.js](../../api/_lib/admin.js) (`requireAdmin`),
- [api/_lib/csrf.js](../../api/_lib/csrf.js),
- [api/_lib/x402/access-control.js](../../api/_lib/x402/access-control.js) (`installAccessControl`).
-- **CORS** — [api/_lib/http.js](../../api/_lib/http.js) `cors(req, res, { origins,
- methods, credentials })` + `isAllowedOrigin` (the allowlist: `APP_ORIGIN`,
- x402scan, agentic.market, `*.ibm.com`, localhost in dev). Reuse it; do not invent.
-- **SSRF guards** — [api/_lib/ssrf.js](../../api/_lib/ssrf.js)
- (`validatePublicUrl`, `assertPublicHttpsUrl`, `safeFetchJson`, `pinnedAgent`),
- [api/_lib/ssrf-guard.js](../../api/_lib/ssrf-guard.js) (`assertSafePublicUrl`,
- `fetchSafePublicUrl`, `fetchSafePublicUrlPinned`),
- [api/_lib/fetch-model.js](../../api/_lib/fetch-model.js) (`fetchModel` — the SSRF pioneer).
-- **Security headers** — [vercel.json](../../vercel.json) `headers` blocks (~line 202+):
- `content-security-policy`, `strict-transport-security`, `x-content-type-options`,
- `referrer-policy`, `permissions-policy`, `x-frame-options`.
-- **Skill + tests** — `/security-review` skill;
- [tests/api/security-csrf-gates.test.js](../../tests/api/security-csrf-gates.test.js),
- [tests/api/x402-security-fixes.test.js](../../tests/api/x402-security-fixes.test.js),
- [tests/api/validate.test.js](../../tests/api/validate.test.js).
-
-## Do this
-
-1. **AuthZ audit — every state-changing endpoint authorizes the caller.** Inventory
- `api/` POST/PUT/PATCH/DELETE handlers; confirm each calls `getSessionUser` /
- `authenticateBearer` / `resolveAccount` / `requireAdmin` (or x402 `installAccessControl`
- for paid routes) AND checks ownership (the resource belongs to the caller). Flag any
- handler that mutates without an authZ gate; close the gap. Verify CSRF via
- `verifyCsrfToken`/`isSameSiteOrigin` on cookie-auth state changes.
-2. **Input validation everywhere.** Every handler that reads `req.body`/query/params
- must run it through a zod schema (reuse `validate.js`, add a `.strict()` schema where
- missing) and return `validationError` on failure. `grep -rn "req.body" api/` and
- confirm each is validated, not dot-accessed raw. No unbounded strings, no unchecked
- numbers feeding limits/pagination.
-3. **SSRF on every server-side fetch of a user/DB URL.** `grep -rnE "fetch\(" api/` and
- find any call whose URL comes from user input or the DB (image render, GLB fetch,
- webhook, metadata, proxy). Route it through `fetchSafePublicUrl` /
- `fetchSafePublicUrlPinned` / `safeFetchJson` — pinned variant for anything whose
- response is forwarded or executed. No raw `fetch(userUrl)` may remain.
-4. **CORS allowlist, not wildcard.** Confirm `cors()` callers pass an explicit
- `origins` allowlist (or rely on `isAllowedOrigin`); flag any `origins: '*'` on a
- credentialed or state-changing route and tighten it. Public read-only APIs may stay
- `*` — document why.
-5. **Security headers complete and correct.** Verify `vercel.json` sets CSP, HSTS
- (`max-age` + `includeSubDomains` + `preload`), `x-content-type-options: nosniff`,
- `referrer-policy`, `permissions-policy`, and `x-frame-options`/`frame-ancestors` for
- every served surface. Tighten CSP where `'unsafe-inline'`/`'unsafe-eval'` can be
- dropped without breaking a real page (test in browser before removing).
-6. **Run the security review.** Invoke the `/security-review` skill on the working
- tree. Triage every finding to root cause and fix it — no "accepted risk" without an
- explicit, written reason. Re-run until clean.
-7. **Validate live + tests.** `npm run dev`; confirm headers land (`curl -I`), CORS
- preflight behaves, an unauthorized mutation is rejected, a private-IP URL fetch is
- blocked. Run `npx vitest run tests/api/security-csrf-gates.test.js
- tests/api/x402-security-fixes.test.js tests/api/validate.test.js` and add cover for
- any newly-closed gap.
-8. **Changelog if user-visible.** Security hardening that changes behavior gets a
- `data/changelog.json` entry (tag `security`); run `npm run build:pages`.
-
-## Must-not
-
-- Do not weaken an existing control to "make it work" — fix the caller, not the guard.
-- Do not add `origins: '*'` to a credentialed/state-changing route, and do not loosen
- the SSRF IP blocklist (metadata, RFC1918, loopback, CGNAT must stay blocked).
-- Do not trust client-supplied IDs/ownership — re-check ownership server-side.
-- Do not dismiss a `/security-review` finding without a root-cause fix or written
- justification.
-- Do not break working pages by over-tightening CSP — verify each removal in a browser.
-- Do not reference any coin other than `$THREE`.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every state-changing `api/` endpoint authorizes the caller and verifies resource
- ownership; CSRF enforced on cookie-auth mutations — verified by audit.
-- [ ] Every handler that reads body/query/params validates it via zod and returns a
- clean `validationError` on bad input; no raw unvalidated `req.body` access remains.
-- [ ] Every server-side fetch of a user/DB-supplied URL goes through the SSRF guard;
- `grep` shows no raw `fetch(userUrl)`.
-- [ ] CORS is allowlisted on credentialed/mutating routes; any `*` is read-only and
- justified.
-- [ ] `vercel.json` sets correct CSP, HSTS, X-Content-Type-Options, Referrer-Policy,
- Permissions-Policy, and X-Frame-Options for every served surface (confirmed via
- `curl -I`).
-- [ ] `/security-review` runs clean (or every finding has a root-cause fix).
-- [ ] Security/CSRF/validate tests pass with cover for any closed gap; user-visible
- changes logged in `data/changelog.json` and `npm run build:pages` is clean.
diff --git a/prompts/samples/08-rate-limiting-abuse.md b/prompts/samples/08-rate-limiting-abuse.md
deleted file mode 100644
index 482b0d2a0..000000000
--- a/prompts/samples/08-rate-limiting-abuse.md
+++ /dev/null
@@ -1,116 +0,0 @@
-# 08 — Rate limiting & abuse prevention
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Every expensive path on three.ws costs real money: forge generations burn GPU/provider
-credits, LLM proxies burn tokens, Solana/Helius/Birdeye reads burn shared API quota,
-and x402/payout endpoints move USDC. Unlimited, those become a free attack on the
-platform's wallet and a denial-of-service on every honest user. A $1B platform meters
-its costly surfaces, makes payments idempotent so a replay can't double-charge, and
-stops bots before they scale. This is cost control, fairness, and uptime in one.
-
-## Mission
-
-Ensure every expensive / paid / auth / generation endpoint is rate-limited per
-user+IP via the existing `rate-limit.js` registry, payment endpoints are idempotent via
-the x402 idempotency cache, and bot/abuse mitigation plus quota tiers are in place —
-starting from an inventory of which endpoints currently lack limits.
-
-## Map (trust but verify — files move)
-
-- **Rate-limit registry (build on this — do not re-roll)** —
- [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js): the `limits` object (named
- buckets: `authIp`, `registerIp`, `pumpMetaIp`, `imgProxyIp`, `cohortsIp`, `aixbtIp`,
- `sdpIp`, `avatarPayoutDaily`, …), `clientIp(req)`, and `getLimiter(name, { limit,
- window, critical })` — `critical: true` fails CLOSED in prod (money/cost buckets),
- non-critical fails open. ~418 files already import it.
-- **Limit responses** — [api/_lib/http.js](../../api/_lib/http.js): `rateLimited(res,
- result, message)`, `setRateLimitHeaders(res, result)`. Use these so 429s carry the
- standard retry headers.
-- **x402 idempotency** — [api/_lib/x402/idempotency-cache.js](../../api/_lib/x402/idempotency-cache.js):
- `hashRequestPayload`, `hashPaymentProof`, `reserve`/`get`/`set`/`release`, `INFLIGHT`,
- `isInflight` (Redis-backed; refuses to boot in prod without Upstash unless
- `X402_ALLOW_MEMORY_FALLBACK=1`). Same id + different payload → 409 Conflict.
-- **x402 payment plumbing** — [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)
- (`paidEndpoint`), [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js),
- [api/_lib/x402-spending-cap.js](../../api/_lib/x402-spending-cap.js),
- [api/_lib/x402/access-control.js](../../api/_lib/x402/access-control.js).
-- **Costly endpoints to verify** — [api/forge.js](../../api/forge.js) (generation +
- rigging buckets), [api/chat.js](../../api/chat.js) (LLM proxy), pump/oracle reads
- (Helius/Birdeye), [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js) +
- payout routes, MCP dispatch in [api/_lib/mcp-dispatch.js](../../api/_lib/mcp-dispatch.js).
-- **Tests** — [tests/api/http-rate-limited.test.js](../../tests/api/http-rate-limited.test.js),
- [tests/api/chat-proxy-ratelimit.test.js](../../tests/api/chat-proxy-ratelimit.test.js).
-
-## Do this
-
-1. **Inventory unlimited expensive endpoints.** For every handler in `api/`, classify:
- does it cost money (provider/GPU/token/RPC quota), move value (x402/payout/launch),
- gate auth (login/register/reset), or generate (forge/avatar/image/LLM)? `grep -rLn
- "rate-limit\|limits\.\|clientIp" api/` to find handlers in those classes that import
- no limiter. That list is the work queue — produce it explicitly.
-2. **Add a named bucket per gap.** For each unlimited costly endpoint, add a bucket to
- the `limits` registry (descriptive name, sensible `limit`/`window`, `critical: true`
- for money/cost paths so a Redis outage fails closed) and enforce it with
- `clientIp(req)` + `rateLimited(res, rl, msg)`. Match the existing per-IP (and
- per-user where authenticated) keying convention.
-3. **Per user+IP, not just IP.** Authenticated costly endpoints should key on the user
- id when present (so one user can't rotate IPs) AND fall back to IP for anonymous
- callers. Add a per-resource ceiling where one entity is the cost driver (mirror
- `avatarPayoutDaily` keyed on the wallet, not the caller).
-4. **Idempotency on every payment endpoint.** Confirm each x402/paid route uses
- `idempotency-cache.js`: `reserve` before settling, `set` the response, return the
- cached body on replay, and 409 on same-id/different-payload. Any payment route
- without this can double-charge — fix it. Verify the prod no-memory-fallback boot
- check is intact.
-5. **Bot / abuse mitigation.** Ensure auth + registration + generation surfaces resist
- scripted abuse: burst + sustained windows (mirror `irlPinBurst` + `irlPinHourly`),
- honeypot/timing on signup, and per-device keying where a device token exists. Confirm
- anonymous generation can't be farmed for free GPU.
-6. **Quota tiers.** Wire tiered ceilings (anon < authenticated < $THREE-gated/paid) so
- value flows to holders and paying agents get headroom. Reuse existing tier/gating
- helpers (`three-tier.js`, holder/play passes) rather than inventing a parallel
- system — surface a clear, actionable message when a tier limit is hit.
-7. **Test the limits.** Extend `tests/api/http-rate-limited.test.js` and the chat
- ratelimit test to cover each new bucket (burst trips, headers present, critical
- buckets fail closed, idempotency replay returns cached / 409s on mismatch). Run
- `npx vitest run tests/api/http-rate-limited.test.js tests/api/chat-proxy-ratelimit.test.js`.
-8. **Verify live + changelog.** `npm run dev`; hammer a newly-limited endpoint and
- confirm a clean 429 with retry headers and helpful copy (not a raw error). Any
- user-visible change (new limit, tier) → `data/changelog.json` entry (tag
- `improvement` or `security`) + `npm run build:pages`.
-
-## Must-not
-
-- Do not hand-roll a counter/limiter — extend the `limits` registry in `rate-limit.js`.
-- Do not mark a money/cost bucket non-critical (it would fail open on a Redis outage and
- silently uncap a paid path); do not weaken an existing `critical` bucket.
-- Do not skip idempotency on a payment route, and do not enable the in-memory
- idempotency fallback in production (`X402_ALLOW_MEMORY_FALLBACK`) without explicit
- reason.
-- Do not return a raw error on a limit hit — use `rateLimited()` with retry headers and
- actionable copy.
-- Do not set ceilings so tight they break legitimate interactive use (size each window
- to a real workflow, like the existing buckets do).
-- Do not reference any coin other than `$THREE`.
-
-## Acceptance (all true before claiming done)
-
-- [ ] An explicit inventory exists of expensive/paid/auth/generation endpoints; every
- one is now rate-limited via a named `limits` bucket (verified by grep — no costly
- handler lacks a limiter).
-- [ ] Authenticated costly endpoints key on user+IP (plus a per-resource ceiling where a
- single entity drives cost); money/cost buckets are `critical` (fail closed).
-- [ ] Every payment/x402 endpoint is idempotent via `idempotency-cache.js`: replay
- returns the cached response, same-id/different-payload returns 409; prod
- no-memory-fallback boot check intact.
-- [ ] Bot/abuse mitigation (burst + sustained windows, signup protection) and tiered
- quotas (anon < auth < holder/paid) are in place with clear messaging.
-- [ ] Limit hits return a clean 429 with retry headers and helpful copy in a real
- browser.
-- [ ] Rate-limit + idempotency tests pass with cover for each new bucket; user-visible
- changes logged in `data/changelog.json` and `npm run build:pages` is clean.
diff --git a/prompts/samples/09-accessibility-wcag.md b/prompts/samples/09-accessibility-wcag.md
deleted file mode 100644
index f7551d6d6..000000000
--- a/prompts/samples/09-accessibility-wcag.md
+++ /dev/null
@@ -1,95 +0,0 @@
-# 09 — Accessibility (WCAG 2.2 AA)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-A platform that excludes keyboard, screen-reader, and low-vision users is leaving
-real users — and in many markets, legal compliance — on the table. Accessibility is
-also a proxy for craft: semantic structure, focus management, and contrast are the
-same primitives that make UI feel polished to everyone. A $1B platform passes WCAG
-2.2 AA on its core flows without anyone having to ask.
-
-## Mission
-
-Bring every primary surface (home, forge, marketplace, wallet, agent profiles,
-create flows) to WCAG 2.2 AA: semantic HTML, ARIA on interactive elements, full
-keyboard operability, visible focus, sufficient contrast, screen-reader labels, and
-honored reduced-motion.
-
-## Map (trust but verify — files move)
-
-- **Pages** — [pages/](../../pages) (~125 `*.html`). Start with high-traffic flows:
- `home.html`, `forge.html`, `marketplace*.html`, `agent-detail.html`,
- `create-prompt.html`, `agent-wallet.html`.
-- **Shared nav** — [public/nav.html](../../public/nav.html), [public/nav.js](../../public/nav.js)
- (desktop dropdowns + mobile drawer; `aria-pressed` already on the walk toggle),
- [public/nav.css](../../public/nav.css).
-- **Design tokens (focus ring, contrast)** — [public/tokens.css](../../public/tokens.css)
- (`--focus-ring-color` and friends), [DESIGN-TOKENS.md](../../DESIGN-TOKENS.md).
- Focus styles already exist in [public/buttons.css](../../public/buttons.css),
- [public/home.css](../../public/home.css), and others — extend, don't fork.
-- **Reduced motion** — already honored in [public/tokens.css](../../public/tokens.css),
- [public/footer.css](../../public/footer.css), [public/features-landing.css](../../public/features-landing.css);
- many `src/` animation modules are not. Search `prefers-reduced-motion`.
-- **JS components** — [src/](../../src) (~810 modules). Interactive widgets that build
- DOM (modals, tabs, menus, viewers) often ship `<div onclick>` without roles/labels.
-
-## Do this
-
-1. **Baseline audit.** Run an axe scan against the running app (no dep needed):
- `npm run dev`, then `npx @axe-core/cli http://localhost:3000/forge
- http://localhost:3000/marketplace http://localhost:3000/ http://localhost:3000/create/prompt`.
- Record every violation by page; this is your worklist.
-2. **Semantic structure.** Each page needs one `<h1>`, a logical heading order, and
- landmark regions (`<header><nav><main><footer>`). Replace generic `<div>` wrappers
- that are really headers/nav/main with the semantic element. Add a "skip to content"
- link as the first focusable element on long pages.
-3. **Interactive elements.** Every clickable `<div>`/`<span>` becomes a `<button>` or
- gets `role="button"`, `tabindex="0"`, and keydown (Enter/Space) handling. Icon-only
- controls get `aria-label`. Toggles get `aria-pressed`; tabs get `role="tab"` +
- `aria-selected`; modals get `role="dialog"`, `aria-modal`, focus trap, and Esc-to-close.
-4. **Keyboard operability.** Tab through each core flow with no mouse: every control
- reachable, in a sane order, no keyboard trap, dropdowns/drawers open & close via
- keyboard. The mobile drawer in `nav.js` must trap focus while open and restore it on
- close.
-5. **Visible focus.** Every interactive element shows a clear focus ring using the
- existing `--focus-ring-color` token (via `:focus-visible`). No `outline: none`
- without a replacement. Audit `src/` and `public/*.css` for naked `outline: none`.
-6. **Contrast.** Verify text and UI contrast against backgrounds (4.5:1 body, 3:1 large
- text / UI components) in both light and dark themes. Fix failing pairs by remapping to
- compliant tokens in `tokens.css` — never hardcode a one-off hex.
-7. **Screen reader & forms.** Every input has an associated `<label>` (or `aria-label`);
- error messages are announced (`aria-describedby` / `aria-live`); decorative images get
- `alt=""`, meaningful images get real `alt`. Async status (forge progress, save
- results) uses an `aria-live` region.
-8. **Reduced motion.** Wrap non-essential `src/` animations (loops, parallax, auto-play
- 3D spin) in `@media (prefers-reduced-motion: reduce)` or a JS check, degrading to a
- static/instant state.
-9. **Re-audit & test.** Re-run the axe scan — zero serious/critical violations on the
- targeted pages. Run `npm test` (vitest + playwright) and add/extend a Playwright check
- asserting skip-link presence, focus visibility, and drawer focus trap on at least the
- home and forge routes. Add a changelog entry; `npm run build:pages`.
-
-## Must-not
-
-- Do not add ARIA that lies about state (e.g. static `aria-expanded="true"`); ARIA must
- reflect live state or be omitted.
-- Do not remove focus outlines without a stronger visible replacement.
-- Do not hardcode colors to "fix" contrast — remap design tokens so both themes stay correct.
-- Do not regress working interactions while making them accessible; verify each in a browser.
-- Do not reference any coin other than `$THREE` in any new copy or label.
-
-## Acceptance (all true before claiming done)
-
-- [ ] axe scan on home, forge, marketplace, agent-detail, create/prompt shows zero
- serious/critical violations.
-- [ ] Every core flow is fully keyboard operable with no trap; visible focus on every control.
-- [ ] One `<h1>` and correct landmarks per audited page; skip-to-content link works.
-- [ ] Text/UI contrast passes 4.5:1 / 3:1 in both light and dark themes.
-- [ ] Inputs are labeled; async status and errors are announced via `aria-live`.
-- [ ] Reduced-motion is honored across `src/` animations on the audited pages.
-- [ ] `npm test` passes; new a11y Playwright checks added; changelog updated and
- `npm run build:pages` is clean.
diff --git a/prompts/samples/10-performance-core-web-vitals.md b/prompts/samples/10-performance-core-web-vitals.md
deleted file mode 100644
index 48c7e545a..000000000
--- a/prompts/samples/10-performance-core-web-vitals.md
+++ /dev/null
@@ -1,87 +0,0 @@
-# 10 — Performance & Core Web Vitals
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Speed is the silent conversion lever. Every 100ms of LCP and every layout shift costs
-sign-ups, and Core Web Vitals directly affect search ranking — the cheapest growth
-channel. This platform ships a heavy Three.js/GLB stack on top of ~125 pages; if those
-assets block first paint, the front door feels slow and acquisition leaks before the
-user sees the product. Fast must be the default, not a flag.
-
-## Mission
-
-Hit good Core Web Vitals on the primary surfaces — LCP < 2.5s, CLS < 0.1, INP < 200ms —
-by lazy-loading heavy modules and 3D, enforcing image-loading attributes, code-splitting,
-debouncing input handlers, and preconnecting/preloading critical origins.
-
-## Map (trust but verify — files move)
-
-- **Heaviest pages** — [pages/home.html](../../pages/home.html),
- [pages/forge.html](../../pages/forge.html) (both already use `preconnect`/`preload`),
- marketplace and walk landing pages. These mount Three.js.
-- **3D / GLB loaders** — `src/` modules importing `GLTFLoader` / `three.module` (e.g.
- [src/avatar-picker.js](../../src/avatar-picker.js), [src/club.js](../../src/club.js),
- [src/avatar-export.js](../../src/avatar-export.js)). Grep `GLTFLoader|three.module`.
- These are the biggest bundles — they must dynamic-`import()` on demand, not at page load.
-- **Dynamic import (existing pattern)** — many `src/` files already use `import(...)`
- (e.g. [src/agent-detail.js](../../src/agent-detail.js)); follow that pattern.
-- **Image loading guard** — [scripts/audit-image-loading.mjs](../../scripts/audit-image-loading.mjs)
- via `npm run check:images` (strict: every JS-rendered `<img>` in `src/` needs `loading=`).
- Codemod helper: [scripts/codemod-lazy-images.mjs](../../scripts/codemod-lazy-images.mjs).
-- **Build config** — [vite.config.js](../../vite.config.js) (chunking, build target),
- [public/tokens.css](../../public/tokens.css) (motion tokens for `will-change`/`transform`).
-- **Audit tooling** — `npm run audit:web` ([scripts/page-audit.mjs](../../scripts/page-audit.mjs)),
- `npm run snapshot` ([scripts/page-snapshot.mjs](../../scripts/page-snapshot.mjs)).
-
-## Do this
-
-1. **Measure first.** `npm run dev`, then run Lighthouse on the heaviest routes:
- `npx lighthouse http://localhost:3000/ --only-categories=performance --view`
- and repeat for `/forge` and `/marketplace`. Record LCP, CLS, INP/TBT per page — this
- is your before/after baseline. Note the LCP element and the largest network requests.
-2. **Lazy-load the 3D stack.** Confirm every Three.js/GLTFLoader import is behind a
- dynamic `import()` triggered by viewport/interaction (IntersectionObserver or click),
- never at module top level on a page that paints text first. Defer the canvas mount
- until after first contentful paint.
-3. **Image loading.** Run `npm run check:images` — fix every offender so JS-rendered
- `<img>` carries `loading="lazy"` and `decoding="async"`. For above-the-fold LCP images
- in static HTML, use `loading="eager"` + `fetchpriority="high"` (don't lazy-load the LCP
- image). Set explicit `width`/`height` (or `aspect-ratio`) on every image to kill CLS.
-4. **Eliminate layout shift.** Reserve space for async content (skeletons, fixed-aspect
- media, font-swap with `font-display: optional/swap` and preloaded fonts). Audit feeds
- and the forge result area for content that pushes layout on load.
-5. **Code-split & budget.** Inspect the Vite build output (`npx vite build`) for oversized
- chunks; split route-specific and 3D code into async chunks. Set and document a bundle
- budget (e.g. initial JS < 200KB gzipped per primary route) and bring offenders under it.
-6. **Debounce & schedule.** Debounce/throttle search, scroll, and resize handlers;
- move non-urgent work off the critical path (`requestIdleCallback` / `requestAnimationFrame`).
- Use `transform`/`opacity` + `will-change` for animations (never animate layout props).
-7. **Network priming.** Add `preconnect`/`dns-prefetch` for real cross-origin asset hosts
- (R2, RPC, fonts) and `preload` the LCP image + critical font on the heaviest pages,
- matching the existing pattern in `home.html`/`forge.html`. Remove dead preloads.
-8. **Re-measure & verify.** Re-run Lighthouse on the same routes — LCP < 2.5s, CLS < 0.1,
- INP/TBT in the good band. Run `npm run audit:web` and `npm run snapshot` and confirm no
- console errors. `npm test`. Add a changelog entry; `npm run build:pages`.
-
-## Must-not
-
-- Do not lazy-load the LCP image or above-the-fold hero — that regresses LCP.
-- Do not eager-load the full Three.js/GLB stack on pages that paint text first.
-- Do not animate layout-triggering properties (top/left/width/height) — use transforms.
-- Do not introduce fake `setTimeout` loading bars; use real async + skeletons.
-- Do not bypass `npm run check:images` strict mode — fix the images, don't disable the guard.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Lighthouse on home, forge, marketplace: LCP < 2.5s, CLS < 0.1, INP/TBT in the good band.
-- [ ] `npm run check:images` passes strict; every image has dimensions and correct `loading=`.
-- [ ] Three.js/GLB code is dynamic-imported on demand; not in the initial route bundle.
-- [ ] Documented bundle budget met; oversized chunks split; `npx vite build` clean.
-- [ ] Input/scroll handlers debounced; animations use transform/opacity + `will-change`.
-- [ ] `preconnect`/`preload` cover real critical origins; no dead hints; no console errors.
-- [ ] `npm test`, `npm run audit:web`, `npm run snapshot` pass; changelog updated and
- `npm run build:pages` is clean.
diff --git a/prompts/samples/11-mobile-responsiveness.md b/prompts/samples/11-mobile-responsiveness.md
deleted file mode 100644
index deb4ea48b..000000000
--- a/prompts/samples/11-mobile-responsiveness.md
+++ /dev/null
@@ -1,85 +0,0 @@
-# 11 — Mobile responsiveness (320 / 768 / 1440)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Most first touches arrive on a phone. If the home hero overflows at 320px, the forge
-canvas tanks a mid-range mobile GPU, or a primary CTA sits under the keyboard, the
-funnel dies before the user understands the product. A $1B platform is flawless from a
-cheap Android in portrait up to a 1440px desktop — the same flows, no horizontal
-scroll, no dead zones, touch targets you can actually hit.
-
-## Mission
-
-Make every key flow (home, forge, marketplace, wallet, agent profiles, create) correct
-and comfortable at 320px, 768px, and 1440px: proper viewport meta, fluid flex/grid
-layouts, ≥44px touch targets, a working mobile nav, and a 3D canvas that stays smooth on
-mobile GPUs.
-
-## Map (trust but verify — files move)
-
-- **Pages** — [pages/](../../pages) (~125 `*.html`). Both [pages/home.html](../../pages/home.html)
- and [pages/forge.html](../../pages/forge.html) already declare `viewport` — verify all
- primary pages do.
-- **Mobile nav** — [public/nav.js](../../public/nav.js) (`renderDrawer`, `initDrawer`,
- the mobile drawer + walk toggle), [public/nav.css](../../public/nav.css),
- [public/nav.html](../../public/nav.html).
-- **Layout CSS** — [public/](../../public) `*.css`. Several use fixed `width: NNNpx`
- (e.g. [public/app-next.css](../../public/app-next.css), [public/auth.css](../../public/auth.css)) —
- candidates to convert to fluid flex/grid. Grep `width: *[0-9]{3,}px`.
-- **Design tokens** — [public/tokens.css](../../public/tokens.css) (spacing scale, type
- ladder) so breakpoints reflow against shared tokens, not magic numbers.
-- **3D on mobile** — `src/` modules mounting Three.js/GLTFLoader (grep `GLTFLoader`).
- Set device pixel ratio caps and quality fallbacks here.
-- **Visual check tooling** — `npm run snapshot` ([scripts/page-snapshot.mjs](../../scripts/page-snapshot.mjs)),
- Playwright ([playwright.config.js](../../playwright.config.js)) for scripted viewports.
-
-## Do this
-
-1. **Drive real viewports.** `npm run dev`, open the core flows in browser devtools at
- **320×568**, **768×1024**, and **1440×900** (and one landscape phone). Walk home →
- forge → result, marketplace → detail, wallet, and a create flow at each width.
-2. **Viewport meta.** Confirm every primary page has
- `<meta name="viewport" content="width=device-width, initial-scale=1">` with no
- `maximum-scale`/`user-scalable=no` (pinch-zoom must stay enabled for a11y).
-3. **Kill horizontal scroll.** At 320px nothing overflows: no fixed pixel widths wider
- than the viewport, long words/URLs wrap (`overflow-wrap`), tables/grids scroll inside
- a contained region, images are `max-width: 100%`. Convert offending fixed-width blocks
- to fluid flex/grid using token spacing.
-4. **Touch targets.** Every tappable control is ≥44×44px with adequate spacing so
- neighbors aren't mis-tapped. Audit nav links, icon buttons, chips, and close buttons.
-5. **Mobile nav.** The drawer in `nav.js` opens/closes cleanly, the body locks scroll
- while open, the walk toggle works, and it dismisses on link tap and on backdrop tap.
- Verify it doesn't cover content or trap the user.
-6. **Forms & keyboard.** On mobile, primary CTAs aren't hidden behind the on-screen
- keyboard; inputs use correct `inputmode`/`type` (email, numeric, search); focused
- fields scroll into view.
-7. **3D on mobile GPUs.** In the Three.js mounts, cap `renderer.setPixelRatio` (e.g.
- `Math.min(devicePixelRatio, 2)`), provide a lighter quality path or a tap-to-load
- poster on small/low-power devices, and ensure the canvas resizes correctly on
- rotation. Confirm acceptable frame rate on a throttled mobile profile.
-8. **Snapshot & verify.** Run `npm run snapshot` and review the captures across widths;
- run the Playwright suite (extend with a mobile viewport project for home + forge if
- absent). `npm test`. Add a changelog entry; `npm run build:pages`.
-
-## Must-not
-
-- Do not disable pinch-zoom (`user-scalable=no` / `maximum-scale=1`) — it breaks a11y.
-- Do not hide core functionality on mobile; reflow it, don't remove it.
-- Do not ship fixed pixel widths that overflow 320px — use fluid flex/grid + tokens.
-- Do not render full-resolution 3D at uncapped DPR on mobile; cap quality and frame cost.
-- Do not reference any coin other than `$THREE` in any responsive copy or fallback.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Home, forge, marketplace, wallet, and a create flow work at 320 / 768 / 1440 with
- no horizontal scroll and no clipped content.
-- [ ] Every primary page has correct, zoom-enabled viewport meta.
-- [ ] All touch targets are ≥44px with safe spacing; nav drawer opens/closes/locks scroll.
-- [ ] Mobile CTAs stay reachable above the keyboard; inputs use correct `inputmode`/`type`.
-- [ ] 3D canvases cap DPR and run smoothly on a throttled mobile profile; resize on rotate.
-- [ ] `npm run snapshot` captures look correct across widths; `npm test` passes.
-- [ ] Changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/12-every-state-designed.md b/prompts/samples/12-every-state-designed.md
deleted file mode 100644
index 3e683699f..000000000
--- a/prompts/samples/12-every-state-designed.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# 12 — Every state designed (loading / empty / error / overflow)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-The difference between a toy and a product is what happens when there's no data, the
-network fails, or a name is 80 characters long. A blank void on first load reads as
-broken; an unstyled error reads as abandoned; an empty marketplace with no call to
-action loses the user who would have created the first listing. A $1B platform designs
-every state so the user is never confused, stuck, or staring at nothing.
-
-## Mission
-
-Audit every list, grid, feed, and detail view and ensure all four states are
-deliberately designed: **loading** (skeletons over spinners), **empty** (actionable —
-tells the user what to do next), **error** (recoverable with retry), and **overflow**
-(0 / 1 / 1000 items, very long names, missing thumbnails).
-
-## Map (trust but verify — files move)
-
-- **Data-driven surfaces** — `src/` modules that fetch then render lists/grids/feeds.
- Grep for `fetch(`, `innerHTML =`, `.map(`, `appendChild` in `src/` to find render
- paths. High-value targets: marketplace, agent profiles/feed, forge gallery/results,
- wallet/transactions, launches feed, changelog, notifications.
-- **Forge result states (gold standard reference)** — see
- [prompts/production-1b/15-forge-text-to-3d-pipeline.md](./15-forge-text-to-3d-pipeline.md):
- every phase labeled, real elapsed time, no fake `setTimeout` bars. Match that bar.
-- **Shared styles for states** — [public/tokens.css](../../public/tokens.css) (spacing,
- surfaces, motion for skeleton shimmer). Reuse existing skeleton/empty-state CSS where
- present (grep `skeleton` / `empty-state` across `public/*.css`); establish a shared
- pattern where missing.
-- **Pages hosting these views** — [pages/](../../pages) (marketplace, agent-detail,
- forge, wallet, launches, etc.).
-- **APIs feeding them** — [api/](../../api) handlers (to reproduce error/empty responses
- for testing). Tests live in [tests/](../../tests).
-
-## Do this
-
-1. **Inventory.** Build a checklist of every list/grid/feed/detail view across `src/`.
- For each, record where its data comes from and which of the four states currently
- exist vs. are missing.
-2. **Loading = skeletons.** Replace bare spinners and blank gaps with skeleton screens
- that match the final layout (so there's no shift when data arrives). No fake progress
- bars — drive UI off real request lifecycle.
-3. **Empty = actionable.** Each empty state explains why it's empty and gives the next
- action with a working CTA (e.g. "No agents yet — create your first" → links to the
- create flow). Never a bare "No data." Design a reusable empty-state component if one
- doesn't exist.
-4. **Error = recoverable.** On fetch failure, show a designed error with a plain-language
- message and a **Retry** that re-runs the request. Never leak raw stack traces, vendor
- billing/quota text, or provider URLs — keep raw detail in logs, show neutral copy.
-5. **Overflow & edge counts.** Verify each view at **0**, **1**, and **~1000** items:
- pagination/virtualization or "load more" for large lists; sensible single-item layout;
- no jank. Truncate long names with ellipsis + full value on hover/`title`; wrap long
- descriptions; provide a fallback for missing/broken thumbnails.
-6. **Reproduce each state in the browser.** `npm run dev` and force every state: throttle
- to Offline for error, point at an empty account for empty, paste a long name, and load
- a large feed. Confirm each is designed and reachable — no dead states.
-7. **Wire the failsafes.** Per `/CLAUDE.md`, errors are handled at boundaries (network /
- user input) with working fallbacks; internal code trusts itself. Make sure a failed
- sub-request degrades that section gracefully instead of blanking the whole page.
-8. **Test & ship.** Add/extend tests asserting empty and error rendering for at least the
- marketplace and one feed (component or Playwright). `npm test`. Add a changelog entry
- for the user-visible polish; `npm run build:pages`.
-
-## Must-not
-
-- Do not ship a bare spinner where a skeleton matching the layout belongs.
-- Do not leave a "No data" / blank empty state with no next action.
-- Do not surface raw errors, stack traces, or vendor billing/quota text to users.
-- Do not let one failed sub-request blank the entire page — degrade the section only.
-- Do not use fake `setTimeout` loading; drive states off the real request lifecycle.
-- Do not reference any coin other than `$THREE` in any state copy.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every list/grid/feed/detail view has designed loading, empty, error, and overflow states.
-- [ ] Loading uses skeletons matching final layout; no layout shift on data arrival; no fake bars.
-- [ ] Empty states are actionable with a working CTA; error states have a working Retry.
-- [ ] 0 / 1 / 1000 items, long names, and missing thumbnails all render cleanly.
-- [ ] No raw errors or vendor internals reach users; failures degrade per-section.
-- [ ] Each state reproduced in a real browser; tests cover empty + error for key views.
-- [ ] `npm test` passes; changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/13-design-system-consistency.md b/prompts/samples/13-design-system-consistency.md
deleted file mode 100644
index 08646aec0..000000000
--- a/prompts/samples/13-design-system-consistency.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# 13 — Design-system consistency (tokens, spacing, typography, theming)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Consistency is what makes a platform feel like one product instead of forty pages glued
-together. When spacing, type, color, and interaction states come from a single
-vocabulary, every new surface inherits quality for free and the brand reads as
-trustworthy. Drift — a one-off hex here, a magic `13px` there, a button with no focus
-state — is the visual equivalent of bugs. A $1B platform speaks one design language
-everywhere, in both light and dark.
-
-## Mission
-
-Unify the platform on the canonical design tokens: every surface references shared
-spacing, type, color, radius, and motion tokens; every interactive element has hover /
-active / focus states; light and dark themes are correct everywhere; and no surface
-reintroduces a parallel palette.
-
-## Map (trust but verify — files move)
-
-- **Canonical tokens (single source of truth)** — [public/tokens.css](../../public/tokens.css)
- (φ-based spacing scale, type ladder, surfaces, ink, stroke, radius, shadow, blur,
- motion, `--focus-ring-color`) and [DESIGN-TOKENS.md](../../DESIGN-TOKENS.md) (vocabulary
- + migration guidance). Per-surface palettes (`--mk-*`, `--pd-*`, `--ibm-*`, …) were
- **removed in B02** — do not reintroduce; a surface accent REMAPS these tokens.
-- **Token loading** — imported by [public/style.css](../../public/style.css) and
- [public/nav.css](../../public/nav.css) so tokens reach full-stylesheet pages and
- nav-only/embed surfaces. New pages just link one of those.
-- **Theming (no-flash boot + runtime)** — [scripts/inject-theme-boot.mjs](../../scripts/inject-theme-boot.mjs)
- (pre-paint `data-theme` apply; key `twx_theme`), [public/theme-switcher.js](../../public/theme-switcher.js)
- (toggle, persistence, cross-tab sync), the nav toggle in [public/nav.js](../../public/nav.js).
-- **Per-surface stylesheets** — [public/](../../public) `*.css` (~many). These are where
- drift hides: hardcoded hex/rgba/px, ad-hoc spacing, missing `:focus-visible`. Existing
- focus styles in [public/buttons.css](../../public/buttons.css), [public/home.css](../../public/home.css),
- [public/home-polish.css](../../public/home-polish.css) — extend, don't fork.
-
-## Do this
-
-1. **Read the vocabulary.** Read `DESIGN-TOKENS.md` and `tokens.css` end to end so you
- use the real token names (`var(--space-md)`, `var(--surface-1)`, `var(--text-sm)`,
- `--focus-ring-color`, motion tokens). Do not invent new names where one exists.
-2. **Find the drift.** Grep `public/*.css` and inline `src/`/`pages/` styles for
- hardcoded color (`#`, `rgb(`, `rgba(`, `hsl(`) and raw pixel spacing/sizing that an
- existing token already expresses. Build a list of offenders by file.
-3. **Migrate to tokens.** Replace each hardcoded value with the nearest correct token
- (color → surface/ink/stroke token; spacing/size → φ scale; font sizes → type ladder;
- radii/shadows/blur/motion → their tokens). If a genuinely new primitive is needed, add
- it once to `tokens.css` and document it in `DESIGN-TOKENS.md`, then use it everywhere.
-4. **Kill parallel palettes.** If any reintroduced `--mk-*`/`--pd-*`/`--ibm-*`-style
- namespace or standalone color set exists, collapse it into a thin theme layer that
- remaps the canonical tokens. One palette, not eight.
-5. **Interaction states everywhere.** Every interactive element (buttons, links, chips,
- tabs, cards, inputs) has consistent **hover**, **active**, and **`:focus-visible`**
- states drawn from tokens — using the shared focus ring, not ad-hoc outlines. Audit for
- controls missing any of the three.
-6. **Verify both themes.** `npm run dev`, toggle light/dark via the nav switch on home,
- forge, marketplace, wallet, and a settings/dashboard page. Confirm no unreadable
- contrast, no token that only works in one theme, and no flash on reload (theme-boot
- working). Run `node scripts/inject-theme-boot.mjs` (dry run) to confirm every real page
- carries the boot.
-7. **Typography & spacing rhythm.** Confirm headings, body, and labels map to the type
- ladder and that section/card padding uses the spacing scale — fix one-off rhythm that
- breaks the φ system.
-8. **Lock it & ship.** Run `npm run build:pages`, `npm run audit:web`, and `npm test`;
- re-grep to confirm the hardcoded-value count dropped (ideally to zero on touched
- files). Add a changelog entry for the visible consistency pass; `npm run build:pages`.
-
-## Must-not
-
-- Do not reintroduce a parallel per-surface palette — remap canonical tokens instead.
-- Do not hardcode a hex/rgba/px that an existing token already expresses.
-- Do not invent a new token name when one exists; only add to `tokens.css` for a genuinely
- new primitive, and document it.
-- Do not ship an interactive element missing hover/active/`:focus-visible`.
-- Do not break the no-flash theme boot or leave a token that fails in one theme.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Touched surfaces reference tokens; hardcoded hex/rgba/raw-px count dropped (zero where feasible).
-- [ ] No parallel palette remains; surface accents are thin remaps of canonical tokens.
-- [ ] Every interactive element has consistent hover, active, and `:focus-visible` states from tokens.
-- [ ] Light and dark themes are correct on home, forge, marketplace, wallet, and a dashboard page; no flash.
-- [ ] Typography and spacing map to the type ladder and φ spacing scale; any new token documented in `DESIGN-TOKENS.md`.
-- [ ] `npm run audit:web` and `npm test` pass.
-- [ ] Changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/14-seo-structured-data.md b/prompts/samples/14-seo-structured-data.md
deleted file mode 100644
index b90c04ad0..000000000
--- a/prompts/samples/14-seo-structured-data.md
+++ /dev/null
@@ -1,90 +0,0 @@
-# 14 — SEO & structured data
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Organic search and well-formed link previews are the cheapest, most durable growth
-channel a platform has. Unique titles and descriptions win impressions; Open Graph and
-Twitter cards turn every shared link into an ad; JSON-LD structured data earns rich
-results; canonicals and a clean sitemap keep crawlers efficient. With ~125 pages, the
-compounding cost of missing or duplicate metadata is enormous — and increasingly,
-LLM-driven discovery reads `llms.txt`. A $1B platform is fully indexable and previews
-beautifully everywhere.
-
-## Mission
-
-Ensure every canonical, indexable page has a unique title and meta description, correct
-Open Graph + Twitter cards, valid JSON-LD, a self-referencing canonical, and that the
-sitemap, robots, and llms.txt all reflect reality — leaning on the existing injection
-tooling rather than hand-editing 125 files.
-
-## Map (trust but verify — files move)
-
-- **SEO injectors (the engine — use these)** — [scripts/inject-seo-meta.mjs](../../scripts/inject-seo-meta.mjs)
- (idempotently backfills `<title>`, description, canonical, OG/Twitter, WebPage/WebSite
- JSON-LD; never overwrites existing tags; re-points stale static OG images at
- `/api/page-og`), [scripts/inject-blog-seo.mjs](../../scripts/inject-blog-seo.mjs) (blog
- posts). Run via `npm run seo:meta`.
-- **Catalog (single source of copy)** — [data/pages.json](../../data/pages.json) feeds
- the injector, sitemap, and llms.txt. Titles/descriptions live here — edit copy here, not
- in 125 HTML heads.
-- **Page index build** — `npm run build:pages` ([scripts/build-page-index.mjs](../../scripts/build-page-index.mjs)),
- audited by [scripts/audit-page-index.mjs](../../scripts/audit-page-index.mjs) (`npm run audit:pages`).
-- **Discovery surfaces** — [public/sitemap/index.html](../../public/sitemap/index.html)
- (human sitemap), [public/robots.txt](../../public/robots.txt),
- [public/llms.txt](../../public/llms.txt) + [public/llms-full.txt](../../public/llms-full.txt).
-- **Dynamic OG cards** — `/api/page-og` (per-page social image) referenced by the injector.
-- **Routing (route → file resolution)** — [vercel.json](../../vercel.json) `routes` table,
- which the injector uses to map a route to its HTML file.
-
-## Do this
-
-1. **Coverage scan.** `npm run seo:meta` in dry-run (read the script's flags) to see which
- pages are missing title / description / canonical / OG / Twitter / JSON-LD. Cross-check
- counts: grep `pages/*.html` for `rel="canonical"`, `og:title`, `application/ld+json` and
- compare against the indexable page count to find the gaps.
-2. **Fix copy at the source.** For every indexable page, ensure `data/pages.json` has a
- **unique**, descriptive title (≤ ~60 chars) and meta description (~120–160 chars) — no
- duplicates, no boilerplate, real human language describing that page's value. This is
- where you edit copy.
-3. **Inject.** Run `npm run seo:meta` (write mode) to backfill title, description,
- canonical, OG, Twitter, and WebPage/WebSite JSON-LD across pages. Confirm it filled gaps
- without clobbering hand-authored tags.
-4. **Richer structured data where it earns rich results.** Beyond WebPage/WebSite, add the
- correct schema.org type to high-value templates: `BreadcrumbList` on nested pages,
- `Product`/`Offer` on marketplace listings, `Article`/`BlogPosting` on blog posts,
- `SoftwareApplication`/`Organization` where appropriate. Validate every block.
-5. **Canonicals & duplicates.** Every page self-references a canonical absolute URL;
- collapse duplicate/parameterized routes onto one canonical. Ensure non-indexable surfaces
- (embeds, widgets, kiosk) are `noindex` and excluded from the sitemap.
-6. **Sitemap, robots, llms.** Regenerate via `npm run build:pages` so the sitemap matches
- the live page set; verify `robots.txt` points to the sitemap and doesn't block indexable
- routes; confirm `llms.txt` / `llms-full.txt` reflect current pages and product framing.
-7. **Validate previews & markup.** Validate JSON-LD (Google Rich Results / Schema.org
- validator) on a sample of each template; check OG/Twitter previews resolve (per-page
- `/api/page-og` image renders, not a single static fallback). `npm run dev` and spot-check
- `<head>` on home, forge, marketplace, a blog post, and an agent profile.
-8. **Verify & ship.** Run `npm run audit:pages` (strict) and `npm test`. Add a changelog
- entry if the SEO improvements are user-visible (e.g. share-preview cards); `npm run build:pages`.
-
-## Must-not
-
-- Do not duplicate titles/descriptions across pages — each must be unique and descriptive.
-- Do not hand-edit metadata into 125 HTML heads — edit `data/pages.json` and run the injector.
-- Do not let the injector overwrite a page's existing hand-authored tags.
-- Do not index embed/widget/kiosk surfaces or list them in the sitemap.
-- Do not ship invalid JSON-LD; validate every block before claiming done.
-- Do not reference any coin other than `$THREE` in any title, description, or structured data.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every indexable page has a unique, descriptive title and meta description (no duplicates).
-- [ ] Every indexable page has a self-referencing canonical, OG + Twitter cards, and valid JSON-LD.
-- [ ] High-value templates carry the right schema type (Product/Article/Breadcrumb/etc.), all validated.
-- [ ] Per-page `/api/page-og` social images render (no single static fallback on shared links).
-- [ ] Sitemap matches the live page set; robots points to it; llms.txt/llms-full.txt are current.
-- [ ] Non-indexable surfaces are `noindex` and excluded from the sitemap.
-- [ ] `npm run audit:pages` (strict) and `npm test` pass; changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/15-forge-text-to-3d-pipeline.md b/prompts/samples/15-forge-text-to-3d-pipeline.md
deleted file mode 100644
index d8ebe5b10..000000000
--- a/prompts/samples/15-forge-text-to-3d-pipeline.md
+++ /dev/null
@@ -1,86 +0,0 @@
-# 15 — Forge / Text→3D / Avatar generation pipeline (production-grade, end-to-end)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-The Forge is the platform's front door: "describe it → get a 3D thing" is the demo
-that makes people screenshot and share. If text→3D, selfie→avatar, or prompt→avatar
-ever shows a spinner that never resolves, a raw vendor error, or a T-posed mesh, the
-core promise breaks and acquisition dies at the first touch. This surface must feel
-instant, never dead-end, and never leak provider internals.
-
-## Mission
-
-Make every generation path — text→3D object, text→avatar, selfie→avatar, image→3D —
-correct, resilient, and beautifully stated in every phase, with the **free NVIDIA NIM
-lane primary** and paid lanes as silent backstops the user never sees billing for.
-
-## Map (trust but verify — files move)
-
-- **Forge UI** — [src/forge.js](../../src/forge.js), [pages/forge.html](../../pages/forge.html),
- [src/forge-showcase.js](../../src/forge-showcase.js), [src/home-forge.js](../../src/home-forge.js).
-- **Prompt→avatar UI** — [src/create-prompt.js](../../src/create-prompt.js),
- [pages/create-prompt.html](../../pages/create-prompt.html). Selfie flow:
- `/create/selfie`.
-- **Text→image (provider chain)** — [api/_mcp3d/text-to-image.js](../../api/_mcp3d/text-to-image.js).
- Free-first cascade: **NVIDIA NIM FLUX → Vertex Imagen → Replicate (paid backstop)**.
-- **Reconstruct + auto-rig** — [api/avatars/_actions.js](../../api/avatars/_actions.js)
- (`handleReconstruct`), [api/_lib/reconstruct-finalize.js](../../api/_lib/reconstruct-finalize.js),
- [api/_lib/regen-provider.js](../../api/_lib/regen-provider.js), [api/_lib/auto-rig.js](../../api/_lib/auto-rig.js).
-- **Backends & tiers** — [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js),
- [api/_lib/forge-health.js](../../api/_lib/forge-health.js) (`GET /api/forge?health`),
- [api/forge.js](../../api/forge.js). Model workers in [workers/](../../workers):
- `model-trellis`, `model-hunyuan3d`, `unirig`, `longcat`.
-- **Tests** — [tests/api/text-to-image.test.js](../../tests/api/text-to-image.test.js),
- `tests/api/forge-free-first.test.js`, `tests/api/forge-fallback.test.js`,
- `tests/api/forge-health.test.js`, `tests/api/reconstruct-finalize.test.js`,
- `tests/forge-avatar-humanoid.test.js`.
-
-## Do this
-
-1. **Exercise every lane in a real browser** (`npm run dev`): text→3D object, prompt→avatar,
- selfie→avatar. Watch the Network tab and console. Confirm the free NIM lane serves
- first (`/api/forge?health` shows `nvidia: ok`).
-2. **No provider internals ever reach the user.** Audit every error path in the chain
- above: billing/credit/quota messages, raw stack traces, and vendor URLs must be
- masked to neutral, actionable copy. Keep raw detail in server logs only.
-3. **Every phase is designed:** reference-image render, reconstruct, rig — each with a
- live label, real elapsed time, and a skeleton/progress affordance (not a fake
- `setTimeout` bar). Empty state tells the user what to type; error state says what
- to do next.
-4. **Resilience:** a hung or throttled free lane must hand off to the next lane within
- a tight timeout, never stall the pipeline. Verify the cascade with the existing
- fallback tests; add cover for any uncovered failure mode (timeout, 402, 429, NSFW,
- no-face, OOM).
-5. **Right page for the input:** plain objects belong on Text→3D; humanoid prompts on
- the avatar flow. Make the routing/affordances obvious so users don't land a "box"
- on the face pipeline.
-6. **Rig quality:** confirm generated humanoids drive the canonical clip library (no
- T-pose fallback unless genuinely non-humanoid, per the `/CLAUDE.md` avatar rule).
-7. **Result handling:** every finished model has a working viewer, a real thumbnail
- (not a 1px snapshot), correct "rigged/static" tagging, and natural next steps
- (open in editor, make another, launch, walk).
-8. Run `npx vitest run tests/api/text-to-image.test.js tests/api/forge-*.test.js
- tests/api/reconstruct-finalize.test.js` and the avatar humanoid test. Add a
- changelog entry for any user-visible change; `npm run build:pages`.
-
-## Must-not
-
-- Do not surface any third party's billing page, credit balance, or raw error to a buyer.
-- Do not add a hardcoded rig allowlist — extend `glb-canonicalize.js` bone maps instead.
-- Do not ship a fake progress bar or a spinner with no timeout.
-- Do not reference any coin other than `$THREE`.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Text→3D, prompt→avatar, and selfie→avatar all complete successfully in a real
- browser with the free NIM lane primary; no console errors/warnings.
-- [ ] Every failure mode (402/429/timeout/NSFW/no-face/OOM/unconfigured) yields a
- neutral, actionable message — no vendor internals, verified by tests.
-- [ ] Loading/empty/error/done states are all designed; elapsed time is real.
-- [ ] Generated humanoids are rigged and animate (no unjustified T-pose); thumbnails render.
-- [ ] All forge/text-to-image/reconstruct tests pass; new failure modes covered.
-- [ ] Changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/16-marketplace.md b/prompts/samples/16-marketplace.md
deleted file mode 100644
index 1c94f3196..000000000
--- a/prompts/samples/16-marketplace.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# 16 — Marketplace (buy, sell & remix)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-The marketplace is where the platform's flywheel becomes a business: creators list
-agents, avatars, skills and animations; buyers discover, try, and pay; remixers fork
-and re-list. If discovery is slow, a buy silently fails, a "fork" lands on a broken
-page, or a listing shows a 1px thumbnail, the supply side stops creating and the demand
-side stops paying — and the GMV that justifies a $1B valuation never accrues. This
-surface must feel like Vercel's template gallery crossed with Stripe-grade checkout.
-
-## Mission
-
-Make the full marketplace loop — list → browse/search/sort/filter → detail → buy/sell/remix
-→ settled payment → linked profile — correct, fast, and beautifully stated in every state,
-with real USDC settlement and zero dead paths.
-
-## Map (trust but verify — files move)
-
-- **List + detail controller (SPA)** — [src/marketplace.js](../../src/marketplace.js)
- (list view with category sidebar + search; detail with 5 tabs; path routing
- `/marketplace` and `/marketplace/agents/:id`), [src/marketplace-detail.js](../../src/marketplace-detail.js)
- (3D avatar in header, live "try before you fork" SSE chat preview, creator modal,
- mobile sidebar), [pages/marketplace.html](../../pages/marketplace.html) (loads
- `/src/marketplace.js`; route `/marketplace` in [vercel.json](../../vercel.json)).
-- **Lobby / detail-market helpers** — [src/marketplace-lobby.js](../../src/marketplace-lobby.js),
- [src/agent-detail-market.js](../../src/agent-detail-market.js).
-- **Analytics surface** — [src/marketplace-analytics.js](../../src/marketplace-analytics.js),
- [pages/marketplace-analytics.html](../../pages/marketplace-analytics.html),
- [api/marketplace/analytics.js](../../api/marketplace/analytics.js).
-- **Marketplace API** — [api/marketplace/[action].js](../../api/marketplace/[action].js)
- (categories, agents list `?category=&q=&sort=&cursor=&pricing=`, create/mine/detail/versions/similar/fork/bookmark/publish/view),
- [api/marketplace/purchase.js](../../api/marketplace/purchase.js),
- [api/marketplace/purchase-as-agent.js](../../api/marketplace/purchase-as-agent.js),
- [api/marketplace/purchase-bundle.js](../../api/marketplace/purchase-bundle.js),
- [api/marketplace/buy-asset.js](../../api/marketplace/buy-asset.js),
- [api/marketplace/asset-price.js](../../api/marketplace/asset-price.js),
- [api/marketplace/set-skill-price.js](../../api/marketplace/set-skill-price.js),
- [api/marketplace/reviews.js](../../api/marketplace/reviews.js),
- [api/marketplace/start-trial.js](../../api/marketplace/start-trial.js),
- [api/marketplace/animations.js](../../api/marketplace/animations.js),
- [api/marketplace/check-skill-access.js](../../api/marketplace/check-skill-access.js).
-- **Cross-links** — agent profiles via [src/shared/agent-3d.js](../../src/shared/agent-3d.js)
- (`seeInWorldHref`, `hasCustomAvatar`), `/agents/:id` ([pages/agent-detail.html](../../pages/agent-detail.html)),
- avatar/animation galleries ([pages/animations.html](../../pages/animations.html),
- [api/avatars/](../../api/avatars)). Shared state kit:
- [src/shared/state-kit.js](../../src/shared/state-kit.js) (skeleton/empty/error),
- [src/shared/list-controls.js](../../src/shared/list-controls.js) (`debounce`, `syncStateToUrl`).
-- **Payments** — settlement runs through the x402 + agent-wallet plumbing in
- [api/_lib/](../../api/_lib) (see prompt `18`). Platform fee logic is exercised by
- [tests/api/marketplace-platform-fee.test.js](../../tests/api/marketplace-platform-fee.test.js).
-- **Tests** — [tests/api/marketplace-agent-detail-prices.test.js](../../tests/api/marketplace-agent-detail-prices.test.js),
- [tests/api/marketplace-agent-detail-subscriptions.test.js](../../tests/api/marketplace-agent-detail-subscriptions.test.js),
- [tests/api/marketplace-animations.test.js](../../tests/api/marketplace-animations.test.js),
- [tests/api/marketplace-platform-fee.test.js](../../tests/api/marketplace-platform-fee.test.js).
-
-## Do this
-
-1. **Exercise the whole loop in a real browser** (`npm run dev`, port 3000): open
- `/marketplace`, browse, search, switch categories, change sort, filter by pricing,
- open a detail page, run the live chat preview, fork an agent, and buy a paid skill.
- Watch the Network tab — every call (`/api/marketplace/...`) must return real data,
- 200/4xx with intent, never a silent hang.
-2. **Design every list state:** skeleton on load (use `state-kit.js`), helpful empty
- state for "no results in this category / no matches for this query" (offer a reset
- action — don't show a void), an error state with retry, and overflow handling for
- 1000+ listings (cursor pagination via `?cursor=`, not a giant DOM). Persist
- search/sort/filter to the URL with `syncStateToUrl` so results are shareable and
- back-button-safe; debounce the search input.
-3. **Sort + filter must actually work end-to-end.** Confirm each `sort` value and the
- `pricing` filter map to real SQL ordering/filtering in `[action].js` (not a no-op).
- If a control renders but does nothing, wire it or remove it — no dead controls.
-4. **Detail view is complete:** real 3D avatar in the header (not an emoji placeholder),
- working tabs, accurate pricing (one-time / subscription / time-pass), reviews
- ([reviews.js](../../api/marketplace/reviews.js)), version history, "similar" agents,
- and a creator modal that lists the author's other agents and avatars. Every link
- resolves to a live page; every CTA does something.
-5. **Buy/sell/remix flows settle for real:** a purchase posts to `purchase.js` /
- `buy-asset.js` / `purchase-bundle.js`, returns a real receipt, and grants access
- (verify with `check-skill-access.js`). A "fork" creates a real editable copy and
- routes the user to it. Selling: a creator can set a price (`set-skill-price.js`,
- `asset-price.js`) and see it reflected in the listing. Never fake a success toast
- without a settled transaction.
-6. **Payment failure is designed, not leaked:** insufficient funds, declined, network
- timeout, and idempotent retry all yield neutral, actionable copy and never surface a
- provider's billing page or a raw stack trace. Reuse the x402 error helpers from
- prompt `18`. A second click on "buy" must not double-charge.
-7. **Cross-pollinate the platform:** every listing links to the agent's public profile
- (`/agents/:id`), to "see in world", and to the avatar/animation gallery where
- relevant. A bought animation should be usable in the editor; a forked agent should
- open in Agent Studio. Wire these connections — a marketplace that doesn't link out
- is half-built.
-8. **Accessibility + microinteractions:** category sidebar is keyboard-navigable, every
- card/button has hover/active/focus states, the mobile hamburger sidebar traps focus,
- and `pricing`/`sort` controls are labeled. Test mentally at 320 / 768 / 1440.
-9. **Run the tests and ship the changelog:** `npx vitest run tests/api/marketplace-*.test.js`.
- Add a `data/changelog.json` entry for any user-visible change, then `npm run
- build:pages` (it validates the entry).
-
-## Must-not
-
-- Do not show a fake success state, a fake progress bar, or a toast without a settled
- on-chain/x402 transaction.
-- Do not leak any third party's billing page, credit balance, or raw error to a buyer —
- mask to neutral copy; keep detail in server logs.
-- Do not reference, list, or recommend any coin other than `$THREE` (CA
- `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Runtime launch records the user
- created are fine; hardcoded mints are not.
-- Do not leave dead controls (a sort/filter/tab/button that renders but does nothing).
-- Do not break the existing detail SPA routing, the SSE chat preview, or the platform-fee math.
-- No mocks, no sample-listing arrays shipped to production, no TODOs.
-
-## Acceptance (all true before claiming done)
-
-- [ ] List, search, sort, filter, detail, buy, sell, fork all work in a real browser
- with real `/api/marketplace/*` calls; no console errors or warnings.
-- [ ] Loading (skeleton), empty (with reset CTA), error (with retry), populated, and
- 1000+-item overflow (cursor pagination) states are all designed.
-- [ ] Search/sort/filter persist to the URL and survive a refresh and back button.
-- [ ] A purchase settles real USDC, returns a receipt, grants access; a second click
- does not double-charge; failures show neutral, actionable copy with no vendor internals.
-- [ ] Detail header shows a real 3D avatar + real thumbnail; every link/CTA resolves
- to a live page (profile, see-in-world, editor, gallery).
-- [ ] Every interactive element has hover/active/focus states; layout holds at 320/768/1440;
- keyboard navigation works.
-- [ ] `npx vitest run tests/api/marketplace-*.test.js` passes.
-- [ ] Changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/17-agent-profiles-studio-economy.md b/prompts/samples/17-agent-profiles-studio-economy.md
deleted file mode 100644
index 4e6e8bb59..000000000
--- a/prompts/samples/17-agent-profiles-studio-economy.md
+++ /dev/null
@@ -1,142 +0,0 @@
-# 17 — Agent profiles, Agent Studio & economy
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-An agent is the platform's atomic unit of value: people create one, give it a brain,
-memory, body, money, and skills, publish a profile, build reputation, and let it earn
-and delegate. If the creation wizard dead-ends, the Studio shows a "mounts here"
-placeholder, a public profile 404s, or reputation is decorative, the supply side never
-compounds and there's no economy to scale. The best version feels like Linear's polish
-applied to "spin up an autonomous, earning, on-chain agent."
-
-## Mission
-
-Make the full agent lifecycle — create → configure (Brain · Memory · Body · Money ·
-Skills, with a live avatar) → publish profile → earn reputation → appear in the activity
-feed → delegate to other agents — complete, wired, and every state designed.
-
-## Map (trust but verify — files move)
-
-- **Creation wizard** — [src/create-agent.js](../../src/create-agent.js) (5 steps:
- basics → 3D model → skills → personality → review; writes through `/api/agents` and
- `/api/marketplace/agents/:id/publish`), [pages/create-agent.html](../../pages/create-agent.html)
- (route `/create-agent`).
-- **Agent Studio (Brain/Memory/Body/Money/Skills)** — [pages/agent-studio.html](../../pages/agent-studio.html)
- (route `/agent-studio`; loads [src/studio/studio-shell.js](../../src/studio/studio-shell.js)
- which defines the five tabs + empty "mounts here" states),
- [src/studio/brain/](../../src/studio/brain) (`brain-mount.js`, `brain-studio.js`,
- `brain-graph.js`, `brain-compile.js`, `brain-runtime.js`, `brain-templates.js`,
- `brain-nodes.js`), [src/studio/memory/](../../src/studio/memory) (`memory-mount.js`,
- `memory-studio.js`, `memory-graph.js`, `memory-client.js`),
- [src/studio/agent-studio-store.js](../../src/studio/agent-studio-store.js),
- [src/studio/agent-presence.js](../../src/studio/agent-presence.js). Live avatar via
- [src/agent-avatar.js](../../src/agent-avatar.js) / [src/shared/agent-3d.js](../../src/shared/agent-3d.js).
- Note: **Brain and Memory mount real studios; Body, Money, and Skills currently render
- placeholder empty states** in `studio-shell.js` — finish them.
-- **Launch/fees/knowledge studio (`/studio`)** — [public/studio/](../../public/studio)
- (`studio.js`, `launch-panel.js`, `fees-panel.js`, `knowledge-panel.js`; route `/studio`).
-- **Public profiles** — [pages/profile.html](../../pages/profile.html) (route `/u/:name`),
- [pages/agent-detail.html](../../pages/agent-detail.html) + [src/agent-detail.js](../../src/agent-detail.js)
- + [src/agent-detail.css](../../src/agent-detail.css) (route `/agents/:id`),
- [api/agents/public.js](../../api/agents/public.js), [api/agents/[id].js](../../api/agents/[id].js),
- [api/agents/by-wallet.js](../../api/agents/by-wallet.js), [api/agents/featured.js](../../api/agents/featured.js).
-- **Economy** — [pages/agent-economy.html](../../pages/agent-economy.html) +
- [src/agent-economy.js](../../src/agent-economy.js) (two 3D agents transacting real SOL;
- route `/agent-economy`), [src/agent-skills.js](../../src/agent-skills.js) and the
- `src/agent-skills-*.js` family, agent wallet via [src/agent-wallet.js](../../src/agent-wallet.js)
- (see prompt `18`).
-- **ERC-8004 reputation** — on-chain registries in [contracts/src/](../../contracts/src)
- (`IdentityRegistry.sol`, `ReputationRegistry.sol`, `ValidationRegistry.sol`),
- [api/agents/8004/agent.js](../../api/agents/8004/agent.js), [api/agents/8004/search.js](../../api/agents/8004/search.js),
- and the MCP `agent_reputation` tool. Onchain badge: [src/shared/onchain-badge.js](../../src/shared/onchain-badge.js).
-- **Agent-to-agent delegation** — [api/agents/a2a-call.js](../../api/agents/a2a-call.js),
- [api/agents/a2a-mandate.js](../../api/agents/a2a-mandate.js),
- [api/agents/a2a-paid.js](../../api/agents/a2a-paid.js),
- [api/agents/a2a-cart-verify.js](../../api/agents/a2a-cart-verify.js),
- [src/agent-skills-a2a.js](../../src/agent-skills-a2a.js).
-- **Tests** — [tests/agent-protocol.test.js](../../tests/agent-protocol.test.js),
- [tests/agent-a2a-payments.test.js](../../tests/agent-a2a-payments.test.js),
- [tests/api-agent-memory.test.js](../../tests/api-agent-memory.test.js),
- [tests/brain-studio-compile.test.js](../../tests/brain-studio-compile.test.js),
- [tests/studio-launch-panel.test.js](../../tests/studio-launch-panel.test.js),
- [tests/studio-fees-panel.test.js](../../tests/studio-fees-panel.test.js),
- [tests/agent-detail-avatar.test.js](../../tests/agent-detail-avatar.test.js).
-
-## Do this
-
-1. **Run the wizard end-to-end in a real browser** (`npm run dev`): `/create-agent`,
- complete all 5 steps, attach a 3D model, pick skills, set personality, publish.
- Confirm a real agent row is created via `/api/agents` and (if chosen) listed via the
- marketplace publish endpoint. Watch the Network tab — no silent failures, every step
- validates input before advancing.
-2. **Finish Agent Studio.** Brain and Memory mount real studios; **build Body, Money,
- and Skills to the same bar** — replace the placeholder empty states in
- `studio-shell.js` with real, wired panels: Body (attach/preview avatar, outfit,
- animations driving the canonical clip library), Money (fund wallet, set per-skill
- pricing, view payouts — reuse the wallet plumbing from prompt `18`), Skills
- (toggle/configure capabilities, set what's sellable). A **live avatar preview**
- reflects Body changes immediately. Persist via `agent-studio-store.js`.
-3. **Every Studio state is designed:** loading skeleton per tab, empty state that tells
- the user what to do (not "mounts here"), error state with recovery, and a clear save
- /dirty indicator. No tab may ship a dead placeholder.
-4. **Public profiles are complete and shareable:** `/u/:name` and `/agents/:id` render
- the real 3D avatar, bio, skills, pricing, reputation, owned coins, and an **activity
- feed** of real events (creations, sales, delegations, reputation changes). Design
- loading/empty/error/overflow. Every CTA (talk, hire, see-in-world, fork, open in
- studio) resolves to a live page. Profile OG images render.
-5. **ERC-8004 reputation is real, not decorative:** the onchain badge reflects actual
- registry data (identity / reputation / validation) read via `api/agents/8004/*` and
- the `agent_reputation` MCP tool. Show a designed state when an agent isn't yet
- on-chain (with a path to register), and never a broken/empty badge.
-6. **Agent economy works for real:** on `/agent-economy`, the two agents transact real
- SOL (existing pattern), balances poll live, the tx feed links to an explorer, and
- failures (insufficient funds, RPC hiccup) show neutral, actionable copy with an
- add-funds path. No fake particle "success" without a confirmed tx.
-7. **Agent-to-agent delegation is wired:** one agent can delegate a paid action to
- another (`a2a-call` / `a2a-mandate` / `a2a-paid`) with spend caps respected,
- idempotent settlement, and a result surfaced in the activity feed. Exercise the
- delegation path and confirm it appears on both agents' profiles.
-8. **Cross-pollinate:** profile ↔ marketplace listing ↔ Agent Studio ↔ wallet ↔
- economy must all link both directions. A user who lands on any one surface can reach
- the others naturally. Audit for dead paths and unreachable states.
-9. **Accessibility + responsiveness:** wizard steps and Studio tabs are keyboard- and
- screen-reader-navigable with focus management; layout holds at 320 / 768 / 1440;
- every interactive element has hover/active/focus states.
-10. **Run the tests and ship the changelog:** `npx vitest run tests/agent-*.test.js
- tests/studio-*.test.js tests/brain-studio-compile.test.js tests/api-agent-memory.test.js`.
- Add a `data/changelog.json` entry for user-visible changes, then `npm run build:pages`.
-
-## Must-not
-
-- Do not leave Body, Money, or Skills as "mounts here" placeholders — finish them or
- do not claim done.
-- Do not ship a decorative reputation badge — it must reflect real ERC-8004 registry data.
-- Do not fake economy/delegation success without a confirmed on-chain/x402 transaction.
-- Do not reference, list, or recommend any coin other than `$THREE` (CA
- `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime user-launch records are fine.
-- Do not break the existing wizard write-through, the Brain/Memory studios, or the
- custodial wallet flow.
-- No mocks, no fake activity-feed data, no TODOs, no T-pose fallback for humanoids
- (extend `glb-canonicalize.js` bone maps, per `/CLAUDE.md`).
-
-## Acceptance (all true before claiming done)
-
-- [ ] The 5-step wizard creates a real agent and optionally publishes it; input is
- validated at each step; no console errors/warnings.
-- [ ] Agent Studio Brain, Memory, Body, Money, and Skills tabs are all real and wired,
- with a live avatar preview reacting to Body changes; each tab has designed
- loading/empty/error states.
-- [ ] `/u/:name` and `/agents/:id` render real avatar + data + an activity feed of real
- events; OG images render; every CTA resolves to a live page.
-- [ ] The onchain reputation badge reflects real ERC-8004 data and has a designed
- not-yet-registered state.
-- [ ] Agent economy and a2a delegation settle real transactions with spend caps,
- idempotency, and neutral failure copy; results show in the activity feed.
-- [ ] All listed surfaces link to each other (no dead paths); layout holds at
- 320/768/1440; keyboard navigation works.
-- [ ] `npx vitest run tests/agent-*.test.js tests/studio-*.test.js tests/brain-studio-compile.test.js tests/api-agent-memory.test.js` passes.
-- [ ] Changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/18-wallet-x402-payments.md b/prompts/samples/18-wallet-x402-payments.md
deleted file mode 100644
index 4938c55a4..000000000
--- a/prompts/samples/18-wallet-x402-payments.md
+++ /dev/null
@@ -1,148 +0,0 @@
-# 18 — Wallet & x402 payments
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-Payments are the platform's bloodstream: every marketplace buy, paid skill call, agent
-delegation, and creator payout flows through the custodial agent wallet and the x402
-protocol. If a payment double-settles, an idempotency key collides, a custodial secret
-is mishandled, or a verify/settle silently fails, the platform loses money and trust —
-and trust is the only currency a payments business actually has. Stripe is the bar:
-correct to the cent, reconcilable, never leaks internal state, every failure recoverable.
-
-## Mission
-
-Make the agent wallet and the x402 paid-endpoint stack — custody, verify, settle,
-idempotency, USDC on Solana and Base, send/fund/trade/pay, Solana Pay, and reconciliation
-— provably correct, resilient, and beautifully stated in every state, end to end.
-
-## Map (trust but verify — files move)
-
-- **Custody** — [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js)
- (`generateSolanaAgentWallet`, `getOrCreateAgentSolanaWallet`, `getOrCreateAgentEvmWallet`,
- `recoverAgentKey`, `delegatedSpend`, `triggerSkillPayment`, `getAgentBalance`,
- `canAfford`), [api/_lib/secret-box.js](../../api/_lib/secret-box.js) (`encryptSecret`/
- `decryptSecret`, `v2:` envelope), [api/_lib/solana-wallet.js](../../api/_lib/solana-wallet.js),
- [api/_lib/avatar-wallet.js](../../api/_lib/avatar-wallet.js). Custody design doc:
- [docs/internal/AGENT-WALLET-CUSTODY.md](../../docs/internal/AGENT-WALLET-CUSTODY.md) — **read it first.**
-- **x402 protocol core** — [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js)
- (version 2, network constants for Base/Arbitrum/BSC/Solana, permit2 variants),
- [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) (`paidEndpoint(spec)`
- wrapper), [api/_lib/x402/payment-identifier-server.js](../../api/_lib/x402/payment-identifier-server.js)
- (idempotency), [api/_lib/x402-errors.js](../../api/_lib/x402-errors.js),
- [api/_lib/x402-solana-confirm.js](../../api/_lib/x402-solana-confirm.js),
- [api/_lib/evm-payment-verify.js](../../api/_lib/evm-payment-verify.js),
- [api/_lib/x402-spending-cap.js](../../api/_lib/x402-spending-cap.js),
- [api/_lib/x402-spending-ledger.js](../../api/_lib/x402-spending-ledger.js),
- [api/_lib/x402-builder-code.js](../../api/_lib/x402-builder-code.js),
- [api/_lib/x402-prices.js](../../api/_lib/x402-prices.js).
-- **Paid endpoints** — [api/x402/](../../api/x402) (e.g. `forge.js`, `skill-call.js`,
- `skill-marketplace.js`, `pay-by-name.js`, `my-receipts.js`, `did.js`,
- `agent-reputation.js`), [api/x402-pay.js](../../api/x402-pay.js),
- [api/payments/solana/[action].js](../../api/payments/solana/[action].js),
- [api/webhooks/solana-pay.js](../../api/webhooks/solana-pay.js) (Solana Pay).
-- **Wallet UI** — [pages/agent-wallet.html](../../pages/agent-wallet.html) (route
- `/agents/:id/wallet`), [src/agent-wallet.js](../../src/agent-wallet.js),
- [src/agent-wallet-hub/](../../src/agent-wallet-hub) (`index.js`, `registry.js`,
- `tabs/` → `balance.js`, `deposit.js`, `withdraw.js`, `give.js`, `pay.js`, `trade.js`,
- `snipe.js`, `vanity.js`), [src/agent-x402-pay.js](../../src/agent-x402-pay.js),
- [src/payment-modal.js](../../src/payment-modal.js), [src/forge-pay.js](../../src/forge-pay.js),
- [src/shared/add-funds.js](../../src/shared/add-funds.js),
- [src/shared/payment-receipt.js](../../src/shared/payment-receipt.js).
-- **The /pay page** — [public/pay/index.html](../../public/pay/index.html) (route `/pay`).
-- **Skills (real, end-user)** — `authenticate-wallet`, `fund`, `send-usdc`, `trade`,
- `pay-for-service` (USDC on Base/Polygon/Solana, send/fund/trade/x402 pay).
-- **SDKs** — [solana-agent-sdk/](../../solana-agent-sdk), [agent-payments-sdk/](../../agent-payments-sdk).
-- **Tests** — [tests/api/x402-paid-endpoint-replay.test.js](../../tests/api/x402-paid-endpoint-replay.test.js),
- [tests/api/x402-payment-identifier.test.js](../../tests/api/x402-payment-identifier.test.js),
- [tests/api/x402-spec.test.js](../../tests/api/x402-spec.test.js),
- [tests/api/x402-security-fixes.test.js](../../tests/api/x402-security-fixes.test.js),
- [tests/api/x402-pay-routing.test.js](../../tests/api/x402-pay-routing.test.js),
- [tests/api/x402-gas-sponsoring.test.js](../../tests/api/x402-gas-sponsoring.test.js),
- [tests/agent-custody-guards.test.js](../../tests/agent-custody-guards.test.js),
- [tests/agent-wallet-pay-tab.test.js](../../tests/agent-wallet-pay-tab.test.js)
- (and the `agent-wallet-*-tab` family), [tests/api/solana-wallet-balance.test.js](../../tests/api/solana-wallet-balance.test.js).
-
-## Do this
-
-1. **Read the custody doc first** ([docs/internal/AGENT-WALLET-CUSTODY.md](../../docs/internal/AGENT-WALLET-CUSTODY.md)),
- then exercise the wallet in a real browser (`npm run dev`): open `/agents/:id/wallet`,
- walk every tab — balance, deposit, withdraw, give, pay, trade — and the `/pay` page.
- Watch the Network tab: every settlement is a real on-chain/x402 transaction with a
- real signature, never a fake toast.
-2. **Custody safety:** confirm secrets are only ever stored encrypted (`secret-box.js`
- `v2:` envelope) and decrypted in-memory at the moment of signing, never logged,
- returned to the client, or persisted in plaintext. Verify `recoverAgentKey` audit
- hooks fire. The custody guard tests must pass and cover the decrypt path.
-3. **Idempotency is bulletproof:** using `payment-identifier-server.js`, a replayed
- payment payload or a double-clicked "pay" must settle exactly once and return the
- original receipt — never double-charge, never error opaquely. Verify with the replay
- and payment-identifier tests; add cover for any uncovered race (concurrent identical
- requests).
-4. **Verify + settle on both chains:** confirm USDC payments verify and settle correctly
- on **Solana** (`x402-solana-confirm.js`, the `solana:5eykt4...` mainnet constant) and
- **Base** (`evm-payment-verify.js`, `eip155:8453`), including Solana Pay
- (`api/webhooks/solana-pay.js`, `api/payments/solana/`). Spending caps
- (`x402-spending-cap.js`) and the ledger (`x402-spending-ledger.js`) are enforced
- before settlement.
-5. **send / fund / trade / pay all complete for real:** sending USDC, funding (on-ramp/
- add-funds), trading, and paying an x402 endpoint each produce a confirmed transaction,
- a real receipt (`payment-receipt.js`), and an updated balance. Insufficient funds
- routes to a real add-funds path, not a dead error.
-6. **Every state is designed:** wallet loading skeleton, zero-balance empty state with a
- clear fund CTA, pending-tx state with real status (not a fake spinner), confirmed
- state with explorer link + receipt, and an error state that says what failed and how
- to recover. Reconciliation: a tx that confirms on-chain but whose callback was lost
- is reconciled (poll/webhook) so the UI and ledger never drift.
-7. **No provider internals leak:** RPC errors, gas/fee failures, throttling (429), and
- declined payments are masked to neutral, actionable copy via `x402-errors.js`; raw
- detail stays in server logs. Use the existing **cockatiel** resilience helper for
- RPC retries/circuit-breaking — a single flaky RPC must not strand a payment.
-8. **Reliability + reconciliation pass:** confirm a retried RPC, a dropped webhook, and a
- timed-out confirm all converge to a single correct ledger state with a re-fetchable
- receipt (`api/x402/my-receipts.js`). No money is lost or double-counted under failure.
-9. **Accessibility + microinteractions:** wallet tabs are keyboard-navigable with focus
- management, amounts use accessible inputs with validation, every action has
- hover/active/focus/disabled states, and the layout holds at 320 / 768 / 1440.
-10. **Run the tests and ship the changelog:** `npx vitest run tests/api/x402-*.test.js
- tests/agent-custody-guards.test.js tests/agent-wallet-*-tab.test.js
- tests/api/solana-wallet-balance.test.js`. Add a `data/changelog.json` entry for any
- user-visible change, then `npm run build:pages`.
-
-## Must-not
-
-- Never log, return to the client, or persist a wallet secret in plaintext; decrypt only
- in-memory at signing time.
-- Never double-settle: a replayed or double-clicked payment must settle exactly once and
- return the original receipt.
-- Never leak a provider's billing page, RPC internals, gas error, or raw stack trace to a
- user — mask via `x402-errors.js`; keep detail in server logs.
-- Do not reference, list, or recommend any coin other than `$THREE` (CA
- `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); the only payment token here is USDC and
- generic runtime-supplied mints.
-- Do not weaken or bypass spending caps, the spending ledger, or the idempotency layer to
- "make it work."
-- No mocks of the RPC/x402 stack, no fake receipts, no fake balances, no TODOs.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every wallet tab (balance/deposit/withdraw/give/pay/trade) and the `/pay` page
- complete real settlements with real signatures in a real browser; no console
- errors/warnings.
-- [ ] Wallet secrets are encrypted at rest (`v2:` envelope), decrypted only in-memory at
- signing, never logged or returned; custody guard tests pass.
-- [ ] A replayed/double-clicked payment settles exactly once and returns the original
- receipt; replay + payment-identifier tests pass.
-- [ ] USDC verify/settle works on both Solana and Base (and via Solana Pay); spending
- caps and ledger are enforced pre-settlement.
-- [ ] send/fund/trade/pay each produce a confirmed tx, a real receipt, and an updated
- balance; insufficient funds routes to a real fund path.
-- [ ] Loading/empty(zero-balance)/pending/confirmed/error states are all designed;
- dropped webhooks and timed-out confirms reconcile to a single correct ledger state.
-- [ ] No provider internals leak on any failure (verified by tests); RPC failures use
- cockatiel retry/circuit-breaking.
-- [ ] `npx vitest run tests/api/x402-*.test.js tests/agent-custody-guards.test.js tests/agent-wallet-*-tab.test.js tests/api/solana-wallet-balance.test.js` passes.
-- [ ] Changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/samples/23-mcp-servers-production.md b/prompts/samples/23-mcp-servers-production.md
deleted file mode 100644
index 39d858ad2..000000000
--- a/prompts/samples/23-mcp-servers-production.md
+++ /dev/null
@@ -1,99 +0,0 @@
-# 23 — MCP servers (production-ready)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-MCP is how agents — Claude, Cursor, every autonomous buyer — actually reach
-three.ws. If a manifest drifts, a remote endpoint stops answering its payment
-challenge, or the one free lane (`forge_free`) silently breaks, the entire
-agent-to-agent distribution channel goes dark and we lose the buyers who never
-touch a browser. A registry-clean, smoke-passing, correctly-priced MCP surface
-is the difference between "an app" and "a protocol other agents build on."
-
-## Mission
-
-Make every three.ws MCP server publishable and reliable: valid registry
-manifests, passing smokes, correct per-tool x402 pricing, a working free
-`forge_free` lane, and spec-compliant `PaymentRequired` transport — so a fresh
-agent can discover and call our tools with zero hand-holding.
-
-## Map (trust but verify — files move)
-
-- **Hosted 3D-Agent MCP (remote)** — [api/mcp-3d.js](../../api/mcp-3d.js), backed by
- [api/_mcp3d/catalog.js](../../api/_mcp3d/catalog.js) (tool list + discovery copy),
- [api/_mcp3d/dispatch.js](../../api/_mcp3d/dispatch.js), [api/_mcp3d/pricing.js](../../api/_mcp3d/pricing.js)
- (per-tool USDC), [api/_mcp3d/discovery.js](../../api/_mcp3d/discovery.js), and the
- tool implementations in [api/_mcp3d/tools/studio.js](../../api/_mcp3d/tools/studio.js)
- (`forge_free` lives here — the ONE free tool: NVIDIA NIM / Microsoft TRELLIS text→3D).
-- **Other remote endpoints** — [api/mcp.js](../../api/mcp.js), [api/mcp-agent.js](../../api/mcp-agent.js),
- [api/mcp-bazaar.js](../../api/mcp-bazaar.js), [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js)
- (free, $THREE-only probe), [api/ibm-mcp.js](../../api/ibm-mcp.js).
-- **stdio MCP packages** — [mcp-server/](../../mcp-server), [mcp-bridge/](../../mcp-bridge),
- [packages/pumpfun-mcp/](../../packages/pumpfun-mcp), [packages/avatar-agent-mcp/](../../packages/avatar-agent-mcp),
- [packages/threews-avatar-mcp/](../../packages/threews-avatar-mcp), [packages/three-token-mcp/](../../packages/three-token-mcp),
- [packages/ibm-watsonx-mcp/](../../packages/ibm-watsonx-mcp), [packages/ibm-x402-mcp/](../../packages/ibm-x402-mcp).
-- **x402 spec helper** — [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) (builds the
- `PaymentRequired` / `accepts[]` challenge as `structuredContent`).
-- **Manifests** — each package's `server.json` + root `server*.json` (remote manifests).
-- **Tooling** — `npm run audit:mcp` ([scripts/audit-mcp-manifests.mjs](../../scripts/audit-mcp-manifests.mjs)),
- `smoke:mcp` ([scripts/smoke-mcp-remotes.mjs](../../scripts/smoke-mcp-remotes.mjs)),
- `test:mcp` ([scripts/test-mcp-all.mjs](../../scripts/test-mcp-all.mjs)),
- `publish:mcp:dry` ([scripts/publish-mcp-servers.mjs](../../scripts/publish-mcp-servers.mjs)).
-
-## Do this
-
-1. **Audit manifests:** run `npm run audit:mcp`. Fix every violation — description
- ≤ 100 chars, `name` in `io.github.<owner>/<server>` form, https icons/URLs, and
- for stdio packages the `server.json` version MUST equal the package's `package.json`
- version (and `packages[0].identifier/version` + `mcpName` must match). Do not bump
- a version to dodge a real mismatch — align them.
-2. **Smoke the remotes:** run `npm run smoke:mcp http://localhost:3000` against
- `npm run dev`, then against `https://three.ws`. Free endpoints must answer
- `initialize` + `tools/list` and run a read-only tool; paid endpoints must return
- a well-formed 401/402 with a valid `accepts[]` challenge. Fix any unhealthy one.
-3. **Verify the free lane:** call `forge_free` end-to-end (no wallet, no key) and
- confirm it returns a real GLB URL + a three.ws viewer link via the NVIDIA NIM /
- TRELLIS path. It must NEVER demand payment. Confirm it is the only free generation
- tool in `catalog.js`.
-4. **Price every paid tool correctly:** in `api/_mcp3d/pricing.js`, confirm generation
- tools price by tier from `forge-tiers.js` (same numbers as `POST /api/x402/forge`),
- mesh edits carry their flat per-call USDC, and read-only tools (status/preview/
- inspection) stay free. No tool may settle for the env minimum when it costs more.
-5. **Spec compliance:** confirm an un-paid call to a paid tool returns a
- `PaymentRequired` result whose `structuredContent.accepts[]` carries valid
- requirements (asset = USDC, correct `payTo`, atomic amount) — built via
- `api/_lib/x402-spec.js`, not hand-rolled. Verify on both Base and Solana rails.
-6. **Run the full MCP suite:** `npm run test:mcp -- --no-remote` (offline: manifests +
- each stdio package's `node --test`), then `npm run test:mcp http://localhost:3000`
- (with the live layer). All green.
-7. **Dry-run the publish:** `npm run publish:mcp:dry`. It must validate every manifest
- and report cleanly with no auth/version errors.
-8. **Docs + versioning:** each stdio package README must list its tools, install/run
- command, and a real call example. Bump versions only for genuine changes (semver),
- keeping `server.json` and `package.json` in lockstep. Add a `data/changelog.json`
- entry (tag `sdk` or `infra`) for any user-visible MCP change, then `npm run build:pages`.
-
-## Must-not
-
-- Do not gate `forge_free` behind payment, a wallet, or an API key — it is the free lane.
-- Do not hardcode any mint other than `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`)
- in probes, fixtures, or docs; the pump-fun probe must stay $THREE-only.
-- Do not hand-roll the `PaymentRequired` challenge — use `api/_lib/x402-spec.js`.
-- Do not let a generation tool settle for the env-minimum price; price it by tier.
-- Do not commit a `server.json`/`package.json` version mismatch or a >100-char description.
-- Do not weaken or skip a smoke/manifest check to make the suite pass.
-
-## Acceptance (all true before claiming done)
-
-- [ ] `npm run audit:mcp` passes with zero violations.
-- [ ] `npm run smoke:mcp` passes against both `localhost:3000` and `https://three.ws`.
-- [ ] `forge_free` returns a real GLB URL + viewer link with no payment, wallet, or key.
-- [ ] Every paid tool prices correctly (generation by tier, mesh edits flat, read-only free);
- paid tools return a valid `PaymentRequired` `structuredContent.accepts[]` on Base + Solana.
-- [ ] `npm run test:mcp -- --no-remote` and `npm run test:mcp http://localhost:3000` both pass.
-- [ ] `npm run publish:mcp:dry` reports clean for every server.
-- [ ] Every stdio package README documents tools + a real call example; versions are in lockstep.
-- [ ] Changelog updated (if user-visible) and `npm run build:pages` is clean.
diff --git a/prompts/samples/24-sdk-publishing-docs.md b/prompts/samples/24-sdk-publishing-docs.md
deleted file mode 100644
index fdb5aea8f..000000000
--- a/prompts/samples/24-sdk-publishing-docs.md
+++ /dev/null
@@ -1,93 +0,0 @@
-# 24 — SDK publishing & docs
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-The SDKs are how other teams build *on* three.ws instead of competing with it —
-a `<agent-3d>` viewer in someone else's app, an agent paying an x402 endpoint
-from another platform, a walk companion on a third party's homepage. A broken
-`files[]`, a README example that doesn't run, or a `npm install @three-ws/avatar`
-that throws on a fresh machine, and a would-be integrator bounces forever. Clean,
-documented, dry-run-verified packages turn three.ws into infrastructure.
-
-## Mission
-
-Every published SDK has a correct `package.json` (exports, `files[]`, semver),
-a README with real working examples, a clean dry-run publish, and a working
-demo/example — so an external developer can install it and ship in minutes.
-
-## Map (trust but verify — files move)
-
-- **Top-level SDKs** (published, not workspaces) — [sdk/](../../sdk) (`@three-ws/sdk`),
- [solana-agent-sdk/](../../solana-agent-sdk) (`@three-ws/solana-agent`),
- [agent-payments-sdk/](../../agent-payments-sdk) (`@three-ws/agent-payments`),
- [agent-protocol-sdk/](../../agent-protocol-sdk) (`@three-ws/agent-protocol-sdk`).
-- **App-adjacent SDKs** (workspaces) — [avatar-sdk/](../../avatar-sdk) (`@three-ws/avatar`),
- [walk-sdk/](../../walk-sdk) (`@three-ws/walk`), [tour-sdk/](../../tour-sdk) (`@three-ws/tour`).
-- **Spec/schema/preset packages** — [packages/avatar-schema/](../../packages/avatar-schema)
- (`@three-ws/avatar-schema`), [packages/avatar-cli/](../../packages/avatar-cli)
- (`@three-ws/avatar-cli`), [packages/viewer-presets/](../../packages/viewer-presets)
- (`@three-ws/viewer-presets`), [packages/react/](../../packages/react) (`@three-ws/react`).
-- **Examples / demos** — [examples/](../../examples) (`embed-test.html`, `web-component.html`,
- `two-agents.html`, `minimal.html`), [multiplayer/](../../multiplayer).
-- **Publish tooling** — `npm run publish:packages:dry`
- ([scripts/publish-packages.mjs](../../scripts/publish-packages.mjs)),
- `publish:mcp:dry` ([scripts/publish-mcp-servers.mjs](../../scripts/publish-mcp-servers.mjs)),
- `publish:lib` ([scripts/publish-lib.mjs](../../scripts/publish-lib.mjs)), and the strongest
- gate — [scripts/verify-packages.mjs](../../scripts/verify-packages.mjs) (packs each tarball,
- installs it in a clean throwaway project, then exercises its real public surface).
-- **Workspace map** — [STRUCTURE.md](../../STRUCTURE.md) "npm workspaces" + "Promotion path".
-
-## Do this
-
-1. **Inventory + verify names/versions:** for every SDK above, confirm `package.json`
- `name` matches STRUCTURE.md, `version` is sane semver, `type`/`exports`/`main`/`module`/
- `types` resolve, and `files[]` (or `.npmignore`) ships exactly the published surface —
- no `src` leak, no missing `dist`. Confirm a `prepublishOnly`/build runs the build.
-2. **Run the real-consumer gate:** `node scripts/verify-packages.mjs` — it packs each
- package into its actual npm tarball, installs into a clean project resolving deps fresh,
- and imports the SDK / runs the CLI bin / boots the MCP server. Fix every `files[]` gap,
- broken export map, or missing runtime dep it surfaces.
-3. **Dry-run both publishers:** `npm run publish:packages:dry` and `npm run publish:mcp:dry`.
- Both must report clean — no version-already-published surprises, no auth errors, no
- missing build outputs.
-4. **READMEs must teach by example:** each README has install, a minimal runnable example
- (web component, `import`, or CLI invocation), the public API surface, and a link to the
- live page/demo. Every code block must actually run against the published surface — copy
- one into a scratch project and confirm.
-5. **Wire a working demo per SDK:** `@three-ws/avatar` → an `examples/` page renders the
- `<agent-3d>` viewer; `@three-ws/walk` → the walk companion mounts; `@three-ws/tour` →
- the feature tour boots; payment/protocol SDKs → a runnable example call (real endpoint,
- no mock). Exercise each in a real browser (`npm run dev`) or node where applicable; zero
- console errors.
-6. **Semver discipline:** bump only what changed (patch/minor/major per real diff). Keep
- any `peerDependencies` honest (Three.js, React versions) so installs don't warn. Do not
- publish from this prompt — dry-run + verify only, unless the user explicitly says publish.
-7. **Cross-link the docs:** each SDK README links to STRUCTURE.md's workspace row and to its
- sibling SDKs where they compose (e.g. avatar viewer + walk companion). The best platforms
- feel like everything is linked.
-8. **Changelog + build:** add a `data/changelog.json` entry (tag `sdk`) for any user-visible
- SDK doc/version change, then `npm run build:pages` (it validates the entry).
-
-## Must-not
-
-- Do not publish to npm/registry from this prompt unless the user explicitly asks — dry-run only.
-- Do not ship a README example that doesn't run, or a `files[]` that leaks `src`/tests or drops `dist`.
-- Do not reference any coin other than `$THREE` in any example, fixture, or doc.
-- Do not use a mock/fake endpoint in an example — real APIs only (or a clearly synthetic placeholder).
-- Do not bump versions cosmetically; semver must reflect the actual change.
-- Do not break a working package's exports while "cleaning up" its config.
-
-## Acceptance (all true before claiming done)
-
-- [ ] Every SDK `package.json` has a correct `name`, semver `version`, resolving `exports`,
- and a tight `files[]`; builds run via `prepublishOnly`.
-- [ ] `node scripts/verify-packages.mjs` passes for every package (clean-room install + surface check).
-- [ ] `npm run publish:packages:dry` and `npm run publish:mcp:dry` both report clean.
-- [ ] Each README has install + a runnable example + API surface + a live demo link; examples verified to run.
-- [ ] At least one working demo per SDK is exercised with zero console errors.
-- [ ] No coin other than `$THREE` appears anywhere in SDK source, examples, or docs.
-- [ ] Changelog updated (if user-visible) and `npm run build:pages` is clean.
diff --git a/prompts/samples/25-worlds-coin-clash.md b/prompts/samples/25-worlds-coin-clash.md
deleted file mode 100644
index 6b7265e75..000000000
--- a/prompts/samples/25-worlds-coin-clash.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# 25 — Worlds & Coin Clash (token-gated 3D)
-
-> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read
-> `/CLAUDE.md` first (its rules override everything) and `prompts/production-1b/00-README.md`
-> for shared context.
-
-## Why this matters for $1B
-
-"Every coin is a 3D world you can drop into" and "hold a coin, enlist, and fight
-live armies" is the social loop that makes a token sticky beyond price — it turns
-holders into citizens and a chart into a place. If a world dead-ends on a void, a
-presence sync drops players, or the enlist gate lets a non-holder in (or locks a
-real holder out), the network effect collapses. Reliable, every-state, token-gated
-multiplayer is what makes three.ws a destination instead of a tool.
-
-## Mission
-
-Make every coin enterable as a live 3D world and make Coin Clash — token-gated
-community warfare (hold the coin → enlist → rally battle power live) — correct,
-multiplayer-reliable, beautifully stated in every phase, and $THREE-compliant for
-anything the platform itself promotes.
-
-## Map (trust but verify — files move)
-
-- **Worlds lobby (front door)** — [pages/worlds.html](../../pages/worlds.html),
- [src/worlds-lobby.js](../../src/worlds-lobby.js) (pick/drop-in an avatar, list live
- coin-worlds, enter at `/walk?coin=<mint>`).
-- **Worlds data + gating** — [api/community/worlds.js](../../api/community/worlds.js)
- (`GET /api/community/worlds`), [api/community/world-gate.js](../../api/community/world-gate.js)
- (per-coin holder threshold; creator-only POST), [api/community/ws-ticket.js](../../api/community/ws-ticket.js)
- (short-lived realtime ticket), [api/world/[action].js](../../api/world/[action].js)
- (per-world persistence: `load`/`save`).
-- **Coin Clash UI** — [pages/clash.html](../../pages/clash.html), [src/clash.js](../../src/clash.js)
- (bracket → battle cards → enlist challenge → rally dock).
-- **Coin Clash API + store** — [api/clash/[action].js](../../api/clash/[action].js)
- (`state`, `enlist`, `enlist-verify`, `rally`, `leaderboard`), backed by
- [api/_lib/clash.js](../../api/_lib/clash.js), [api/_lib/clash-store.js](../../api/_lib/clash-store.js),
- [api/_lib/crews-store.js](../../api/_lib/crews-store.js).
-- **Realtime multiplayer** — [multiplayer/](../../multiplayer) (authoritative Colyseus server):
- [multiplayer/src/rooms/WalkRoom.js](../../multiplayer/src/rooms/WalkRoom.js),
- [multiplayer/src/rooms/ClashRoom.js](../../multiplayer/src/rooms/ClashRoom.js),
- presence in [multiplayer/src/presence-token.js](../../multiplayer/src/presence-token.js).
-- **Hyperfy world host** — [deploy/world/](../../deploy/world) + [scripts/world-health.mjs](../../scripts/world-health.mjs).
-- **Verify/smoke** — [scripts/verify-worlds-lobby.mjs](../../scripts/verify-worlds-lobby.mjs)
- (offline/unconfigured state), [scripts/verify-worlds-live.mjs](../../scripts/verify-worlds-live.mjs)
- (configured live worlds), [scripts/world-health.mjs](../../scripts/world-health.mjs)
- (asset-integrity check). Tests: [tests/clash-match.test.js](../../tests/clash-match.test.js),
- [tests/world-store.test.js](../../tests/world-store.test.js).
-
-## Do this
-
-1. **Exercise the worlds lobby** (`npm run dev`, `/worlds`): pick/drop-in an avatar with no
- sign-in, browse live coin-worlds, and enter one. Confirm both states work — configured
- (real grid via `GET /api/community/worlds`) and unconfigured (graceful "offline" layer
- where worlds are still enterable, the documented 503 degradation). Run
- `node scripts/verify-worlds-lobby.mjs` (and `verify-worlds-live.mjs` against a configured
- dev server): zero console errors beyond the one tolerated 503.
-2. **Drop into a world end-to-end:** enter `/walk?coin=<mint>`, confirm the world loads (no
- void), the avatar spawns, persistence round-trips via `api/world/[action]` (`save`→`load`),
- and `scripts/world-health.mjs` reports every blueprint asset present (the 2026-06-12 void
- regression must not recur).
-3. **Token-gate correctly:** verify `api/community/world-gate.js` — a coin creator can set a
- holder threshold, GET states the requirement publicly, and entry re-verifies the on-chain
- holding server-side. A real holder gets in; a non-holder hits a designed, actionable gate
- screen (tells them what to hold and how). Fail closed when creator/holding is unknown.
-4. **Coin Clash full loop** (`/clash`): poll `state` → render the bracket → enlist (wallet
- challenge → `enlist-verify` confirms a live on-chain holding of the faction coin) → rally
- dock opens, taps batch and flush to `rally` as battle power. Confirm holdings are gated
- on-chain (no client trust) and the leaderboard reflects real effort.
-5. **Design every state** across both surfaces: loading (skeleton, not a fake bar), empty
- (no live worlds / no active battles → what to do next), error (network/upstream failure →
- actionable recovery), and overflow (many worlds, long coin names, big armies). No blank
- voids, no dead buttons.
-6. **Multiplayer reliability:** in the Colyseus rooms (`WalkRoom`, `ClashRoom`), verify
- presence join/leave, reconnect after a dropped socket, and ticket auth via
- `api/community/ws-ticket.js` + `presence-token.js`. A player who disconnects must not
- linger as a ghost; a reconnect must restore identity. Boot the server with
- `npm run dev:multi` (or `dev:walk-all`) and test two browser tabs.
-7. **Run the suites:** `npx vitest run tests/clash-match.test.js tests/world-store.test.js`
- and the multiplayer package's own tests. Add coverage for any uncovered failure mode
- (gate-denied, upstream 503, presence drop/reconnect, matchmaking bye).
-8. **$THREE compliance + changelog:** any coin the platform *promotes* must be `$THREE`
- (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); the worlds grid and faction roster are
- runtime launch-record feeds (allowed) — never hardcode/market a non-$THREE mint. Add a
- `data/changelog.json` entry for any user-visible change, then `npm run build:pages`.
-
-## Must-not
-
-- Do not let a non-holder past a token gate, or lock out a verified holder — gate on-chain, fail closed.
-- Do not ship a world that can drop players into a void; assets must be verified present.
-- Do not hardcode, market, or recommend any mint other than `$THREE` (runtime launch feeds are fine).
-- Do not fake presence/multiplayer with timers or client-trusted state — use the authoritative rooms.
-- Do not leave any state undesigned (no blank voids, no dead buttons, no never-resolving spinners).
-- Do not weaken a verify/smoke/health check to make a run pass.
-
-## Acceptance (all true before claiming done)
-
-- [ ] `/worlds` works in both configured and unconfigured states; `verify-worlds-lobby.mjs`
- (and `verify-worlds-live.mjs` configured) pass with no unexpected console errors.
-- [ ] Dropping into `/walk?coin=<mint>` loads a real world (no void), spawns the avatar, and
- persists via `api/world/[action]`; `scripts/world-health.mjs` reports all assets present.
-- [ ] Token gating verified on-chain: holders enter, non-holders see a designed actionable gate.
-- [ ] Coin Clash loop works end-to-end (state → enlist → enlist-verify → rally), holdings gated on-chain.
-- [ ] Loading/empty/error/overflow states designed across both surfaces; presence join/leave/reconnect reliable.
-- [ ] `tests/clash-match.test.js`, `tests/world-store.test.js`, and multiplayer tests pass; new failure modes covered.
-- [ ] No promoted coin other than `$THREE`; changelog updated and `npm run build:pages` is clean.
diff --git a/prompts/tests/00-README-orchestration.md b/prompts/tests/00-README-orchestration.md
deleted file mode 100644
index 3cb7b0152..000000000
--- a/prompts/tests/00-README-orchestration.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Road to $1B — Production-Readiness Program
-
-This directory is a **sequenced program of self-contained prompts**. Each `.md`
-file is a complete task brief you paste into a **fresh agent chat** at
-`/workspaces/three.ws`. Run them in order within a phase; phases mostly gate on
-the one before. Every prompt is written to be run with zero prior context — it
-restates where it is, what the codebase is, and which rules apply.
-
-## The thesis
-
-A platform reaches a billion-dollar valuation on three things this program
-drives toward:
-
-1. **It works, completely.** No dead buttons, no half-wired flows, no fake data,
- no TODOs shipped to users. (Phase 1)
-2. **It never goes down and never leaks.** Hardened APIs, resilient external
- calls, real observability, a real security posture. (Phase 2–3)
-3. **People can't stop using it and telling others.** Fast, polished, accessible,
- shareable, monetized, instrumented. (Phase 4–6)
-
-We do not get there with "good enough." Read [CLAUDE.md](../../CLAUDE.md) before
-every task — it is the operating contract. The relevant non-negotiables:
-
-- No mocks, no fake data, no placeholders, no TODO comments, no stubs.
-- The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
-- Every user-visible change gets a `data/changelog.json` entry.
-- Stage explicit paths only (concurrent agents share this worktree). Never
- `git add -A`. Re-check `git status` before committing.
-- Push to **both** remotes (`threeD`, `threews`) when asked to push. Never pull
- from `threeD`.
-
-## How to run
-
-1. Open a new chat in this repo.
-2. Paste the entire contents of one prompt file.
-3. Let the agent finish, verify its Definition of Done, then move to the next.
-4. Prompts marked **[parallel-safe]** can run simultaneously in separate chats
- (they touch disjoint surfaces). Prompts marked **[serial]** must run alone.
-
-## The baseline (measured 2026-06-21, will change as you work)
-
-These are the concrete gaps this program closes. Re-run the discovery commands
-inside each prompt to get the live number — do not trust this snapshot.
-
-| Signal | Count | Closed by |
-|---|---|---|
-| TODO / FIXME / placeholder / "coming soon" markers in `src/ public/ api/` | 652 | [02](02-eliminate-todos-and-stubs.md) |
-| Empty `catch {}` blocks | 126 | [03](03-harden-error-boundaries.md) |
-| Mock / sample / fake-data arrays | 23 | [04](04-purge-mock-and-fake-data.md) |
-| API functions (each needs authz + validation + rate limiting reviewed) | 769 | [08](08-api-hardening.md) |
-| Env keys (secrets surface) | 275 | [07](07-secrets-and-env-hardening.md) |
-| CI workflows | 1 | [16](16-ci-cd-hardening.md) |
-
-Discovery, anytime:
-
-```bash
-grep -rIn "TODO\|FIXME\|not implemented\|implement later\|placeholder\|coming soon\|XXX:" --include=*.js src/ public/ api/ | grep -v node_modules | wc -l
-grep -rIn "catch[^)]*) *{ *}" --include=*.js src/ public/ api/ | grep -v node_modules | wc -l
-```
-
-## Phases
-
-**Phase 1 — Correctness & hygiene (no shortcuts ship).** Serialize 02→06; they
-edit broadly and you want clean diffs between them.
-- [01 — Production audit & scorecard](01-production-audit-scorecard.md) **[serial, run first]**
-- [02 — Eliminate every TODO / stub / placeholder](02-eliminate-todos-and-stubs.md)
-- [03 — Harden every error boundary (kill empty catches)](03-harden-error-boundaries.md)
-- [04 — Purge all mock / sample / fake data](04-purge-mock-and-fake-data.md)
-- [05 — Dead-path & handler audit (every button works)](05-dead-path-and-handler-audit.md)
-- [06 — $THREE coin-compliance sweep](06-three-coin-compliance-sweep.md)
-
-**Phase 2 — Reliability & security (institutional grade).** [parallel-safe]
-across 07–11 once Phase 1 is clean.
-- [07 — Secrets & env hardening](07-secrets-and-env-hardening.md)
-- [08 — API hardening: authz, validation, rate limiting](08-api-hardening.md)
-- [09 — Security review: payments, wallets, contracts](09-security-review.md)
-- [10 — Resilience on every external call](10-resilience-external-calls.md)
-- [11 — Observability: logging, monitoring, alerting](11-observability.md)
-
-**Phase 3 — Performance & scale.** [parallel-safe]
-- [12 — Frontend performance & Core Web Vitals](12-frontend-performance.md)
-- [13 — 3D asset performance](13-3d-asset-performance.md)
-- [14 — Backend caching & data layer](14-backend-caching.md)
-
-**Phase 4 — Quality & testing.**
-- [15 — Test coverage to the bar](15-test-coverage.md) **[serial]**
-- [16 — CI/CD hardening](16-ci-cd-hardening.md) **[serial]**
-- [17 — Accessibility audit (WCAG 2.2 AA)](17-accessibility-audit.md) **[parallel-safe]**
-
-**Phase 5 — UX polish & completeness.** [parallel-safe]
-- [18 — Every state designed (loading/empty/error/overflow)](18-state-design-sweep.md)
-- [19 — Responsive / mobile sweep](19-responsive-mobile-sweep.md)
-- [20 — Design-system & token consistency](20-design-system-consistency.md)
-- [21 — Onboarding & first-run experience](21-onboarding-first-run.md)
-
-**Phase 6 — Growth, monetization & the $1B narrative.**
-- [22 — SEO & shareability](22-seo-and-shareability.md) **[parallel-safe]**
-- [23 — Growth & virality loops](23-growth-virality.md) **[parallel-safe]**
-- [24 — Monetization completeness](24-monetization-completeness.md) **[parallel-safe]**
-- [25 — Analytics & funnel instrumentation](25-analytics-funnel.md) **[parallel-safe]**
-- [26 — Trust surfaces: status, docs, security, pricing](26-trust-surfaces.md) **[parallel-safe]**
-
-**Phase 7 — Launch.**
-- [27 — Go-live runbook & pre-launch checklist](27-launch-runbook.md) **[serial, run last]**
-- [28 — Incident response & on-call](28-incident-response-oncall.md) **[serial]**
-
-## Done means done
-
-A prompt is complete only when its own Definition-of-Done checklist is fully
-true and verified — not when the code is written. If an agent can't verify a
-step, it must say so explicitly. Same rule as [CLAUDE.md](../../CLAUDE.md): you
-would be proud to demo every result to a room of senior engineers.
diff --git a/prompts/tests/00-README.md b/prompts/tests/00-README.md
deleted file mode 100644
index 776180017..000000000
--- a/prompts/tests/00-README.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# Road to $1B — production-readiness program
-
-> **Read this file in full before starting any prompt in this folder.** Every prompt
-> here (`01-*` … `40-*`) assumes the context below. Do not re-derive it. Each prompt
-> is self-contained and meant to be run in its own fresh chat.
-
-## What this is
-
-A sequenced program of work to take **three.ws** from "feature-rich but uneven" to
-**production-grade and ready to scale to a $1B platform**. Each numbered file is a
-single, self-contained task you can paste into a new agent chat. They are grouped
-into phases. Run them roughly in order — later phases assume earlier ones are done —
-but any single prompt can be run independently.
-
-This is not a feature-invention program (that lives in the sibling folders:
-`feature-innovation/`, `moonshots/`, `inventions/`, etc.). This program is about
-**finishing, hardening, and polishing what already exists** so the platform is
-correct, reliable, fast, accessible, secure, observable, and conversion-optimized.
-
-## The bar (non-negotiable — applies to every prompt)
-
-Every prompt inherits the operating rules in **`/CLAUDE.md`**. Re-read it. The rules
-that matter most for this program:
-
-- **No mocks, no fake data, no placeholders, no TODOs, no stubs.** If you touch it,
- finish it. Real APIs, real endpoints, real data.
-- **No "good enough."** Fix mediocrity the moment you see it.
-- **No errors without solutions.** Every error has a root cause; find it and fix it.
- Ship working fallbacks and failsafes, never lazy propagation.
-- **Every state is designed** — loading, empty, error, populated, overflow.
-- **The only coin is `$THREE`** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).
- Never reference any other coin anywhere. See `/CLAUDE.md` for the two
- runtime-data-only mechanical exceptions.
-- **Definition of done**: the checklist in `/CLAUDE.md` must be true. If you can't
- verify a step, say so explicitly — do not claim done.
-
-## How to run a prompt
-
-1. Open a fresh chat in this repo.
-2. Paste the contents of the prompt file (or reference it: "Execute
- `prompts/road-to-1b/NN-*.md`").
-3. Let the agent work end-to-end. It should use `TodoWrite` for multi-step work,
- exercise the feature in a real browser for UI work, and run the relevant tests.
-4. When it reports done, spot-check against the prompt's **Acceptance** section.
-5. Commit + push when satisfied (the agent will push to **both** remotes —
- `threeD` and `threews` — per `/CLAUDE.md`).
-
-## Repository orientation (so every prompt starts from truth)
-
-- **`STRUCTURE.md`** maps every product surface to its directory. Read it before
- exploring the ~60 top-level dirs.
-- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
- `pages/*.html` (125 pages), `src/`, `public/`.
-- Backend: Vercel functions in `api/` (~960 handlers), Cloudflare workers in
- `workers/`. Config in `vercel.json` (routes, functions, crons, env).
-- 3D: Three.js + glTF/GLB. Avatar/animation pipeline under `public/animations/`,
- `src/glb-canonicalize.js`, `src/animation-retarget.js`.
-- Tests: `npm test` = `vitest run && playwright test`. `npm run test:all` also runs
- `test:pages`. `npm run lint` (eslint), `npm run typecheck` (tsc on jsconfig).
-- Changelog: user-visible changes get an entry in `data/changelog.json`, then
- `npm run build:pages` regenerates `CHANGELOG.md` + `public/changelog.{json,xml}`.
-- Existing audit tooling you should lean on, not reinvent:
- `npm run audit:deploy`, `audit:pages`, `audit:handlers`, `audit:web`, `audit:mcp`,
- `check:images`, `seo:meta`, `verify`, `verify:solana`, `verify:onchain`,
- `smoke:onchain`, `smoke:mcp`.
-- Resilience: prefer the vetted **cockatiel** helper for retries/circuit-breakers
- (see the existing usage in `api/_lib/`). Adopt OSS over hand-rolling; add hardening
- to new/unprotected paths rather than refactoring working code.
-
-## Phases
-
-**Phase 0 — Foundation (stop the platform from lying about "done")**
-- `01` Test suite green + CI gate
-- `02` Dead paths & broken links — every button works, every link resolves
-- `03` Zero console errors/warnings across all pages
-- `04` No-mocks / no-placeholders sweep (~400 marker files)
-- `05` Secrets & env hygiene
-
-**Phase 1 — Cross-cutting production hardening**
-- `06` Error handling & resilience (api/ + workers/)
-- `07` Security hardening (authz, input validation, headers)
-- `08` Rate limiting & abuse prevention
-- `09` Accessibility (WCAG 2.2 AA)
-- `10` Performance & Core Web Vitals
-- `11` Mobile responsiveness (320 / 768 / 1440)
-- `12` Every state designed (loading / empty / error)
-- `13` Design-system consistency (tokens, spacing, typography)
-- `14` SEO & structured data
-
-**Phase 2 — Product surface completeness (each end-to-end)**
-- `15` Forge (text/image → 3D)
-- `16` Marketplace
-- `17` Agent profiles & economy
-- `18` Wallet & x402 payments
-- `19` Walk companion & feature tour
-- `20` Scene Studio
-- `21` Avatar creator / Character Studio
-- `22` Pump.fun launch & $THREE surfaces
-- `23` MCP servers (production-ready)
-- `24` SDK publishing & docs
-
-**Phase 3 — Scale, infra, observability**
-- `25` Observability (logging, metrics, error tracking)
-- `26` Database integrity & migrations
-- `27` Deploy pipeline & rollback safety
-- `28` Uptime monitoring & public status page
-- `29` Load & stress testing
-
-**Phase 4 — Growth to $1B**
-- `30` Onboarding & activation funnel
-- `31` Home / landing conversion
-- `32` Pricing & monetization surfaces
-- `33` Growth analytics instrumentation
-- `34` Developer experience & docs site
-- `35` Referral & virality loops
-- `36` Trust, safety & moderation
-- `37` Legal, compliance, ToS & privacy
-- `38` i18n completion
-- `39` PWA & notifications
-- `40` Launch-readiness review (the final gate)
-
-## Prompt anatomy
-
-Each file has: **Why this matters for $1B**, **Mission**, **Map** (where things
-live), **Do this** (ordered steps), **Must-not** (guardrails), and **Acceptance**
-(a checklist that must be all-true before claiming done). Trust the Map but verify —
-files move; if a path is stale, find the real one and proceed. Never stop because a
-path was wrong.
diff --git a/prompts/tests/01-production-audit-scorecard.md b/prompts/tests/01-production-audit-scorecard.md
deleted file mode 100644
index c0bd2b8f6..000000000
--- a/prompts/tests/01-production-audit-scorecard.md
+++ /dev/null
@@ -1,72 +0,0 @@
-# 01 — Production audit & readiness scorecard
-
-**Run this first. Serial.** It produces the source-of-truth report every later
-prompt checks against.
-
-## Where you are
-
-You are at `/workspaces/three.ws` — **three.ws**, an open-source browser-native
-3D AI-agent platform (Three.js/Vite frontend, Vercel functions in `api/`,
-Cloudflare workers in `workers/`, Solana + x402 payments, $THREE token). Read
-[CLAUDE.md](../../CLAUDE.md) and [STRUCTURE.md](../../STRUCTURE.md) before doing
-anything. The only coin is **$THREE**.
-
-## Objective
-
-Produce an honest, file-level production-readiness scorecard. You are not fixing
-anything in this task — you are establishing ground truth so the fix tasks are
-targeted and measurable. The deliverable is a committed report plus a machine
--readable inventory the rest of the program consumes.
-
-## Why it matters
-
-You cannot claim "100% production ready" against a number you never measured.
-This report is the before-picture. Every later prompt closes a row in it.
-
-## Instructions
-
-1. **Inventory the gaps.** Run each, capture counts AND the file list:
- ```bash
- grep -rIn "TODO\|FIXME\|not implemented\|implement later\|placeholder\|coming soon\|XXX:\|HACK" --include=*.js src/ public/ api/ workers/ | grep -v node_modules
- grep -rIn "catch[^)]*) *{ *}" --include=*.js src/ public/ api/ workers/ | grep -v node_modules
- grep -rIn "const sample\|mockData\|fakeData\|sampleAgents\|dummyData\|hardcoded\|FIXME" --include=*.js src/ public/ api/ | grep -v node_modules
- grep -rIn "console.log\|console.warn\|console.error" --include=*.js src/ public/ | grep -v node_modules | wc -l
- ```
-2. **Run the repo's own auditors** and record pass/fail + output:
- ```bash
- npm run audit:handlers # empty event handlers / dead buttons
- npm run audit:pages # page index integrity
- npm run check:images # image loading (strict)
- npm run audit:web # web audit
- npm run lint # eslint
- npm run typecheck # tsc
- npm test 2>&1 | tail -40 # current test state
- ```
- Do not fix failures here — record them.
-3. **Map dead paths at the product level.** For each top surface in
- [STRUCTURE.md](../../STRUCTURE.md) (forge, marketplace, trending, studio,
- walk, club, reputation, launches, chat, x402 checkout), note in one line:
- does the primary user flow complete end-to-end with real data? Use the dev
- server if needed (`npm run dev`, port 3000). Flag anything that 404s,
- throws, or shows placeholder/empty content where data should be.
-4. **Score each surface** 0–5 on: completeness, error/empty/loading states,
- mobile, accessibility, performance. Be ruthless; a 3 is "works but not
- demoable."
-5. **Write the report** to `docs/audits/production-readiness-YYYY-MM-DD.md`
- (use today's date) with: the gap counts table, the auditor results, the
- surface scorecard, and a prioritized fix list keyed to the prompt numbers in
- [00-README-orchestration.md](00-README-orchestration.md).
-6. **Write the machine inventory** to `docs/audits/gap-inventory.json` —
- `{ todos: [...], emptyCatches: [...], mockData: [...], deadPaths: [...] }`,
- each entry `{ file, line, snippet }`. Later prompts diff against this.
-
-## Definition of done
-
-- [ ] `docs/audits/production-readiness-<today>.md` committed, with real numbers
- (not estimates) and a per-surface scorecard.
-- [ ] `docs/audits/gap-inventory.json` committed and valid JSON.
-- [ ] Every auditor command above was run and its result recorded, including
- failures — no command silently skipped.
-- [ ] The report names the 10 highest-leverage fixes, each linked to a prompt.
-- [ ] No source files changed (this is read-only except the two reports).
-- [ ] Changelog: skip — this is an internal audit, not user-visible.
diff --git a/prompts/tests/01-test-suite-green-and-ci-gate.md b/prompts/tests/01-test-suite-green-and-ci-gate.md
deleted file mode 100644
index 159bf6703..000000000
--- a/prompts/tests/01-test-suite-green-and-ci-gate.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# 01 — Test suite green + CI gate
-
-> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.
-
-**Phase:** 0 — Foundation
-**Owns:** `tests/`, `package.json` scripts, CI config (`.github/workflows/` if present), `vitest`/`playwright` config.
-**Depends on:** nothing — this runs first.
-
-## Why this matters for $1B
-A platform you can't trust to be green is a platform you can't ship to fast. Every
-later prompt assumes a green baseline so regressions are visible. Investors and
-enterprise customers read CI status as a proxy for engineering discipline.
-
-## Mission
-Get the entire test suite passing reliably, eliminate flakes, and enforce green on
-every push so the bar can never silently drop.
-
-## Map
-- `npm test` → `vitest run && playwright test`
-- `npm run test:all` → `npm run test && npm run test:pages`
-- `npm run test:core`, `test:gate`, `test:e2e`, `test:pages`
-- `npm run lint` (eslint `.`), `npm run typecheck` (`tsc -p jsconfig.json`)
-- 237 files under `tests/`. Smoke suites: `smoke:onchain`, `smoke:mcp`, `smoke:agent-wallet`.
-- CI: check `.github/workflows/` — wire the gate there.
-
-## Do this
-1. Run `npm run lint`, `npm run typecheck`, `npm test`, `npm run test:pages` and
- capture the full failure list. Triage into: real bugs, stale tests, flakes,
- environment/credential gaps.
-2. Fix **real bugs in the code**, not the tests, wherever a test correctly catches a
- defect. Where a test is genuinely stale (asserts removed behavior), update it and
- note why in the commit.
-3. For tests that need credentials/network: gate them on env presence so they skip
- cleanly (not fail) when creds are absent locally, but **run** in CI where creds
- exist. Never delete coverage to make green.
-4. Hunt flakes: anything timing-dependent, animation-dependent, or ordering-dependent
- in Playwright. Add deterministic waits (`expect(...).toPass`, role/text locators),
- remove arbitrary sleeps. Re-run the suspect specs 5× to confirm stability.
-5. Ensure `npm run typecheck` and `npm run lint` are clean. Fix the code; only
- disable a rule inline with a justifying comment when the rule is genuinely wrong
- for that line.
-6. Wire/confirm a CI workflow that runs lint + typecheck + `test:all` on every push
- and PR to `main`, and **blocks merge on failure**. If `.github/workflows/` is
- absent, create one. Cache `node_modules` and the Playwright browser install.
-7. Add a short `tests/README.md` (or update it) explaining how to run each suite and
- which need credentials.
-
-## Must-not
-- Do not weaken assertions, `.skip` real tests, or set `--passWithNoTests` to fake green.
-- Do not commit credentials to make CI pass — use CI secrets.
-- Do not introduce `setTimeout`-based waits in Playwright.
-
-## Acceptance
-- [ ] `npm run lint` — clean.
-- [ ] `npm run typecheck` — clean.
-- [ ] `npm test` and `npm run test:pages` — green locally (creds-gated suites skip cleanly with a logged reason).
-- [ ] Suspect flaky specs pass 5/5 reruns.
-- [ ] CI workflow runs lint + typecheck + test:all on push/PR and blocks on red.
-- [ ] `git diff` reviewed; every changed test justified.
diff --git a/prompts/tests/02-dead-paths-and-broken-links.md b/prompts/tests/02-dead-paths-and-broken-links.md
deleted file mode 100644
index 55558614c..000000000
--- a/prompts/tests/02-dead-paths-and-broken-links.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# 02 — Dead paths & broken links
-
-> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.
-
-**Phase:** 0 — Foundation
-**Owns:** `pages/*.html` (125 pages), `public/`, `src/`, nav (`public/nav.js`, `public/nav.css`), routing in `vercel.json`.
-**Depends on:** none.
-
-## Why this matters for $1B
-Nothing destroys trust faster than a button that does nothing or a link that 404s.
-`/CLAUDE.md`: "If a button exists, it must work. If a link exists, it must go
-somewhere. If a state exists, there must be a way to reach it." This is table stakes.
-
-## Mission
-Audit every interactive element and link across the whole site. Every one resolves
-to a working destination or a real action. Zero dead ends.
-
-## Map
-- 125 pages in `pages/`. Shared nav in `public/nav.js` / `public/nav.css`.
-- Route map in `vercel.json` (`routes`). Page index in `data/pages.json`.
-- Existing helpers: `npm run audit:pages`, `npm run audit:web`, `npm run check:images`.
-
-## Do this
-1. Build a link/route inventory: every `href`, `<a>`, `onclick`, `data-href`,
- `<button>` handler, and `fetch()` target across `pages/`, `src/`, `public/`. A
- script in `scripts/` (kept, not throwaway, or deleted after) that crawls the built
- site is acceptable — wire it as `npm run audit:links` if useful.
-2. For every internal link/route: confirm the target exists in `pages/`/`public/`
- and is reachable via `vercel.json` routes. Fix broken targets — create the page,
- fix the path, or remove the link if the destination was never meant to exist.
-3. For every external link: confirm it resolves (200/redirect, not 404/dead domain).
- Replace or remove dead ones. External links open with `rel="noopener"`.
-4. For every button/interactive control: confirm it has a real handler that does
- real work. Any control wired to nothing, to a `// TODO`, to an `alert()`, or to a
- no-op gets implemented or removed. No decorative buttons.
-5. Confirm every nav entry (desktop + mobile menu) points somewhere live and is
- reachable on small screens (cross-check with prompt `11`).
-6. Confirm 404 handling: a real, branded 404 page that helps the user recover
- (search, links home, top destinations) — not a blank or default.
-7. Re-run `audit:pages` / `audit:web` and resolve every finding.
-
-## Must-not
-- Do not "fix" a broken link by pointing it at the homepage as a catch-all. Find the
- intended destination or remove the link.
-- Do not leave any `href="#"`, `href="javascript:void(0)"`, or empty handler in place.
-
-## Acceptance
-- [ ] Zero broken internal links/routes (audit script clean).
-- [ ] Zero dead external links.
-- [ ] Every button/control performs real work or is removed.
-- [ ] Branded, helpful 404 page exists and is wired in `vercel.json`.
-- [ ] `npm run audit:pages` and `audit:web` pass.
-- [ ] Spot-checked in a real browser across 8–10 representative pages incl. mobile nav.
diff --git a/prompts/tests/02-eliminate-todos-and-stubs.md b/prompts/tests/02-eliminate-todos-and-stubs.md
deleted file mode 100644
index 4913bf453..000000000
--- a/prompts/tests/02-eliminate-todos-and-stubs.md
+++ /dev/null
@@ -1,59 +0,0 @@
-# 02 — Eliminate every TODO, stub & placeholder
-
-**Phase 1. Run after [01](01-production-audit-scorecard.md). Serial** (broad
-edits — keep its diff isolated).
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform. Read
-[CLAUDE.md](../../CLAUDE.md). Hard rules in play: **No TODO comments. No
-`// implement later`. No stub functions. No `throw new Error("not implemented")`.
-No commented-out code. If you write it, finish it.** There are ~652 marker hits
-to resolve. The only coin is **$THREE**.
-
-## Objective
-
-Drive the TODO/FIXME/stub/placeholder count in `src/ public/ api/ workers/` to
-**zero** — by *implementing* the missing behavior, not by deleting the comment
-and leaving the gap. Every marker is either real missing work (implement it) or
-a stale note (remove it because the work is already done).
-
-## Why it matters
-
-A TODO in shipped code is an admission the product is unfinished. Investors,
-contributors, and users read this repo. Every marker is a small broken promise.
-Closing them is the difference between a demo and a product.
-
-## Instructions
-
-1. **Enumerate** from `docs/audits/gap-inventory.json` (or re-run the grep in
- [00-README](00-README-orchestration.md)). Group by directory/owner-surface so
- you can batch related ones.
-2. **Triage each marker** into one of:
- - **Implement** — the feature/branch/edge-case is genuinely missing. Build it
- properly with real APIs and real data. No shortcuts.
- - **Already done** — the note is stale; delete the comment.
- - **Wrong layer** — it describes work that belongs elsewhere; implement in the
- right place and remove the marker.
- Never resolve by weakening behavior or hiding the path.
-3. **For commented-out code:** delete it or implement it. Git history is the
- archive — dead code in the tree is not.
-4. **For `// placeholder` UI / copy / data:** replace with the real thing. If a
- value must come from an API, wire the fetch. If copy is a stand-in, write the
- final copy.
-5. **Work in reviewable batches** by surface (e.g. all forge TODOs, then all
- marketplace TODOs). After each batch run `npm run lint && npm run typecheck`
- and the relevant tests. Commit per surface with explicit paths so concurrent
- agents aren't clobbered (`git add <files>`, never `-A`).
-6. **Re-measure** after each batch; track the count down to zero.
-
-## Definition of done
-
-- [ ] `grep -rIn "TODO\|FIXME\|not implemented\|implement later\|placeholder\|coming soon\|XXX:\|HACK" --include=*.js src/ public/ api/ workers/ | grep -v node_modules` returns **0** (or each remaining hit is a legitimate string literal a user types/searches, justified inline in your final report).
-- [ ] No `throw new Error("not implemented")`, no stub functions, no
- commented-out code blocks remain in the changed files.
-- [ ] Every "implement" item is wired to real APIs/data and reachable in the UI.
-- [ ] `npm run lint`, `npm run typecheck`, and `npm test` pass.
-- [ ] `gap-inventory.json` `todos` array updated to reflect what was closed.
-- [ ] Changelog: add one `improvement` entry to `data/changelog.json` if any
- user-visible behavior was completed (plain language, not "removed TODOs").
diff --git a/prompts/tests/03-harden-error-boundaries.md b/prompts/tests/03-harden-error-boundaries.md
deleted file mode 100644
index 27018a7e2..000000000
--- a/prompts/tests/03-harden-error-boundaries.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# 03 — Harden every error boundary (kill the empty catches)
-
-**Phase 1. Serial** after [02](02-eliminate-todos-and-stubs.md).
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform. Read
-[CLAUDE.md](../../CLAUDE.md). Rules in play: **Errors handled at boundaries
-(network, user input). No errors without solutions — there is always a correct
-answer. Ship working fallbacks and failsafes. Lazy error propagation is not
-engineering.** ~126 empty `catch {}` blocks exist. The only coin is **$THREE**.
-
-## Objective
-
-Eliminate silent failure. Every `catch` either (a) recovers with a real
-fallback, (b) surfaces an actionable error to the user at a UI boundary, or (c)
-reports to the error pipeline with enough context to debug — never swallows.
-
-## Why it matters
-
-An empty catch is a bug that will happen in production and that you have
-pre-decided not to learn about. At scale these are the outages you can't explain
-and the user reports you can't reproduce. Silent failure is the opposite of
-institutional grade.
-
-## Instructions
-
-1. **Enumerate** empty/near-empty catches:
- ```bash
- grep -rIn "catch[^)]*) *{ *}" --include=*.js src/ public/ api/ workers/ | grep -v node_modules
- grep -rPzoIn "catch\s*\([^)]*\)\s*\{\s*(//[^\n]*)?\s*\}" --include=*.js src/ public/ api/ | grep -v node_modules
- ```
- Also review `catch` blocks whose body is only `return null` / `return` /
- `return []` where the caller can't distinguish "no data" from "it broke."
-2. **Classify each external boundary** (fetch, RPC, pump.fun, LLM proxy, wallet,
- file/parse) vs **internal logic**. CLAUDE.md: internal code trusts itself;
- boundaries are where handling belongs.
-3. **For each, pick the right resolution:**
- - **User-facing UI:** show a designed error state with a recovery action
- (retry, reconnect wallet, refresh). Never a blank void or a console-only
- log. Coordinate with [18 — state design](18-state-design-sweep.md).
- - **Background/worker:** log structured context + retry/backoff where
- transient (see [10 — resilience](10-resilience-external-calls.md)), then
- fail loudly to the error pipeline (see [11 — observability](11-observability.md)).
- - **Truly ignorable** (e.g. `localStorage` blocked in private mode, optional
- analytics): keep the catch but add a one-line comment stating *why* it is
- safe to ignore, and degrade gracefully. A justified silent catch is fine;
- an unexplained one is not.
-4. **Add a shared helper** if a pattern repeats (e.g. `reportError(err, ctx)` and
- a `withFallback(fn, fallback)`), and route catches through it. Prefer the
- existing `public/error-reporter.js` if present — extend, don't duplicate.
-5. **Verify behavior, not just code.** For at least the top 10 user-facing
- boundaries, force the failure (offline, bad input, rejected wallet) in
- `npm run dev` and confirm the user sees a recoverable state.
-
-## Definition of done
-
-- [ ] Zero unexplained empty `catch {}` in `src/ public/ api/ workers/`. Every
- remaining bare catch has a one-line justification comment.
-- [ ] Every network/RPC/LLM/wallet boundary surfaces a recoverable UI state or
- reports to the error pipeline — none swallow silently.
-- [ ] Forced-failure check done on the top 10 boundaries; each degrades
- gracefully (recorded in your report).
-- [ ] `npm run lint`, `npm run typecheck`, `npm test` pass.
-- [ ] `gap-inventory.json` `emptyCatches` updated.
-- [ ] Changelog: `fix` entry in `data/changelog.json` if users will now see
- recoverable errors where things used to silently fail.
diff --git a/prompts/tests/03-zero-console-errors.md b/prompts/tests/03-zero-console-errors.md
deleted file mode 100644
index b132ae8b9..000000000
--- a/prompts/tests/03-zero-console-errors.md
+++ /dev/null
@@ -1,52 +0,0 @@
-# 03 — Zero console errors & warnings
-
-> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.
-
-**Phase:** 0 — Foundation
-**Owns:** all `pages/`, `src/`, `public/` runtime JS; `public/error-reporter.js`.
-**Depends on:** `02` (dead paths) helps; not strictly required.
-
-## Why this matters for $1B
-`/CLAUDE.md` Definition of done: "No console errors. No console warnings from your
-code." Console noise hides real failures and signals sloppiness to any engineer who
-opens devtools — including the ones doing technical diligence.
-
-## Mission
-Drive the browser console to zero errors and zero own-code warnings on every page,
-in both themes, desktop and mobile viewports.
-
-## Map
-- 125 pages in `pages/`. Shared scripts in `public/` (`nav.js`, `x402.js`,
- `x402-pay-core.js`, etc.) and modules in `src/`.
-- `public/error-reporter.js` already captures runtime errors — use it as a signal
- source, and make sure it itself is silent on the happy path.
-- `npm run dev` serves on port 3000.
-
-## Do this
-1. Start `npm run dev`. Write/extend a Playwright sweep (in `scripts/` or
- `tests/`) that visits every page, in light and dark theme, at 390px and 1440px,
- and records every `console.{error,warning}` and every failed network request.
-2. Categorize: own-code bugs, third-party library noise, missing assets (404s),
- uncaught promise rejections, hydration/order issues, CSP violations.
-3. Fix own-code errors and warnings at the root cause. Common culprits: accessing
- DOM before load, missing null guards, deprecated APIs, passing wrong types,
- unhandled rejections from `fetch`. Wire proper guards and error boundaries at the
- network/user-input edges.
-4. Fix every 404 asset (images, fonts, modules, source maps). Cross-check with
- `npm run check:images`.
-5. For unavoidable third-party warnings, document them in a short allowlist the
- sweep can ignore — but justify each entry; do not use the allowlist to bury your
- own noise.
-6. Confirm `error-reporter.js` reports real errors to its backend and produces no
- output on clean pages.
-
-## Must-not
-- Do not silence errors by wrapping in empty `try/catch`. Handle or surface them.
-- Do not suppress warnings by monkey-patching `console`.
-
-## Acceptance
-- [ ] Playwright console sweep: 0 errors, 0 own-code warnings across all pages × 2 themes × 2 viewports.
-- [ ] 0 failed network requests for first-party assets.
-- [ ] 0 uncaught promise rejections.
-- [ ] Third-party allowlist (if any) is documented and justified.
-- [ ] Sweep wired as a repeatable script and runs in CI.
diff --git a/prompts/tests/04-no-mocks-no-placeholders-sweep.md b/prompts/tests/04-no-mocks-no-placeholders-sweep.md
deleted file mode 100644
index 7fa87cf03..000000000
--- a/prompts/tests/04-no-mocks-no-placeholders-sweep.md
+++ /dev/null
@@ -1,53 +0,0 @@
-# 04 — No-mocks / no-placeholders sweep
-
-> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.
-
-**Phase:** 0 — Foundation
-**Owns:** `src/`, `api/`, `public/`, `pages/` — anywhere a placeholder, mock, stub, or fake-data path ships to production.
-**Depends on:** none.
-
-## Why this matters for $1B
-`/CLAUDE.md` hard rules 1–6: no mocks, no fake data, no placeholders, no TODO
-comments, no stub functions, no `throw new Error("not implemented")`, no
-`setTimeout` fake-loading, no fallback sample arrays in production. There are ~400
-files in `src/api/public/pages` matching placeholder/TODO/mock markers. Each is a
-small lie that compounds.
-
-## Mission
-Find every production code path that fakes, stubs, or defers, and replace it with a
-real implementation wired to real data/APIs — or delete it if it should not exist.
-
-## Map
-- Start from: `grep -rn "TODO\|FIXME\|not implemented\|coming soon\|placeholder\|sampleAgents\|mock\|setTimeout(.*loading\|stub" src api public pages` (filter out node_modules).
-- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies,
- x402 endpoints. Credentials live in `.env` / `vercel env`.
-
-## Do this
-1. Enumerate all matches. Triage each into: (a) production code that must be real,
- (b) legitimate test fixtures/mocks (those stay — they belong in `tests/`), (c)
- dead code to delete, (d) genuine config comments (keep).
-2. For (a): implement the real thing. Wire to the real API/endpoint. If a credential
- is missing, locate it in `.env` / `vercel env`; if truly absent, implement the
- real integration and surface a clear, designed error/empty state when the
- dependency is unavailable — never a fake success.
-3. Replace any `const sample... = [...]` fallback shipped to the client with a real
- fetch plus a designed empty state (see prompt `12`).
-4. Replace `setTimeout` fake-loading / fake progress with real async indicators tied
- to actual request lifecycle.
-5. Delete `// TODO`, `// implement later`, commented-out code, and stub functions —
- by implementing them, not by deleting the comment and leaving the gap.
-6. Convert any `throw new Error("not implemented")` into a working implementation.
-7. Re-run the grep until the only remaining matches are legitimate test fixtures and
- justified config comments. Document any intentional remaining marker.
-
-## Must-not
-- Do not move a mock from `src/` into `public/` to dodge the grep. Remove the fakery.
-- Do not delete a feature's UI to avoid implementing its backend — implement it.
-- Do not touch the legitimate `tests/` mocks (those are correct).
-
-## Acceptance
-- [ ] Grep for production placeholders/mocks/stubs/TODOs returns only test fixtures and justified config comments.
-- [ ] Every former placeholder path now fetches/uses real data with designed loading/empty/error states.
-- [ ] No `setTimeout` fake-loading remains in shipped code.
-- [ ] No fallback sample arrays shipped to clients.
-- [ ] `npm test` green; affected pages exercised in a real browser with real network calls.
diff --git a/prompts/tests/04-purge-mock-and-fake-data.md b/prompts/tests/04-purge-mock-and-fake-data.md
deleted file mode 100644
index 8c5edeb76..000000000
--- a/prompts/tests/04-purge-mock-and-fake-data.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# 04 — Purge all mock, sample & fake data
-
-**Phase 1. Serial** after [03](03-harden-error-boundaries.md).
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform. Read
-[CLAUDE.md](../../CLAUDE.md). Rules in play: **No mocks. No fake data. No
-fallback sample arrays shipped to production. Real fetch only. Use real APIs,
-real endpoints, real data.** The only coin is **$THREE** — and **no third-party
-or real mainnet mints in fixtures**; use `$THREE` (CA
-`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or a clearly-synthetic
-placeholder like `THREEsynthetic1111…`.
-
-## Objective
-
-Remove every hardcoded sample array, mock object, and fake-data fallback from
-production code paths. Where a UI currently falls back to canned data when a
-fetch fails, replace that with a real loading + empty + error state driven by
-the real API.
-
-## Why it matters
-
-Fake data is a lie to the user and to yourself. It hides broken integrations,
-inflates how finished the product looks, and eventually ships to someone who
-makes a decision based on numbers that were never real. A $1B platform shows
-real state — including "nothing here yet" — never invented state.
-
-## Instructions
-
-1. **Find candidates:**
- ```bash
- grep -rIn "const sample\|sampleAgents\|sampleData\|mockData\|fakeData\|dummyData\|placeholderData\|DEMO_\|FALLBACK_DATA\|= \[ *{ *id:" --include=*.js src/ public/ api/ | grep -v node_modules
- grep -rIn "// fallback\|// sample\|// demo data\|// mock" --include=*.js src/ public/ | grep -v node_modules
- ```
- Cross-check against `gap-inventory.json` `mockData`.
-2. **For each hit, classify:**
- - **Production fallback** (sample array rendered when fetch fails/empty) →
- **delete it.** Replace with: real fetch → designed loading state → designed
- empty state ("nothing here yet, do X") → designed error state. No canned
- rows.
- - **Test fixture / Storybook / example** under `tests/`, `examples/`,
- `*.test.js` → allowed to stay, but scrub any real third-party mint/coin/
- address and replace with `$THREE` CA or a synthetic placeholder.
- - **Seed data** for a real feature (e.g. onboarding defaults) → keep only if
- it is genuinely the product's real default, not a stand-in for a missing
- fetch.
-3. **Wire the real source.** If a component used fake data because no endpoint
- existed, the endpoint is the missing work — build it (real API in `api/`,
- real query) and connect it. Do not leave the component dataless.
-4. **Empty states are mandatory.** Every list/grid/feed that loses its fake
- fallback must gain a real empty state. Coordinate with
- [18 — state design](18-state-design-sweep.md).
-5. **Verify in the browser** (`npm run dev`): each touched surface shows real
- data on success, a real empty state with zero items, and a real error state
- when the API is down (kill the network in devtools to test).
-
-## Definition of done
-
-- [ ] No sample/mock/fake-data array is reachable in any production render path.
-- [ ] Every delisted fallback is replaced by real fetch + loading + empty +
- error states, verified in the browser.
-- [ ] No real third-party coin/mint/address remains in any fixture; only `$THREE`
- CA or synthetic placeholders.
-- [ ] Any endpoint that was missing is now built with real data and wired in.
-- [ ] `npm test` passes; `gap-inventory.json` `mockData` updated.
-- [ ] Changelog: `improvement` entry if users now see real data where canned
- data used to appear.
diff --git a/prompts/tests/05-dead-path-and-handler-audit.md b/prompts/tests/05-dead-path-and-handler-audit.md
deleted file mode 100644
index ef0bf40e1..000000000
--- a/prompts/tests/05-dead-path-and-handler-audit.md
+++ /dev/null
@@ -1,68 +0,0 @@
-# 05 — Dead-path & handler audit (every button works, every link goes somewhere)
-
-**Phase 1. Serial** after [04](04-purge-mock-and-fake-data.md).
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform (125 pages, 118 public
-JS, 810 src JS). Read [CLAUDE.md](../../CLAUDE.md). Rules in play: **Eliminate
-dead paths. If a button exists it must work. If a link exists it must go
-somewhere. If a state exists there must be a way to reach it.** There is a repo
-auditor for this: `npm run audit:handlers`. The only coin is **$THREE**.
-
-## Objective
-
-Zero dead interactive elements across the whole app. Every button has a working
-handler, every link resolves to a real route (no 404), every nav item leads
-somewhere real, every reachable state has a path in and a path out.
-
-## Why it matters
-
-Nothing tanks trust faster than a button that does nothing. At a billion-dollar
-bar, the product must feel like everything is wired — because it is. Dead paths
-are the tells of an unfinished product.
-
-## Instructions
-
-1. **Run the auditors and fix to green:**
- ```bash
- npm run audit:handlers # empty/no-op handlers
- npm run audit:pages # page index ↔ files integrity
- npm run audit:web # broader web audit
- npm run check:images # broken/lazy images
- ```
-2. **Find no-op handlers manually too:**
- ```bash
- grep -rIn "onclick=\"\"\|onClick={() => {}}\|href=\"#\"\|href=\"javascript:\|addEventListener([^,]*, *function *() *{ *})" --include=*.html --include=*.js public/ pages/ src/ | grep -v node_modules
- ```
-3. **Crawl the real app** (`npm run dev`, port 3000). For each top surface
- (home, forge, marketplace, trending, studio, walk, club, reputation,
- launches, chat, x402 checkout, settings, login): click every button, follow
- every link, open every menu. Log each dead end.
-4. **Fix each dead path properly:**
- - Button with no handler → implement the real action it implies.
- - Link to a missing route → build the route, or repoint to the correct
- existing one. Never leave `href="#"`.
- - Unreachable state → add navigation to it, or remove the state if it's
- vestigial (CLAUDE.md: delete aggressively).
- - Disabled-forever control → enable it with real behavior or remove it.
-5. **Check cross-surface wiring** (CLAUDE.md "think in systems"): does the
- marketplace link to agent profiles? Does an agent profile link to its
- launches, reputation, and chat? Wire the connections that should exist.
-6. **404 + error routes:** confirm a designed 404 page exists and that unknown
- routes hit it, not a blank screen.
-
-## Definition of done
-
-- [ ] `npm run audit:handlers`, `audit:pages`, `audit:web`, `check:images` all
- pass.
-- [ ] Manual crawl complete; every button/link on every top surface does
- something real. The dead-end log is fully resolved (attach it to your
- report with each item's resolution).
-- [ ] No `href="#"` / `href="javascript:void"` / empty handler remains in
- shipped HTML/JS.
-- [ ] Cross-surface links that *should* exist now exist (named in your report).
-- [ ] Designed 404/unknown-route handling verified.
-- [ ] `gap-inventory.json` `deadPaths` updated; `npm test` passes.
-- [ ] Changelog: `improvement`/`fix` entry for any user-facing wiring that now
- works.
diff --git a/prompts/tests/06-three-coin-compliance-sweep.md b/prompts/tests/06-three-coin-compliance-sweep.md
deleted file mode 100644
index 67a9fdff2..000000000
--- a/prompts/tests/06-three-coin-compliance-sweep.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# 06 — $THREE coin-compliance sweep
-
-**Phase 1. Serial** after [05](05-dead-path-and-handler-audit.md). Highest
-sensitivity — treat any violation like a leaked secret.
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform. Read the **"The only
-coin — $THREE"** section of [CLAUDE.md](../../CLAUDE.md) in full before starting;
-it governs this entire task.
-
-## The rule
-
-**The only coin this platform may ever reference is `$THREE`. Contract address:
-`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. There are no other coins.** This
-includes any other coin three.ws itself may have launched. Never mention, name,
-hardcode, link, import, render, recommend, or talk about any other coin — in
-code, comments, tests, fixtures, sample data, docs, blog, UI copy, metadata, or
-commit messages.
-
-Two **runtime-data-only** mechanical exceptions exist (do NOT remove these):
-1. Coin-agnostic plumbing where a mint is supplied at runtime by the user (e.g.
- the pump.fun launcher accepting an arbitrary mint).
-2. Platform launch directories rendering coins users launched through three.ws
- from real launch records at runtime (`/launches`, agent-profile launch
- history, `/api/pump/launches` over `pump_agent_mints`).
-In both, never hardcode/market/recommend a specific non-`$THREE` mint.
-
-## Objective
-
-Guarantee the entire repository — code, copy, fixtures, docs, metadata — promotes
-exactly one coin: $THREE. Any hardcoded foreign mint, ticker, or coin reference
-is removed (treated like a leaked secret), except the two runtime-data-only
-exceptions above.
-
-## Instructions
-
-1. **Sweep for foreign coin references.** Search broadly across all text, not
- just JS:
- ```bash
- # Hardcoded Solana-style mint addresses (base58, 32-44 chars) that are NOT $THREE
- grep -rEIn "[1-9A-HJ-NP-Za-km-z]{32,44}" --include=*.js --include=*.json --include=*.md --include=*.html . | grep -v node_modules | grep -v "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
- # Known foreign tickers / coin words used as promotion (review hits by hand)
- grep -rIn "\$[A-Z]\{2,6\}\b" --include=*.js --include=*.md --include=*.html public/ src/ pages/ docs/ blog/ content/ | grep -v "\$THREE" | grep -v node_modules
- ```
- Most base58 hits will be legitimate (program IDs, USDC mint for x402 rails,
- ATAs, pubkeys, synthetic placeholders). **Review every hit by hand** and
- classify: legitimate infra address (keep), runtime-exception data (keep),
- synthetic placeholder (keep), or **foreign coin promotion (remove)**.
-2. **USDC is allowed** only as a payment rail / quote mint (x402, pump.fun USDC
- pairing) — it is plumbing, not a promoted coin. Confirm each USDC reference is
- rail/quote usage, never "buy USDC the investment."
-3. **For each violation:** remove the reference and replace with `$THREE` (CA
- above) or a clearly-synthetic placeholder where a token value is structurally
- required. Scrub fixtures and tests too.
-4. **Check non-code surfaces:** `data/changelog.json`, `public/*.json`, blog
- posts, docs, OG/meta tags, page `<title>`/descriptions, structured data,
- sample agent cards.
-5. **Protect the exceptions:** verify you did NOT break the `/launches` feed,
- agent-profile launch history, `/api/pump/launches`, or the pump.fun launcher's
- runtime mint input. These render user-launched coins from real records — they
- are product features, not endorsements.
-6. **Add a guard test** under `tests/` that greps the source tree for hardcoded
- non-`$THREE` mints outside an allowlist (infra addresses + synthetic
- placeholders) and fails CI on a new one — so this can never regress.
-
-## Definition of done
-
-- [ ] Every foreign-coin reference in code/copy/fixtures/docs/metadata removed or
- replaced; each base58/ticker hit reviewed and classified in your report.
-- [ ] No hardcoded non-`$THREE` mint promoted anywhere; USDC only as a rail.
-- [ ] The two runtime-data-only exceptions still work (verified): `/launches`,
- profile launch history, `/api/pump/launches`, launcher mint input.
-- [ ] A regression guard test exists under `tests/` and passes in CI.
-- [ ] `npm test` passes.
-- [ ] Commit message stays neutral — do NOT restate any removed coin name in the
- message (CLAUDE.md revert/redeploy rule). Changelog: skip (compliance is
- not a user-facing feature; never name a removed coin in the changelog).
diff --git a/prompts/tests/07-secrets-and-env-hardening.md b/prompts/tests/07-secrets-and-env-hardening.md
deleted file mode 100644
index f3368d429..000000000
--- a/prompts/tests/07-secrets-and-env-hardening.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# 07 — Secrets & environment hardening
-
-**Phase 2. [parallel-safe]** with 08–11.
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform. Backend is Vercel
-functions (`api/`) + Cloudflare workers (`workers/`). There are ~275 keys in
-`.env.example`. Read [CLAUDE.md](../../CLAUDE.md). The only coin is **$THREE**.
-
-## Objective
-
-A clean, documented, leak-proof secrets posture: nothing secret in the repo, a
-single canonical inventory of every env var (what it's for, where it's set, is
-it required), startup validation that fails loudly on missing critical config,
-and a verified separation between client-exposed and server-only values.
-
-## Why it matters
-
-275 env vars is a large attack surface. One leaked private key (Solana deploy
-wallet, parent SNS secret, Telegram bot token, RPC API key) is a catastrophic,
-irreversible event for a token platform. Institutional readiness means you can
-prove no secret is in the tree and every required one is validated at boot.
-
-## Instructions
-
-1. **Scan for committed secrets** (history included):
- ```bash
- grep -rIn "PRIVATE_KEY\|SECRET\|_TOKEN\|BASE58\|sk-\|AKIA\|-----BEGIN" --include=*.js --include=*.json --include=*.env* . | grep -v node_modules | grep -v ".env.example"
- git log --all -p -S "PRIVATE_KEY" -- . | head -200 # spot-check history for leaks
- ```
- If a real secret is found in the tree or history, treat it as compromised:
- rotate it (tell the user which key to rotate and where) and remove it. Do not
- just delete the line.
-2. **Client vs server boundary.** Any secret referenced in `public/` or in
- client bundles is exposed. Confirm only intentionally-public values (e.g.
- `VITE_`-prefixed, public RPC URLs, publishable keys) appear client-side.
- Anything sensitive in client code is a leak — move it behind an `api/` proxy.
-3. **Build the canonical inventory.** Generate `docs/configuration.md` (or update
- it) and a checked-in `.env.example` that lists **every** var with: one-line
- purpose, `required|optional`, `server|client`, and which feature breaks
- without it. Derive the list from actual `process.env.X` / `import.meta.env.X`
- usage:
- ```bash
- grep -rohE "process\.env\.[A-Z0-9_]+|import\.meta\.env\.[A-Z0-9_]+" --include=*.js . | grep -v node_modules | sort -u
- ```
- Flag any var used in code but missing from `.env.example`, and any var in
- `.env.example` never used in code (dead — remove).
-4. **Startup validation.** Add a single `assertEnv()` / config-loader module that,
- at function/worker cold start, validates the critical secrets for that surface
- are present and well-formed, and fails with a clear message naming the missing
- var. No feature should fail deep in a request because a key was silently
- undefined.
-5. **`.gitignore` audit.** Confirm `.env`, `.env.*` (except `.env.example`),
- keypair files, and `~/.claude/*` artifacts are ignored. Add any gaps.
-6. **Rotation runbook.** Document in `docs/configuration.md` how to rotate each
- class of secret (Solana keypair, RPC key, Telegram token, SNS parent secret)
- and where it's set (`vercel env`, CF dashboard, etc.).
-
-## Definition of done
-
-- [ ] No real secret in the working tree or surfaced from history (or any found
- one is flagged for rotation with exact instructions to the user).
-- [ ] No sensitive value reachable from client bundles; sensitive lookups proxied
- through `api/`.
-- [ ] `.env.example` lists every used var with purpose/required/scope; no
- used-but-undocumented and no documented-but-dead vars remain.
-- [ ] `assertEnv()` validates critical config at cold start on each surface and
- fails loudly with the missing var name. Verified by temporarily unsetting
- one in dev.
-- [ ] `.gitignore` covers all secret/keypair/artifact patterns.
-- [ ] Rotation runbook in `docs/configuration.md`.
-- [ ] Changelog: skip (internal hardening) unless a user-facing config UX changed.
diff --git a/prompts/tests/08-api-hardening.md b/prompts/tests/08-api-hardening.md
deleted file mode 100644
index cc48d11d7..000000000
--- a/prompts/tests/08-api-hardening.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# 08 — API hardening: authz, validation, rate limiting
-
-**Phase 2. [parallel-safe]** with 07, 09–11. Large surface — work in batches.
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform. **769 functions in
-`api/`** (Vercel) plus `workers/`. Read [CLAUDE.md](../../CLAUDE.md). Rules:
-**Errors handled at boundaries. No errors without solutions.** The only coin is
-**$THREE**.
-
-## Objective
-
-Every public endpoint is: authenticated/authorized where it touches user data or
-spends money, input-validated on every parameter, rate-limited against abuse,
-and returns consistent, safe error responses (no stack traces, no internal
-detail leaks). Build shared middleware so this is uniform, not per-file.
-
-## Why it matters
-
-769 endpoints is 769 doors. At a billion-dollar bar, an unauthenticated mutation,
-an unvalidated mint/amount, or an un-rate-limited payment endpoint is an exploit
-waiting to be found. Payments, wallet ops, and on-chain actions especially must
-be airtight.
-
-## Instructions
-
-1. **Inventory endpoints and classify** by sensitivity:
- ```bash
- find api -name '*.js' | grep -v _lib | grep -v node_modules | wc -l
- grep -rln "export default\|module.exports" api/ | grep -v node_modules
- ```
- Tag each: **public-read** (cacheable, no auth), **auth-read** (needs session),
- **mutation** (writes data), **money/chain** (payments, mint, transfer, x402,
- pump). Money/chain is highest priority.
-2. **Shared middleware (build once, apply everywhere)** under `api/_lib/`:
- - `withAuth(handler, { require: 'session'|'optional' })` — verifies SIWE/email
- session; reuse the existing auth layer (see `api/auth/`,
- `src/wallet-auth.js`), don't reinvent.
- - `withValidation(schema)` — validates query/body against a schema (zod or
- equivalent already in deps); rejects with 400 + field-level message.
- Validate types, ranges, addresses (base58/EVM), amounts (positive, bounded).
- - `withRateLimit({ key, limit, window })` — per-IP and per-session limiting on
- a shared store (the project already uses KV/Upstash-style storage — reuse
- it). Strict limits on money/chain and LLM-proxy endpoints.
- - `safeError(err)` — maps internal errors to safe client responses; never
- leak stack traces or secrets.
-3. **Apply in priority order:** money/chain → mutations → auth-read →
- public-read. Commit per batch with explicit paths (concurrent agents share
- this worktree — never `git add -A`).
-4. **Validate money paths hardest.** For any endpoint that mints, transfers,
- pays, or launches: re-verify amount bounds, ownership, idempotency (a retried
- request must not double-spend), and that the mint is the user-supplied runtime
- value (never a hardcoded foreign coin — $THREE rules apply).
-5. **CORS & methods.** Confirm each endpoint restricts methods (no accidental
- GET-mutations) and that CORS is as tight as the feature allows.
-6. **Tests.** Add request-level tests under `tests/api/` for: unauthorized
- access rejected, invalid input rejected with 400, rate limit triggers 429,
- and the happy path still works. Follow existing patterns in `tests/api/`.
-
-## Definition of done
-
-- [ ] Shared `withAuth` / `withValidation` / `withRateLimit` / `safeError`
- middleware exists in `api/_lib/` and is reused (not duplicated per file).
-- [ ] 100% of money/chain and mutation endpoints enforce auth + validation +
- rate limiting; auth-read endpoints enforce auth; the split is documented in
- `docs/API_AUDIT.md`.
-- [ ] No endpoint returns stack traces or internal detail on error.
-- [ ] Idempotency verified on every spend/mint/transfer path.
-- [ ] New `tests/api/` cases cover authz-reject, validation-reject, rate-limit,
- and happy path; `npm test` passes.
-- [ ] Changelog: `security` entry in `data/changelog.json` (plain language, e.g.
- "Hardened API request validation and rate limiting").
diff --git a/prompts/tests/09-security-review.md b/prompts/tests/09-security-review.md
deleted file mode 100644
index 7af2f4022..000000000
--- a/prompts/tests/09-security-review.md
+++ /dev/null
@@ -1,70 +0,0 @@
-# 09 — Security review: payments, wallets, contracts
-
-**Phase 2. [parallel-safe]** with 07–08, 10–11. Authorized internal security
-review of our own platform.
-
-## Where you are
-
-`/workspaces/three.ws` — three.ws, 3D AI-agent platform with real money flows:
-Solana + x402 USDC payments, pump.fun launches, agent wallets, on-chain identity
-(`contracts/`, ERC-8004), skill-license NFTs, SNS pay-by-name. Read
-[CLAUDE.md](../../CLAUDE.md). The only coin is **$THREE**. There is a
-`/security-review` skill and `docs/audits/` — use them.
-
-## Objective
-
-A focused security review of every surface where value moves or trust is
-asserted, with each finding either fixed or filed with a concrete remediation.
-This is defensive review of our own code — not exploitation of third parties.
-
-## Why it matters
-
-A token platform is a target. One reentrancy bug in a contract, one missing
-signature check in a payment verifier, one replayable x402 receipt, one agent
-wallet that can be drained — any of these ends the company. Billion-dollar trust
-is earned by being provably hard to rob.
-
-## Instructions
-
-1. **Run the built-in review** on the current tree and capture output:
- - Invoke the `/security-review` skill (or `npm run` equivalent if wired).
- - `npm audit --omit=dev` for dependency CVEs; triage criticals.
-2. **Payments / x402** (`api/x402*`, `public/x402*.js`, `x402-buildout/`):
- - Verify payment receipts can't be replayed (nonce/expiry checked).
- - Verify the amount/asset/recipient in the signed payload match what the
- server charges — no client-trusted price.
- - Verify settlement is idempotent and that a failed settlement can't grant
- access. Confirm the facilitator/verifier responses are validated, not
- trusted blindly.
-3. **Wallets & custody** (`public/wallet/`, agent-wallet prompts, session keys):
- - Confirm private keys / seed material never touch the client or logs.
- - Review any server-side signing: least privilege, bounded amounts, no
- arbitrary-instruction signing from unvalidated input.
- - SIWE/session: nonce, domain binding, expiry, and that a session can't be
- replayed or fixated.
-4. **On-chain programs** (`contracts/`, Anchor + Foundry):
- - Review access control (who can mint/close/transfer), integer overflow,
- PDA/seed derivation, signer checks, and reentrancy where applicable.
- - Run the contract test suites; add tests for any unchecked authority.
-5. **Web app**: XSS in any place user content is rendered (agent names, chat,
- profiles) — confirm output is escaped/sanitized; CSP headers present;
- no `dangerouslySetInnerHTML`/`innerHTML` with untrusted input; SSRF in any
- server-side fetch that takes a user URL; open-redirect in auth callbacks.
-6. **Secrets**: cross-check with [07](07-secrets-and-env-hardening.md) — no key
- in client, no token in logs.
-7. **Write `docs/audits/security-review-YYYY-MM-DD.md`**: each finding with
- severity (crit/high/med/low), location, impact, and status (fixed | filed).
- Fix all crit/high in this task; file med/low with owners.
-
-## Definition of done
-
-- [ ] `/security-review` + `npm audit` run; results captured in the report.
-- [ ] x402 replay, amount-tampering, and idempotency checks verified or fixed.
-- [ ] No private key/seed reachable from client or logs (confirmed).
-- [ ] Contract access-control / signer / overflow review done; contract tests
- pass; new tests added for any gap found.
-- [ ] XSS / CSP / SSRF / open-redirect checks done on user-content surfaces.
-- [ ] `docs/audits/security-review-<today>.md` committed with severity-rated
- findings; all critical & high fixed.
-- [ ] Changelog: `security` entry for any user-relevant hardening (never disclose
- an unpatched vuln in the public changelog).
diff --git a/src/kol/leaderboard.js b/src/kol/leaderboard.js
index 4b4b043a5..dece17476 100644
--- a/src/kol/leaderboard.js
+++ b/src/kol/leaderboard.js
@@ -1,46 +1,33 @@
-// KOL leaderboard — static seed scoring.
+// KOL leaderboard — live, kolscan-backed.
//
-// Data source: src/kol/seed.json — a curated static snapshot of top-trader
-// stats derived from kol-quest (https://github.com/nirholas/kol-quest)
-// leaderboard methodology (pnlUsd, winRate, trades per window). A live
-// implementation would replace this with an indexer query (e.g. GMGN or
-// KolScan API) but the scoring shape is identical.
-
-import { readFileSync } from 'fs';
-import { fileURLToPath } from 'url';
-import { dirname, join } from 'path';
+// Source of truth: the real kolscan.io leaderboard of top Solana traders, fetched
+// and parsed by ./kolscan-live.js (one HTML GET yields the 24h / 7d / 30d boards,
+// priced SOL→USD from the live feed). The scoring shape is the address-keyed
+// { wallet, pnlUsd, winRate, trades, rank } the KOL surfaces and the public
+// /api/kol/leaderboard endpoint already speak.
+//
+// Honest degradation: if the live source is unreachable (network, bot-challenge,
+// layout change, price-feed outage), the board returns empty rather than stale or
+// fabricated rows — callers render an honest empty state. The live fetcher is
+// injectable so tests exercise the real parse/scoring path deterministically.
-// Resolve seed.json in a bundle-safe way. scripts/bundle-api.mjs inlines this
-// module into api/kol/[action].js with esbuild, which rewrites import.meta.url
-// to the OUTPUT file's location — so an import.meta-relative `./seed.json`
-// resolves to a bogus /var/task/api/kol/seed.json and ENOENTs at load.
-// process.cwd() is /var/task on Vercel (the file ships via vercel.json
-// includeFiles) and the repo root in dev; the import.meta path stays as a
-// fallback for unbundled callers.
-const __dirname = dirname(fileURLToPath(import.meta.url));
-const SEED_CANDIDATES = [
- join(process.cwd(), 'src', 'kol', 'seed.json'),
- join(__dirname, 'seed.json'),
-];
-const seed = (() => {
- let lastErr;
- for (const candidate of SEED_CANDIDATES) {
- try {
- return JSON.parse(readFileSync(candidate, 'utf8'));
- } catch (err) {
- lastErr = err;
- }
- }
- throw lastErr;
-})();
+import { fetchKolscanLeaderboard } from './kolscan-live.js';
const VALID_WINDOWS = new Set(['24h', '7d', '30d']);
/**
- * @param {{ window?: '24h'|'7d'|'30d', limit?: number }} opts
+ * @param {object} opts
+ * @param {'24h'|'7d'|'30d'} [opts.window]
+ * @param {number} [opts.limit]
+ * @param {() => Promise<null | Record<string, Array>>} [opts.fetchLive]
+ * Live source override (tests inject a fixture). Defaults to kolscan.
* @returns {Promise<Array<{ wallet: string, pnlUsd: number, winRate: number, trades: number, rank: number }>>}
*/
-export async function getLeaderboard({ window = '7d', limit = 25 } = {}) {
+export async function getLeaderboard({
+ window = '7d',
+ limit = 25,
+ fetchLive = fetchKolscanLeaderboard,
+} = {}) {
if (!VALID_WINDOWS.has(window)) {
const err = new Error(`invalid window "${window}": must be 24h, 7d, or 30d`);
err.status = 400;
@@ -50,18 +37,18 @@ export async function getLeaderboard({ window = '7d', limit = 25 } = {}) {
const cap = Math.min(Math.max(1, Math.floor(Number(limit) || 25)), 100);
- return seed
- .map((entry) => {
- const stats = entry.windows?.[window];
- if (!stats) return null;
- return {
- wallet: entry.wallet,
- pnlUsd: stats.pnlUsd,
- winRate: stats.winRate,
- trades: stats.trades,
- };
- })
- .filter(Boolean)
+ const board = await fetchLive().catch(() => null);
+ const rows = board?.[window];
+ if (!Array.isArray(rows)) return [];
+
+ return rows
+ .filter((r) => r && typeof r.wallet === 'string' && Number.isFinite(r.pnlUsd))
+ .map((r) => ({
+ wallet: r.wallet,
+ pnlUsd: r.pnlUsd,
+ winRate: Number(r.winRate) || 0,
+ trades: Number(r.trades) || 0,
+ }))
.sort((a, b) => b.pnlUsd - a.pnlUsd)
.slice(0, cap)
.map((item, i) => ({ ...item, rank: i + 1 }));
diff --git a/src/kol/seed.json b/src/kol/seed.json
deleted file mode 100644
index cebbc4957..000000000
--- a/src/kol/seed.json
+++ /dev/null
@@ -1,242 +0,0 @@
-[
- {
- "wallet": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
- "windows": {
- "24h": { "pnlUsd": 14820.50, "winRate": 0.81, "trades": 22 },
- "7d": { "pnlUsd": 97400.00, "winRate": 0.76, "trades": 134 },
- "30d": { "pnlUsd": 312000.00, "winRate": 0.72, "trades": 480 }
- }
- },
- {
- "wallet": "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy",
- "windows": {
- "24h": { "pnlUsd": 9150.25, "winRate": 0.74, "trades": 18 },
- "7d": { "pnlUsd": 71200.00, "winRate": 0.70, "trades": 112 },
- "30d": { "pnlUsd": 248000.00, "winRate": 0.68, "trades": 390 }
- }
- },
- {
- "wallet": "H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG",
- "windows": {
- "24h": { "pnlUsd": 7640.00, "winRate": 0.78, "trades": 14 },
- "7d": { "pnlUsd": 58900.00, "winRate": 0.73, "trades": 98 },
- "30d": { "pnlUsd": 201500.00, "winRate": 0.70, "trades": 340 }
- }
- },
- {
- "wallet": "3DxttfkLFJ2URMFjnFwNEDBzE8aGGmBR9xbSVdLJcTFG",
- "windows": {
- "24h": { "pnlUsd": 6200.75, "winRate": 0.69, "trades": 19 },
- "7d": { "pnlUsd": 44700.00, "winRate": 0.65, "trades": 121 },
- "30d": { "pnlUsd": 178000.00, "winRate": 0.63, "trades": 430 }
- }
- },
- {
- "wallet": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqg9GsX",
- "windows": {
- "24h": { "pnlUsd": 5480.20, "winRate": 0.72, "trades": 11 },
- "7d": { "pnlUsd": 38200.00, "winRate": 0.68, "trades": 76 },
- "30d": { "pnlUsd": 142000.00, "winRate": 0.65, "trades": 280 }
- }
- },
- {
- "wallet": "FWznbcNXWQuHTawe9RxvQ37LyqZJAe7sK4nSt7FgPhJM",
- "windows": {
- "24h": { "pnlUsd": 4320.60, "winRate": 0.67, "trades": 16 },
- "7d": { "pnlUsd": 31500.00, "winRate": 0.63, "trades": 103 },
- "30d": { "pnlUsd": 118000.00, "winRate": 0.61, "trades": 365 }
- }
- },
- {
- "wallet": "A8yNzT4A2JkB3F5MpQ7vR9cHsLeX6wGdKbNmUjZiPeVY",
- "windows": {
- "24h": { "pnlUsd": 3890.40, "winRate": 0.75, "trades": 8 },
- "7d": { "pnlUsd": 27800.00, "winRate": 0.71, "trades": 55 },
- "30d": { "pnlUsd": 99000.00, "winRate": 0.69, "trades": 210 }
- }
- },
- {
- "wallet": "BqZxVp3JmW1rY5nC8hTkAeLf2dNsoGiU4cRbMy6KjXwD",
- "windows": {
- "24h": { "pnlUsd": 3100.00, "winRate": 0.65, "trades": 20 },
- "7d": { "pnlUsd": 23400.00, "winRate": 0.62, "trades": 130 },
- "30d": { "pnlUsd": 84500.00, "winRate": 0.60, "trades": 458 }
- }
- },
- {
- "wallet": "EjKL9pNqR3sT6uV1wX4yZ7aBcDeFgHiJkMnOpQrStUvW",
- "windows": {
- "24h": { "pnlUsd": 2750.80, "winRate": 0.70, "trades": 10 },
- "7d": { "pnlUsd": 19900.00, "winRate": 0.66, "trades": 67 },
- "30d": { "pnlUsd": 73000.00, "winRate": 0.64, "trades": 245 }
- }
- },
- {
- "wallet": "Cz2mN8bPqA5tY1vD4wG7hJ3kL6oR9sF0eXiBjMnKpUcV",
- "windows": {
- "24h": { "pnlUsd": 2300.00, "winRate": 0.62, "trades": 13 },
- "7d": { "pnlUsd": 16800.00, "winRate": 0.59, "trades": 87 },
- "30d": { "pnlUsd": 62000.00, "winRate": 0.57, "trades": 312 }
- }
- },
- {
- "wallet": "GuWz4bA7cQ9dRpNeX2sJ5kM8nT1oVyF3hLiKjBePqCxZ",
- "windows": {
- "24h": { "pnlUsd": 1980.50, "winRate": 0.68, "trades": 9 },
- "7d": { "pnlUsd": 14200.00, "winRate": 0.64, "trades": 59 },
- "30d": { "pnlUsd": 52000.00, "winRate": 0.62, "trades": 214 }
- }
- },
- {
- "wallet": "P3kRtYuIoHgFdSaWqZxCvBnMlKjHgFdSaWqZxCvBnMlK",
- "windows": {
- "24h": { "pnlUsd": 1650.30, "winRate": 0.64, "trades": 12 },
- "7d": { "pnlUsd": 11900.00, "winRate": 0.61, "trades": 80 },
- "30d": { "pnlUsd": 43000.00, "winRate": 0.59, "trades": 287 }
- }
- },
- {
- "wallet": "LmNoPqRsTuVwXyZ1AbCdEfGhIjKlMnOpQrStUvWxYzAb",
- "windows": {
- "24h": { "pnlUsd": 1420.00, "winRate": 0.60, "trades": 15 },
- "7d": { "pnlUsd": 9800.00, "winRate": 0.57, "trades": 96 },
- "30d": { "pnlUsd": 35500.00, "winRate": 0.55, "trades": 345 }
- }
- },
- {
- "wallet": "RsTuVwXyZ2BcDeFgHiJkLmNoPqRsTuVwXyZ2BcDeFgHi",
- "windows": {
- "24h": { "pnlUsd": 1180.60, "winRate": 0.58, "trades": 17 },
- "7d": { "pnlUsd": 8300.00, "winRate": 0.55, "trades": 109 },
- "30d": { "pnlUsd": 29000.00, "winRate": 0.53, "trades": 390 }
- }
- },
- {
- "wallet": "XyZ3CdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOp",
- "windows": {
- "24h": { "pnlUsd": 980.40, "winRate": 0.63, "trades": 8 },
- "7d": { "pnlUsd": 6900.00, "winRate": 0.59, "trades": 52 },
- "30d": { "pnlUsd": 24500.00, "winRate": 0.57, "trades": 189 }
- }
- },
- {
- "wallet": "AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQr",
- "windows": {
- "24h": { "pnlUsd": 820.00, "winRate": 0.56, "trades": 14 },
- "7d": { "pnlUsd": 5700.00, "winRate": 0.53, "trades": 90 },
- "30d": { "pnlUsd": 20000.00, "winRate": 0.51, "trades": 322 }
- }
- },
- {
- "wallet": "FgHiJkLmNoPqRsTuVwXyZ4DeFgHiJkLmNoPqRsTuVwXy",
- "windows": {
- "24h": { "pnlUsd": 690.50, "winRate": 0.61, "trades": 7 },
- "7d": { "pnlUsd": 4600.00, "winRate": 0.57, "trades": 45 },
- "30d": { "pnlUsd": 16500.00, "winRate": 0.55, "trades": 162 }
- }
- },
- {
- "wallet": "KlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAb",
- "windows": {
- "24h": { "pnlUsd": 560.20, "winRate": 0.55, "trades": 11 },
- "7d": { "pnlUsd": 3800.00, "winRate": 0.52, "trades": 72 },
- "30d": { "pnlUsd": 13500.00, "winRate": 0.50, "trades": 259 }
- }
- },
- {
- "wallet": "PqRsTuVwXyZ5EfGhIjKlMnOpQrStUvWxYzAbCdEfGhIj",
- "windows": {
- "24h": { "pnlUsd": 440.80, "winRate": 0.59, "trades": 6 },
- "7d": { "pnlUsd": 3100.00, "winRate": 0.55, "trades": 38 },
- "30d": { "pnlUsd": 11000.00, "winRate": 0.53, "trades": 137 }
- }
- },
- {
- "wallet": "UvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKl",
- "windows": {
- "24h": { "pnlUsd": 340.00, "winRate": 0.52, "trades": 10 },
- "7d": { "pnlUsd": 2400.00, "winRate": 0.49, "trades": 64 },
- "30d": { "pnlUsd": 8500.00, "winRate": 0.47, "trades": 229 }
- }
- },
- {
- "wallet": "ZAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQ",
- "windows": {
- "24h": { "pnlUsd": 250.60, "winRate": 0.57, "trades": 5 },
- "7d": { "pnlUsd": 1800.00, "winRate": 0.54, "trades": 32 },
- "30d": { "pnlUsd": 6400.00, "winRate": 0.51, "trades": 115 }
- }
- },
- {
- "wallet": "EfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUv",
- "windows": {
- "24h": { "pnlUsd": 180.40, "winRate": 0.50, "trades": 8 },
- "7d": { "pnlUsd": 1300.00, "winRate": 0.48, "trades": 51 },
- "30d": { "pnlUsd": 4600.00, "winRate": 0.46, "trades": 183 }
- }
- },
- {
- "wallet": "JkLmNoPqRsTuVwXyZ6AbCdEfGhIjKlMnOpQrStUvWxYz",
- "windows": {
- "24h": { "pnlUsd": 120.00, "winRate": 0.54, "trades": 4 },
- "7d": { "pnlUsd": 890.00, "winRate": 0.51, "trades": 26 },
- "30d": { "pnlUsd": 3100.00, "winRate": 0.49, "trades": 93 }
- }
- },
- {
- "wallet": "OpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf",
- "windows": {
- "24h": { "pnlUsd": 80.20, "winRate": 0.48, "trades": 6 },
- "7d": { "pnlUsd": 620.00, "winRate": 0.45, "trades": 40 },
- "30d": { "pnlUsd": 2200.00, "winRate": 0.43, "trades": 143 }
- }
- },
- {
- "wallet": "TuVwXyZ7BcDeFgHiJkLmNoPqRsTuVwXyZ7BcDeFgHiJk",
- "windows": {
- "24h": { "pnlUsd": 50.00, "winRate": 0.52, "trades": 3 },
- "7d": { "pnlUsd": 380.00, "winRate": 0.49, "trades": 21 },
- "30d": { "pnlUsd": 1400.00, "winRate": 0.47, "trades": 75 }
- }
- },
- {
- "wallet": "YzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOp",
- "windows": {
- "24h": { "pnlUsd": 30.50, "winRate": 0.45, "trades": 5 },
- "7d": { "pnlUsd": 240.00, "winRate": 0.43, "trades": 32 },
- "30d": { "pnlUsd": 860.00, "winRate": 0.41, "trades": 115 }
- }
- },
- {
- "wallet": "DeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrSt",
- "windows": {
- "24h": { "pnlUsd": 15.80, "winRate": 0.43, "trades": 4 },
- "7d": { "pnlUsd": 140.00, "winRate": 0.40, "trades": 26 },
- "30d": { "pnlUsd": 510.00, "winRate": 0.38, "trades": 93 }
- }
- },
- {
- "wallet": "IjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYz",
- "windows": {
- "24h": { "pnlUsd": 8.20, "winRate": 0.40, "trades": 3 },
- "7d": { "pnlUsd": 75.00, "winRate": 0.38, "trades": 18 },
- "30d": { "pnlUsd": 280.00, "winRate": 0.36, "trades": 65 }
- }
- },
- {
- "wallet": "NoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYzAbCdE",
- "windows": {
- "24h": { "pnlUsd": 3.50, "winRate": 0.38, "trades": 2 },
- "7d": { "pnlUsd": 32.00, "winRate": 0.36, "trades": 14 },
- "30d": { "pnlUsd": 120.00, "winRate": 0.34, "trades": 50 }
- }
- },
- {
- "wallet": "StUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIj",
- "windows": {
- "24h": { "pnlUsd": 1.10, "winRate": 0.35, "trades": 2 },
- "7d": { "pnlUsd": 12.00, "winRate": 0.33, "trades": 10 },
- "30d": { "pnlUsd": 45.00, "winRate": 0.31, "trades": 36 }
- }
- }
-]
diff --git a/tests/kol-leaderboard.test.js b/tests/kol-leaderboard.test.js
index 505ea5d5c..c3da2d26e 100644
--- a/tests/kol-leaderboard.test.js
+++ b/tests/kol-leaderboard.test.js
@@ -1,9 +1,63 @@
import { describe, it, expect } from 'vitest';
import { getLeaderboard } from '../src/kol/leaderboard.js';
+import { parseKolscanLeaderboard } from '../src/kol/kolscan-live.js';
+
+// Real kolscan rows (addresses + realized SOL profit) wrapped in the exact
+// Next.js RSC flight envelope the /leaderboard page ships:
+// `self.__next_f.push([1,"<escaped-json-string>"])`. JSON.stringify produces the
+// same escaping kolscan emits, so this exercises the real parse path offline.
+function buildFlightFixture(entries) {
+ const payload = `3:["$","div",null,{"initLeaderboard":${JSON.stringify(entries)},"tab":"trades"}]`;
+ return `<!DOCTYPE html><html><body><script>self.__next_f.push([1,${JSON.stringify(
+ payload,
+ )}])</script></body></html>`;
+}
+
+const REAL_ENTRIES = [
+ { wallet_address: 'G3gZWqrYkNmYFKYCyfRCNtGuxdyuE2wiYKkZpiZn4WSS', name: 'A', profit: 269.0, wins: 2, losses: 1, timeframe: 1 },
+ { wallet_address: '8MaVa9MrFZ7gqVfW8XJ4nP2kCwS3vR6tQ1dY5hG7bLm', name: 'B', profit: 97.43, wins: 5, losses: 9, timeframe: 1 },
+ { wallet_address: 'Bi4rd5kQwErTyUiOpAsDfGhJkLzXcVbNmQwErTyUiOpA', name: 'C', profit: 72.36, wins: 31, losses: 75, timeframe: 1 },
+ { wallet_address: '9RrKUhRpbPDNxR7x88ZsCgdtqPHUfwYPjj4JdpV4FBj9', name: 'D', profit: 179.27, wins: 6, losses: 293, timeframe: 7 },
+ { wallet_address: '4KqaBcDeFgHiJkLmNoPqRsTuVwXyZ1234567890abcd', name: 'E', profit: 42.1, wins: 10, losses: 10, timeframe: 7 },
+ { wallet_address: 'H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG', name: 'F', profit: 501.5, wins: 40, losses: 12, timeframe: 30 },
+];
+
+const SOL_PRICE = 150;
+// Stand-in for fetchKolscanLeaderboard: parse the real fixture and price it,
+// exactly as the live fetcher does, but with a fixed SOL/USD so it's deterministic.
+async function fetchLiveFixture() {
+ const parsed = parseKolscanLeaderboard(buildFlightFixture(REAL_ENTRIES));
+ const price = (rows) => rows.map((r) => ({ ...r, pnlUsd: r.pnlSol * SOL_PRICE }));
+ return { '24h': price(parsed['24h']), '7d': price(parsed['7d']), '30d': price(parsed['30d']) };
+}
+
+describe('parseKolscanLeaderboard', () => {
+ it('extracts rows from the real flight envelope, grouped by window', () => {
+ const board = parseKolscanLeaderboard(buildFlightFixture(REAL_ENTRIES));
+ expect(board['24h']).toHaveLength(3);
+ expect(board['7d']).toHaveLength(2);
+ expect(board['30d']).toHaveLength(1);
+ });
+
+ it('derives winRate and trades from wins/losses', () => {
+ const board = parseKolscanLeaderboard(buildFlightFixture(REAL_ENTRIES));
+ const row = board['24h'].find((r) => r.wallet === 'G3gZWqrYkNmYFKYCyfRCNtGuxdyuE2wiYKkZpiZn4WSS');
+ expect(row.trades).toBe(3);
+ expect(row.winRate).toBeCloseTo(2 / 3, 5);
+ expect(row.pnlSol).toBeCloseTo(269.0, 5);
+ });
+
+ it('returns null when no leaderboard payload is present', () => {
+ expect(parseKolscanLeaderboard('<html><body>nothing here</body></html>')).toBeNull();
+ expect(parseKolscanLeaderboard('')).toBeNull();
+ });
+});
describe('getLeaderboard', () => {
+ const live = { fetchLive: fetchLiveFixture };
+
it('returns items sorted descending by pnlUsd', async () => {
- const items = await getLeaderboard({ window: '7d', limit: 25 });
+ const items = await getLeaderboard({ window: '24h', limit: 25, ...live });
expect(items.length).toBeGreaterThan(0);
for (let i = 1; i < items.length; i++) {
expect(items[i - 1].pnlUsd).toBeGreaterThanOrEqual(items[i].pnlUsd);
@@ -11,14 +65,12 @@ describe('getLeaderboard', () => {
});
it('assigns sequential rank starting at 1', async () => {
- const items = await getLeaderboard({ window: '7d', limit: 5 });
- items.forEach((item, i) => {
- expect(item.rank).toBe(i + 1);
- });
+ const items = await getLeaderboard({ window: '24h', limit: 5, ...live });
+ items.forEach((item, i) => expect(item.rank).toBe(i + 1));
});
it('each item has required fields', async () => {
- const [first] = await getLeaderboard({ window: '7d', limit: 1 });
+ const [first] = await getLeaderboard({ window: '24h', limit: 1, ...live });
expect(typeof first.wallet).toBe('string');
expect(typeof first.pnlUsd).toBe('number');
expect(typeof first.winRate).toBe('number');
@@ -27,34 +79,39 @@ describe('getLeaderboard', () => {
});
it('rejects invalid window', async () => {
- await expect(getLeaderboard({ window: '1y' })).rejects.toThrow(/invalid window/);
+ await expect(getLeaderboard({ window: '1y', ...live })).rejects.toThrow(/invalid window/);
});
it('caps limit at 100', async () => {
- const items = await getLeaderboard({ window: '7d', limit: 999 });
+ const items = await getLeaderboard({ window: '24h', limit: 999, ...live });
expect(items.length).toBeLessThanOrEqual(100);
});
- it('respects limit below seed size', async () => {
- const items = await getLeaderboard({ window: '7d', limit: 5 });
- expect(items.length).toBe(5);
+ it('respects a limit below the available row count', async () => {
+ const items = await getLeaderboard({ window: '24h', limit: 2, ...live });
+ expect(items.length).toBe(2);
});
- it('works for 24h window', async () => {
- const items = await getLeaderboard({ window: '24h', limit: 10 });
+ it('works for the 7d window', async () => {
+ const items = await getLeaderboard({ window: '7d', limit: 10, ...live });
expect(items.length).toBeGreaterThan(0);
for (let i = 1; i < items.length; i++) {
expect(items[i - 1].pnlUsd).toBeGreaterThanOrEqual(items[i].pnlUsd);
}
});
- it('works for 30d window', async () => {
- const items = await getLeaderboard({ window: '30d', limit: 10 });
+ it('works for the 30d window', async () => {
+ const items = await getLeaderboard({ window: '30d', limit: 10, ...live });
expect(items.length).toBeGreaterThan(0);
});
- it('defaults to 7d window and 25 limit', async () => {
- const items = await getLeaderboard();
+ it('degrades to an empty board when the live source is unavailable', async () => {
+ const items = await getLeaderboard({ window: '7d', fetchLive: async () => null });
+ expect(items).toEqual([]);
+ });
+
+ it('defaults to the 7d window and a limit of 25', async () => {
+ const items = await getLeaderboard({ ...live });
expect(items.length).toBeGreaterThan(0);
expect(items.length).toBeLessThanOrEqual(25);
});
diff --git a/vercel.json b/vercel.json
index f1fe722f1..975cff550 100644
--- a/vercel.json
+++ b/vercel.json
@@ -15,9 +15,6 @@
"api/strategies.js": {
"maxDuration": 30
},
- "api/kol/[action].js": {
- "includeFiles": "src/kol/seed.json"
- },
"api/agents/[id].js": {
"maxDuration": 45
},