Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: add design-system consistency and SEO structured data prompts
miniaturization1dbebf1d87ac
diff --git a/docs/tutorials/claim-threews-name.md b/docs/tutorials/claim-threews-name.mdnew file mode 100644index 000000000..eb1845666--- /dev/null+++ b/docs/tutorials/claim-threews-name.md@@ -0,0 +1,301 @@+# Claim a *.threews.sol name and get paid by name++By the end of this tutorial you'll own a real Solana Name Service name — `yourname.threews.sol` — that resolves to your three.ws showcase in Brave, and you'll know exactly how another agent or person sends you USDC using that name instead of a 44-character wallet address.++Along the way you'll understand what the subdomain points at on-chain, why the mint is gasless for you, and how the pay-by-name endpoint turns a human-readable name into a signed USDC transfer.++**Prerequisites:** a signed-in three.ws account with a **username set** (the subdomain label must match it) and at least one agent — creating an agent provisions the Solana wallet that receives the name ([create one](/create)). Light JavaScript familiarity for the pay-by-name section; the claim itself is no-code.++---++## What you're building++```+You (once): claim "nich" at /threews/claim+ ↓ [threews.sol subdomain minted, URL record set, ownership transferred to your wallet]+Anyone, later: pays nich.threews.sol → USDC lands in your wallet+Brave user: types nich.threews.sol → lands on https://three.ws/u/nich+```++A wallet address is unspeakable, unmemorable, and easy to fat-finger. `nich.threews.sol` is a name a person can read aloud, an agent can resolve in one request, and a browser can navigate to. One claim gives you all three: a resolvable name, a showcase page, and a pay-by-name handle.++---++## How it works (two minutes of theory)++three.ws owns the parent domain `threews.sol`. When you claim a label, the platform mints `<label>.threews.sol` as a **subdomain** under that parent and hands it to you. Three on-chain actions happen inside **one** transaction (so the subdomain is never claimable by a third party in between):++1. **createSubdomain** — the parent owner mints the new registry and is, momentarily, its owner.+2. **createRecordV2Instruction(URL → `https://three.ws/u/<label>`)** — a `URL` record is written while the platform still owns the subdomain. This record is what makes the name resolve in Brave and any SNS-aware client.+3. **transferSubdomain** — ownership (and the attached records) is transferred to your wallet.++The platform keypair is the only signer and fee payer, so **you pay no SOL gas and never sign a wallet transaction** to claim. After the transfer, the name is yours — the platform doesn't retain custody, it just set the URL record on the way out.++What the name resolves *to* depends on the flow:++| Flow | Endpoint | URL record points at |+|---|---|---|+| **User claim** (this tutorial) | [POST /api/threews/subdomain](/api/threews/subdomain) | `https://three.ws/u/<label>` — your showcase |+| **Agent attach** | [POST /api/sns-subdomain](/api/sns-subdomain) | `https://three.ws/a/<agent_id>` — the agent page |++For payments, three.ws resolves any of three name forms to a recipient wallet, in this order: a raw base58 address (pass-through), a `.sol` domain or subdomain (resolved on-chain via Bonfida `resolve()`), or a bare `@username` (looked up to the user's default agent wallet). That's what makes `nich.threews.sol`, `@nich`, and the raw address all valid payment targets.++Two hard rules to know before you start:++- **The label must equal your account username.** `<label>.threews.sol` showcases `/u/<label>`, so allowing divergent labels would let anyone mint a name impersonating another handle. Set your username first if you haven't.+- **Some labels are reserved.** Platform paths and impersonation-risk words (`admin`, `api`, `pay`, `threews`, `wallet`, `official`, and similar) are denied. The availability check tells you immediately.++---++## Step 1: Set your username++The mint endpoint rejects any label that doesn't match `users.username` (HTTP `409 username_mismatch`), so this is the gate.++1. Open your account settings and set a username if you don't have one — it must be lowercase `[a-z0-9-]`, 1–63 characters, and not a reserved word.+2. That username **is** your subdomain label. If your username is `nich`, you can only claim `nich.threews.sol`.++If you skip this, the mint fails with `409 no_username` ("set a username on your account before claiming a subdomain").++---++## Step 2: Open the claim page++Go to **[/threews/claim](/threews/claim)**.++You'll see a single input with a fixed `.threews.sol` suffix and a disabled **Mint subdomain** button. The button stays disabled until the availability check confirms the label is free.++Type your username into the label field. As you type, the page:++- Lowercases the input and strips anything outside `[a-z0-9-]` in real time.+- Debounces for 350ms, then calls `GET /api/threews/subdomain?label=<label>` to check availability.++---++## Step 3: Read the availability result++The check returns a small envelope describing the label's status:++```jsonc+{+ "data": {+ "full": "nich.threews.sol",+ "label": "nich",+ "parent": "threews",+ "available": true,+ "owner": null,+ "on_chain_check": "ok",+ "on_chain_error": null,+ "claim": null,+ "showcase_url": null+ }+}+```++Interpreting it:++- **`available: true`** — nobody has claimed it through three.ws and no on-chain owner was found. The Mint button enables and the status reads `nich.threews.sol is available.`+- **`available: false` with `claim`** — already claimed through three.ws; the status shows `claimed by @<username>`.+- **`available: false` with only `owner`** — registered on-chain to a wallet outside our records; the status shows `owned by <wallet>`.+- **`on_chain_check: "unavailable"`** — a Solana RPC hiccup meant the on-chain side couldn't be verified. The endpoint still answers `200` (it won't `500` the UI) and the response is sent `no-store` so you can retry. If you see this, wait a moment and re-type the last character to re-check.++The availability check is **public and rate-limited** — it needs no auth, so you can verify a label before committing.++---++## Step 4: Mint the subdomain++With an available label, click **Mint subdomain**. The page now does the authenticated write:++1. Fetches a CSRF token from `/api/csrf-token` (your session must be signed in).+2. `POST /api/threews/subdomain` with `{ "label": "nich" }`, sending the `x-csrf-token` header and same-origin credentials.++```jsonc+// POST /api/threews/subdomain+// headers: { "content-type": "application/json", "x-csrf-token": "<token>" }+// credentials: same-origin+{ "label": "nich" }+```++The server then, in order:++1. Confirms minting is configured (the platform parent key is present) — otherwise `503 config_missing`.+2. Loads your user, confirms you have a username, and confirms it **matches the label** — otherwise `409`.+3. Confirms nobody has claimed it through three.ws and nobody owns it on-chain — otherwise `409 conflict`.+4. Picks the **recipient wallet**: if you pass `owner_wallet` it must be a Solana wallet **linked to your account** (else `403 forbidden`); otherwise it falls back to your **default agent's Solana wallet** (the oldest agent you own). No agent and no linked wallet → `409 no_wallet`.+5. Runs the atomic mint + URL-record + transfer transaction and records the claim in `user_subdomains`.++On success you get a `201` with the receipt:++```jsonc+{+ "data": {+ "id": "…",+ "label": "nich",+ "parent": "threews",+ "owner_wallet": "<your Solana wallet>",+ "url_record": "https://three.ws/u/nich",+ "signature": "<tx signature>",+ "full": "nich.threews.sol",+ "showcase_url": "https://three.ws/u/nich",+ "explorer": "https://solscan.io/tx/<signature>"+ }+}+```++The page renders a green result card with your name, the showcase link, and a Solscan link to the on-chain transaction. The subdomain is yours and already owned by your wallet — the whole thing typically lands in a few seconds.++### Claiming to a specific wallet++To receive the name in a wallet other than your default agent's, link that Solana wallet to your account first, then include it in the POST body:++```jsonc+{ "label": "nich", "owner_wallet": "<your linked base58 wallet>" }+```++If the wallet isn't linked, the mint refuses with `403` — three.ws will not mint a subdomain into a third-party wallet.++---++## Step 5: Verify the name resolves++Two ways to confirm the claim is live.++**Forward resolution (any client):**++```js+const r = await fetch('/api/sns?name=nich.threews.sol');+const { data } = await r.json();+// { name: "nich.threews.sol", address: "<wallet>", network: "solana", resolved: true }+```++`/api/sns` is the public resolver. A miss returns `resolved: false` with `address: null` (a `200`, not a `404`) — so if you see `resolved: false` right after minting, give the RPC cache its short TTL and retry.++**In Brave:** type `nich.threews.sol` into the URL bar. Because the `URL` record was written at mint time, Brave's SNS resolver redirects you straight to `https://three.ws/u/nich` — your showcase, rendering your public agents, avatars, paid skills, and socials. No extension, no plugin.++---++## Step 6: Resolve the name for a payment++Now the payoff: getting paid by name. Anyone — a human or an agent — can resolve your name to a wallet with a single public GET:++```js+const r = await fetch('/api/x402/pay-by-name?name=nich.threews.sol');+const { data } = await r.json();+// {+// address: "<your wallet base58>",+// source: "sns",+// resolved: "nich.threews.sol",+// claim: { user_id, username: "nich", display_name } // present for *.threews.sol+// }+```++The resolver accepts all three name forms, tried in order:++1. A **raw base58 address** → returned as-is (`source: "address"`).+2. A **`.sol` domain or subdomain** like `nich.threews.sol` → resolved on-chain via Bonfida `resolve()` (`source: "sns"`). For `*.threews.sol` names it also attaches the matching three.ws `claim` so the caller can show your showcase link.+3. A bare **`@username`** (3–30 chars) → mapped to that user's default agent Solana wallet (`source: "username"`).++A name that resolves to nothing returns `404 not_found`. This GET is the safe, side-effect-free way to preview *exactly which wallet* a name points at before sending anything.++---++## Step 7: Have someone pay you by name++There are two payment modes on `POST /api/x402/pay-by-name`. Payments are denominated in **USDC** (mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`, 6 decimals), capped at **10,000 USDC per call**.++### Mode `prep` — browser wallet signs (no auth)++The payer passes their own wallet as `payer_wallet`; the server builds an **unsigned** USDC SPL transfer and returns it base64-encoded for the payer's wallet to sign and broadcast. The transfer includes an idempotent "create associated token account" instruction so it works even if your USDC token account doesn't exist yet.++```js+const r = await fetch('/api/x402/pay-by-name', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ name: 'nich.threews.sol',+ amount_usdc: 5,+ payer_wallet: '<payer base58 wallet>',+ // mode defaults to "prep"+ }),+});+const { data } = await r.json();+// {+// recipient: { address, source: "sns", resolved: "nich.threews.sol", claim },+// amount_usdc: 5,+// tx_base64: "<unsigned VersionedTransaction>",+// blockhash, last_valid_block_height,+// mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"+// }+```++The payer deserializes `tx_base64`, signs with their wallet, and submits it to Solana. No three.ws account needed on the payer's side.++### Mode `send` — an agent pays on the caller's behalf (auth required)++If the payer is a three.ws user paying from one of **their own agents**, `mode: "send"` has the server sign as that agent and broadcast the transfer, returning the signature directly. This requires a signed-in session (or bearer token) and an `agent_id` the caller owns.++```js+const r = await fetch('/api/x402/pay-by-name', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ name: 'nich.threews.sol',+ amount_usdc: 5,+ mode: 'send',+ agent_id: '<your agent uuid>',+ expected_address: '<address you previewed in Step 6>', // recommended+ }),+});+const { data } = await r.json();+// { recipient, payer, amount_usdc: 5, signature: "<tx>", mode: "send" }+```++Two guardrails worth knowing on the send path:++- **`expected_address`** — pass the address you previewed, and the server requires the fresh resolution to still match it before signing. A name can repoint between preview and send (or a lookalike name can resolve to an attacker wallet); this binds the recipient you approved into the signed request. A mismatch returns `409 recipient_changed`.+- **Per-transaction limit** — the agent's configured per-tx USD ceiling applies. A send over the limit returns `403 per_tx_exceeded`. The amount must also be `> 0`, and off-curve targets (PDAs/program addresses) are rejected as invalid recipients.++Either way, the USDC lands in the wallet your `nich.threews.sol` points at — the one the subdomain was transferred to in Step 4.++---++## What you get from one claim++- `nich.threews.sol` **resolves in Brave** to your showcase at `/u/nich` — no extension.+- A **pay-by-name handle** — anyone can `POST /api/x402/pay-by-name` with `nich.threews.sol` to send you USDC, or preview the target wallet with the matching GET.+- **On-chain ownership** in your wallet — three.ws set the URL record and transferred custody; it doesn't hold the name.+- A **verified profile** at [/u/nich](/u/).++---++## Troubleshooting++- **`409 no_username` / `409 username_mismatch`** — the label must equal your account username. Set or correct your username, then claim that exact string.+- **Mint button never enables** — availability returned `available: false` (claimed or on-chain owned) or `on_chain_check: "unavailable"` (RPC hiccup). For the latter, retry in a moment; the response is `no-store` precisely so you can.+- **`409 conflict` on mint** — someone claimed or registered the label between your availability check and your click. Pick another label (which must still match your username — in practice this means the name is genuinely taken).+- **`409 no_wallet`** — you passed no `owner_wallet` and have no agent. Create an agent (it provisions a Solana wallet) or link a Solana wallet and pass it as `owner_wallet`.+- **`403 forbidden` on mint** — the `owner_wallet` you passed isn't linked to your account. Link it first; three.ws won't mint into an unlinked wallet.+- **`503 config_missing`** — subdomain minting isn't configured on this deployment (the platform parent key is absent). This is an environment issue, not a request error.+- **`401 unauthorized`** — minting and `mode=send` need a signed-in session or bearer token. The availability check and `mode=prep` preview do not.+- **`/api/sns` says `resolved: false` right after minting** — resolution is cached briefly; the negative cache TTL is short. Wait a few seconds and re-resolve.+- **Pay-by-name `404 not_found`** — the name doesn't resolve. Confirm the exact spelling (`<label>.threews.sol`), or use the GET resolver to see what it points at.+- **`409 recipient_changed` on `mode=send`** — the name now resolves to a different address than the `expected_address` you sent. Re-run the GET preview and confirm the new target before sending.+- **`403 per_tx_exceeded`** — the send exceeds the paying agent's per-transaction USD limit. Lower the amount or raise the agent's limit.++---++## Recap++You claimed a real Solana name and wired it to payments:++- **Claim** ([/threews/claim](/threews/claim)) — type your username, the page checks `GET /api/threews/subdomain?label=…`, and `POST /api/threews/subdomain` mints `<label>.threews.sol` gaslessly, sets its URL record to `/u/<label>`, and transfers ownership to your wallet — all in one transaction.+- **Resolve** — `GET /api/sns?name=<name>.threews.sol` (forward), and the name lands in Brave on your showcase via the URL record.+- **Get paid by name** — `GET /api/x402/pay-by-name?name=…` previews the recipient wallet; `POST` with `mode=prep` returns an unsigned USDC transfer for a browser wallet, or `mode=send` (auth + `agent_id`) has an agent sign and broadcast it, guarded by `expected_address` and a per-tx limit.++One name, three jobs: a browser destination, a verifiable identity, and a USDC pay-by-name handle. For the full SNS surface — agent-attached subdomains, attaching an existing `.sol` you already own, and reverse lookups — see [POST /api/sns-subdomain](/api/sns-subdomain) and the [resolver at /api/sns](/api/sns).++See also:++- [Build a custom skill](/docs/tutorials/custom-skill) — give your named agent new capabilities.+- [Create & edit agent memory](/docs/tutorials/create-and-edit-memory) — make your agent remember to quote in USDC.diff --git a/docs/tutorials/getting-started.md b/docs/tutorials/getting-started.mdnew file mode 100644index 000000000..c78026da8--- /dev/null+++ b/docs/tutorials/getting-started.md@@ -0,0 +1,164 @@+# Getting started: your first hosted agent++By the end of this tutorial you'll have a live 3D AI agent — a character with a body, a personality, and a public URL you can paste into a chat, a tweet, or a website. No code, no 3D software, no wallet. Five minutes, start to share.++This is the easiest entry point on the platform. Everything you do here is editable later, so don't overthink any single choice — the goal is to get something live and shareable.++**Prerequisites:** a modern browser (Chrome, Firefox, or Safari) and an email address. No coding experience, no 3D files, and no crypto required. You'll sign in once, partway through, to save your work.++---++## What you're building++A hosted agent is three things stacked together: a **body** (a 3D avatar), a **brain** (an LLM plus a personality you write), and a **public page** anyone can open.++```+You: pick a body → name it → describe its personality+ ↓+Result: three.ws/@aria → a 3D character that talks, on a page you can share+```++A concrete example. Say you run a small coffee roaster and want a friendly guide on your site:++```+Name: Aria+Personality: "You are Aria, the guide for Bean & Brew coffee roasters.+ You're warm and concise. You answer questions about our+ beans, brewing methods, and shipping. If you don't know+ something, you say so and point people to [email protected]."+Shared at: three.ws/@aria (and embeddable on beanbrew.co)+```++That's the whole loop. Pick a body, give it a voice, share the link.++---++## The three pieces (one minute of concepts)++Before you start, it helps to know the difference between the two core objects on the platform:++| | What it is | The analogy |+|---|---|---|+| **Avatar** | A 3D model — the body, with a rig so it can move | The actor's body |+| **Agent** | An avatar **plus** a brain: an LLM and the personality you write | The character the actor plays |++You'll create an avatar first, then turn it into an agent by giving it a personality. The platform handles all the 3D rendering, the rig, and the animations — you never touch a 3D tool.++For a deeper take on the distinction, see [Agents vs. Avatars](/docs/agents-vs-avatars). To go straight through, just follow the steps below.++---++## Step 1: Open the create flow++Go to **[/create](/create)**. This is the launchpad for every way to make a body.++You'll see a few starting points. For the fastest five-minute path, you have two good choices:++- **Customize a base avatar** (the recommended hero card) — click **Open editor** to sculpt a face, pick outfits, and adjust colors in the browser. Free, no sign-in to start, about a minute.+- **Start with a template** — click **Browse templates** to pick a ready-made character and make it yours. The fastest option at roughly 15 seconds.++If you already have a model, the **Upload your own GLB** card takes any glTF 2.0 / `.glb` file via **Choose file**. There's also **Scan yourself to 3D** (point your camera and hold still) if you'd rather star as your own agent — that one asks you to sign in first.++Pick one. For your first agent, **Start with a template** is the quickest way to reach the finish line; you can always swap the body later without losing the personality.++---++## Step 2: Name it and choose "Agent"++Whichever starting point you picked, you land on the **preview page** at [/create-review](/create-review). Your 3D character renders in the viewer — drag to orbit it, scroll to zoom.++On the right, fill in two things:++1. **Name & handle** — type a name in the field (placeholder: *"Give your avatar a name"*). As you type, a live handle preview shows the public URL your agent will get, like `three.ws/@aria`. There's a **Copy** button next to it once a handle is reserved.+2. **Is this an agent or an item?** — choose **Agent** (described as *"Thinks, talks, remembers — can go on-chain"*). The other option, **Item**, is for static 3D props with no brain — not what you want here.++Picking **Agent** is the choice that gives your character a mind. Don't pick Item.++---++## Step 3: Save it (sign in once)++Click the primary button. Its label depends on whether you're signed in:++- If you're already signed in, it reads **Save to my account**.+- If you're not, it reads **Sign in to save** — clicking it sends you to sign-in and brings you right back to this exact preview afterward, so you don't lose your work.++> The preview lives only in your browser until you save. That's why signing in is required at this step: it claims your handle and creates the agent record on the platform. Use the email sign-in option — no wallet needed. (Wondering about the crypto stuff? See [Do I need crypto?](/docs/do-i-need-crypto) — short answer: not for this.)++After it saves, you land on a short **"Your agent is ready"** screen with next steps. The first one — **Chat with your agent** — is where the personality gets set. Click it.++---++## Step 4: Give it a personality++**Chat with your agent** opens your agent in the app at `/app?agent=<your-agent-id>`. Here you can talk to it directly and shape how it behaves.++To write its personality properly, open the agent's editor: from your **[dashboard](/dashboard)**, find the agent and open **Edit** (the editor lives at `/agent/<id>/edit`). It's organized into tabs across the top — **Persona**, **Outfit**, **Voice**, **Knowledge**, **Skills**, **Publish**, **Embed**, and more.++Two fields define who your agent is:++- **Persona tab → Description** — a short, public-facing summary of the character (up to 500 characters). Click **Save** when you're done.+- **Publish tab → Agent Profile (system prompt)** — the real instructions the agent follows, in plain language (the placeholder shows *"You are a professor of computer science…"*). This is the heart of the personality. Write it in the second person, like you're briefing an employee:++```+You are Aria, the guide for Bean & Brew coffee roasters.+You're warm, concise, and never pushy. You answer questions about our+single-origin beans, brewing methods, and shipping. When you don't know+something, say so plainly and point the person to [email protected].+Keep replies to two or three sentences unless asked for detail.+```++The clearer and more specific you are, the better the agent behaves. State its name, its job, its tone, and what to do when it's unsure. You can also set a **Greeting (demo first message)** on the Publish tab so visitors get a warm opening line.++When you're happy, click **Publish to Marketplace** on the Publish tab to make the agent's public page live.++---++## Step 5: Share the URL++Your agent now has a public page at **`three.ws/agents/<id>`**, and a friendly handle URL like **`three.ws/@aria`**. Open it — anyone can talk to your agent there in 3D.++On the public agent page you'll find a **Share** button to copy the link, and an **EMBED THIS AGENT** section with three ready-to-copy snippets:++- **Web component** — a `<script>` tag plus an element you drop into any HTML page.+- **Iframe** — a self-contained frame for sites where you can't add scripts.+- **Direct link** — just the URL, for chats, emails, or social posts.++Each has its own **Copy** button. For sharing in a message, copy the **Direct link**. To put the live agent on your own website, copy the **Web component** snippet and paste it into your page — that's the whole integration.++That's it. You created a body, gave it a brain, and shipped a shareable URL.++---++## Troubleshooting++- **The Save button says "Sign in to save" and I lost my preview.** You didn't — sign-in returns you to the same preview and resumes the save automatically. Finish signing in, and the button becomes **Save to my account**.+- **My 3D model doesn't appear in the preview.** Orbit and zoom first (drag / scroll) in case it loaded off-camera. If it still doesn't show, go back to [/create](/create) and pick a template instead of uploading — templates are guaranteed to render.+- **I uploaded a GLB and it was rejected.** The uploader only accepts valid `.glb` (glTF 2.0 binary) files. Re-export as `.glb`, or skip the upload and use a template for now.+- **I picked "Item" by mistake.** Items have no brain. Start over from [/create](/create) and choose **Agent** on the preview page — or, if you already saved it, open the agent editor and promote it.+- **The agent replies generically / ignores its personality.** The personality lives in **Publish → Agent Profile (system prompt)**, not just the Description. Make it specific (name, role, tone, fallback behavior), click **Publish to Marketplace**, then start a fresh chat to test.+- **"Sign in to save" but I don't want a wallet.** You don't need one. Use the email sign-in option — wallets are only for the optional on-chain step, which this tutorial skips entirely.+- **I hit an avatar limit.** The free plan caps how many avatars you can keep. Delete one you don't need from the [dashboard](/dashboard), then create the new one.++---++## Recap++You shipped a hosted agent in five minutes, no code:++1. **[/create](/create)** — picked a body (template, in-browser editor, upload, or selfie scan).+2. **[/create-review](/create-review)** — named it, chose **Agent**, and clicked **Save to my account** (signing in once).+3. **Chat with your agent** — opened it in the app, then the **Edit** view.+4. **Persona → Description** and **Publish → Agent Profile (system prompt)** — wrote the personality and clicked **Publish to Marketplace**.+5. **`three.ws/@your-handle`** — shared the public URL, or copied an **Embed** snippet to put it on your own site.++Everything is editable forever — swap the body, rewrite the prompt, add capabilities — without breaking the URL you shared.++**See also**++- [Make your first agent](/docs/make-your-agent) — the same path with extra screenshots and context.+- [Agents vs. Avatars](/docs/agents-vs-avatars) — the body-vs-brain distinction in depth.+- [Embed in 30 seconds](/docs/tutorials/embed-in-30-seconds) — put your agent on any web page with one line.+- [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) — teach your agent durable facts it carries between sessions.+- [Build a custom skill](/docs/tutorials/custom-skill) — give your agent a new capability, like calling a live API.+- [Do I need crypto?](/docs/do-i-need-crypto) — honest answers on wallets and the optional on-chain step.diff --git a/docs/tutorials/selfie-to-avatar.md b/docs/tutorials/selfie-to-avatar.mdnew file mode 100644index 000000000..62d387da1--- /dev/null+++ b/docs/tutorials/selfie-to-avatar.md@@ -0,0 +1,229 @@+# Turn a Selfie into a Rigged 3D Avatar++Take one front-facing photo and walk away with a rigged 3D avatar that looks like you — one you can drop onto an agent, animate, and embed anywhere. The Scanner handles capture, reconstruction, and auto-rigging end to end; you point a camera and name the result.++**Prerequisites:** a device with a camera (phone or laptop) or a clear front-facing photo to upload. No code, no 3D experience, and no account needed to start a scan. You'll want a [three.ws account](/create) to save the avatar and put it on an agent.++---++## What you're building++```+You: one front-facing selfie (optionally + left and right angles)+ ↓ [reconstruct → texture → auto-rig]+Result: a rigged GLB that looks like you — animation-ready,+ attached to an agent, downloadable for any engine+```++A flat photo has no geometry. The Scanner reconstructs a 3D head-and-body mesh, wraps your real face onto it as a texture, then **auto-rigs the mesh with a humanoid skeleton** so it can move — idle, walk, gesture — without you touching a rig. The output is a standard glTF 2.0 binary (`.glb`) that works in three.ws and in external tools (VRChat, Spatial, Unity, Unreal) alike.++This tutorial covers the full path: **capture → generate → auto-rig → put it on an agent**.++---++## How the flow works (one minute of theory)++The Scanner is one pipeline reachable two ways:++- **[/scan](/scan)** is the front door. It immediately forwards to **[/create/selfie](/create/selfie)**, which is the full capture experience (including the option to bring your own reconstruction key). Either URL gets you to the same place — `/scan` is the memorable one to share.+- **[/create/selfie](/create/selfie)** is where capture, the build progress, and the finished avatar all live.++Under the hood the page ([src/selfie-capture.js](../src/selfie-capture.js)) collects your photos, downscales them in your browser, and hands them to the pipeline ([src/selfie-pipeline.js](../src/selfie-pipeline.js)), which submits the job and polls for progress. There are exactly two calls:++1. `POST /api/avatars/reconstruct` — submit the photos, get back a `jobId`.+2. `GET /api/avatars/regenerate-status?jobId=…` — poll until the job reports `done`.++The job moves through visible stages — reconstructing the mesh, building geometry and textures, **auto-rigging the skeleton and skinning** — then returns the finished avatar's id. You never call the rig step yourself; it's part of the job. This is the platform-wide rule: every avatar three.ws creates is auto-rigged so it can animate. (For the rig internals, see [Avatar Creation](../avatar-creation.md).)++---++## Step 1: Take or pick a good photo++Result quality is mostly decided here. The face the engine can see clearly is the face you get back.++Five rules for the front-facing shot:++1. **Face the camera directly** — no extreme angles, chin level.+2. **Good, even lighting** — indirect daylight is ideal; avoid harsh shadows or backlighting.+3. **Remove anything covering your face** — sunglasses, masks, a hat brim over the eyes.+4. **Keep hair off your forehead and jawline** where you can — the engine needs your face outline.+5. **Plain background** helps the reconstruction isolate you.++You don't need a studio. A normal selfie in a well-lit room is plenty.++**Accepted formats:** JPEG, PNG, WebP, and HEIC/HEIF (iPhone photos work as-is). Photos are downscaled in your browser to a maximum of 1024px before upload — your original file never sits on disk, and only the generated avatar texture is kept.++---++## Step 2: Open the Scanner and add your photo++Go to **[/scan](/scan)** (it lands you on [/create/selfie](/create/selfie)).++You'll see one required slot: **Add a front-facing photo**. Two ways to fill it:++- **Use camera** — opens your camera in the browser with live face guides. Hold still inside the oval; the page checks framing, lighting, blur, and head angle and captures when it's a good frame.+- **Upload photo** — pick an existing image from your device.++If your browser or device can't open the camera (common on non-HTTPS connections and some desktop browsers), the camera option is disabled automatically — use **Upload** instead.++That one front-facing photo is all you need to build an avatar. The submit button stays disabled (showing "Add a photo to start") until a frontal photo is in place.++---++## Step 3: Add side angles for sharper geometry (optional)++Open the **Add side angles** disclosure to reveal two more slots:++- **Left** — turn your head about 45° to the left.+- **Right** — turn your head about 45° to the right.++Each extra angle is geometry the engine doesn't have to guess, so the sides and back of your head come out noticeably crisper. The trade-off is time: the submit button updates to reflect it — roughly **~90s** for one photo, **~120s** when you add angles.++Keep the same lighting and the same way-up across all three shots. Side angles are optional; skip them if you just want a fast result.++---++## Step 4: Choose style and body type++Two quick choices below the photos:++**Style**++- **Photoreal** — likeness-first; closest to how you actually look. (This is the default.)+- **Stylized** — cleaner, cartoon-leaning; good for streaming and games.++**Body type**++- **Masc** (default) or **Femme** — this selects the body proportions the rig is built on.++Pick the pair that fits how you'll use the avatar. You can always run another scan with different settings later — nothing here is permanent.++---++## Step 5: Build the avatar++Click the build button (it reads **Build my avatar · ~90s**, or the high-fidelity variant if you added angles).++What happens next:++- If you're not signed in, you'll be sent to sign in and returned to the Scanner — saving an avatar requires an account.+- The page submits your photos and switches to the build view: **"Building your avatar… This usually takes 1–2 minutes. Don't close this tab."**+- You'll see the pipeline narrate real progress as it works:++```+Queued — waiting for a reconstruction slot…+Generating 3D mesh from your photo…+Building geometry and textures…+Auto-rigging skeleton and skinning…+Finishing avatar…+```++That **"Auto-rigging skeleton and skinning…"** line is the step that makes the avatar movable — the reconstruction produces a mesh, and the pipeline fits a humanoid skeleton to it and binds the skin so animation clips can drive it. You don't trigger it; it's part of every build.++The build is resilient: the job id is held in your session, so if you reload mid-build the page resumes polling the same job instead of starting over. If the engine is busy you may see "Still working — this one is taking a bit longer…"; that's expected on the longer tail, not an error.++---++## Step 6: Why "auto-rigged" matters++A reconstructed mesh that isn't rigged is a statue — it can be viewed but not animated. That's why rigging is built into the create path, not an optional extra.++Across three.ws, **every avatar that gets created auto-rigs so it can move.** For the selfie flow the rig is fitted inside the reconstruction job (the step you watched in Step 5). For avatars that arrive already built — an uploaded GLB or a forged model — the same guarantee holds: if the mesh comes in static, the platform fires an auto-rig pass in the background and swaps the rigged version in place, with a sweep cron as a safety net so nothing gets stuck half-rigged. The mechanism differs; the outcome is identical: a humanoid you can animate.++Once rigged, the avatar drives the shared clip library. Bone names from common conventions (Mixamo, VRM, Unreal, and more) are mapped to a canonical skeleton, and idle/walk/gesture clips retarget onto it automatically — legs included. The practical upshot: the avatar you just built will move the moment you open it in the [Animation Studio](/pose), with no extra rigging work from you.++---++## Step 7: Name it and open your avatar++When the build finishes you land on the done view: **"Your avatar is ready."**++- It renders in a live 3D preview — drag to spin it and check the result. Look at the sides and back; if you skipped angles, that's where the engine had the least to work with.+- Give it a name in the **Name your avatar** field (up to 60 characters).+- Click **Open my avatar →** to go to your avatar's page at `/avatars/<id>`.++From the done view you can also:++- **Customize in editor** — opens the avatar in the editor (`/avatars/<id>/edit`) to adjust appearance, clothing, and accessories.+- **List on marketplace** — flips the avatar to public and takes you to its marketplace listing.+- **Not quite right — try again** — resets the form so you can rescan with a better photo or different settings.++Whatever you choose, the avatar is already saved to your account as a rigged GLB.++---++## Step 8: Put the avatar on an agent++An avatar is a body; an agent is the brain that lives in it. Creating an avatar already wires up an agent for you — the two are tied together so the avatar shows up, animates, and can transact.++You have two paths:++**It's already done.** When the avatar is saved, three.ws attaches it to an agent automatically: it links the avatar to one of your agents that doesn't yet have a body, and if you don't have one, it creates a default agent and gives it this avatar. Open **Open my avatar →** and the agent behind it is provisioned and ready.++**Reassign it deliberately.** If you want this avatar to become the face of a *specific* existing agent, attach it explicitly:++```js+await fetch('/api/onboarding/link-avatar', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ avatarId: 'your-avatar-uuid', // the id from /avatars/<id>+ force: true, // replace the agent's current avatar+ }),+});+// → { agent: { id, avatar_id, updated_at } }+```++`force: true` overrides an avatar the agent already has. Omit it (or set `false`) to only attach when the agent has no avatar yet. Either way the call is owner-scoped — you can only attach avatars to agents you own.++Once linked, give the agent a [personality](/tutorials/agent-personality) and a [brain](/tutorials/connect-ai-brain), then [share it](/tutorials/share-your-agent) or embed it on a site.++---++## Step 9: Use the avatar everywhere++Because the output is a clean, rigged glTF 2.0 file, it isn't locked to three.ws:++- **Animate it** in the [Animation Studio](/pose) — load it, browse the clip gallery, and retarget motion onto it live. It works because it's rigged.+- **Download the GLB** from the avatar page to use it in Unity, Unreal, Blender, or any glTF-aware tool.+- **Embed it** on a website with the web component — see [Embed in 30 seconds](/tutorials/embed-in-30-seconds).+- **Refine the look** with [Customize your agent's appearance](/tutorials/customize-appearance) — clothing, accessories, and more layer on without re-rigging.++---++## Troubleshooting++| Symptom | Likely cause | Fix |+|---|---|---|+| "Add a photo to start" won't go away | No frontal photo in the required slot | The front-facing slot is mandatory; side angles alone aren't enough |+| The **Use camera** option is missing or disabled | Browser/device can't open the camera (often non-HTTPS, or no camera) | Use **Upload photo** instead, or open the page in Safari/Chrome on a device with a camera |+| Build failed: "Try clearer photos in better light" | Blurry photo, no detectable face, or harsh lighting | Reshoot per Step 1 — face the camera, even light, nothing covering your face |+| Sides or back of the head look wrong | Only a frontal photo was provided | Add **Left** and **Right** angles (Step 3) and rebuild |+| "Photos are too large" | The upload exceeded the size limit | Photos are downscaled to 1024px in-browser; retry, or use a smaller source image |+| Asked to sign in mid-build | Saving an avatar needs an account | Sign in when prompted — you're returned to the Scanner and the build continues |+| "Too many requests" / rate-limited | Per-visitor cooldown after repeated attempts | Wait about a minute and try again |+| The reload during a build started a fresh scan | Rare; the pending job id wasn't found | The build resumes automatically when the job id is in your session — re-open [/create/selfie](/create/selfie) and let it poll |+| Asked for a reconstruction API key | This deployment runs in bring-your-own-key mode | Paste a key from the supported provider in the form shown; it's stored for your session only |++---++## Recap++You turned a single selfie into a rigged, agent-ready 3D avatar:++- **Capture** — one front-facing photo at [/scan](/scan) → [/create/selfie](/create/selfie); optional left/right angles sharpen the geometry.+- **Choose** — Photoreal vs Stylized, Masc vs Femme body type.+- **Generate** — `POST /api/avatars/reconstruct` builds the mesh and texture; the page polls `regenerate-status` and shows real progress.+- **Auto-rig** — the build fits a humanoid skeleton and skins the mesh so it can animate; this happens for every avatar three.ws creates, no manual step.+- **Attach** — the avatar is linked to an agent automatically, or attach it to a specific agent with `POST /api/onboarding/link-avatar`.++The result is a standard `.glb` that animates in the [Animation Studio](/pose), embeds on the web, and works in external engines — a real likeness of you, ready to move.++### See also++- [Turn Photos into a 3D Model](/tutorials/image-to-3d) — reconstruct an *object* (not a person) from a few photos in the Forge.+- [Animate your avatar](/tutorials/animate-your-avatar) — apply and tune motion on the rigged avatar you just built.+- [Avatar Creation](../avatar-creation.md) — the full reference: every creation path, rig requirements, and accessories.+- [Customize your agent's appearance](/tutorials/customize-appearance) — clothing, accessories, and styling on top of your avatar.+- [Give your agent a personality](/tutorials/agent-personality) — turn the body into a character.diff --git a/prompts/avatar-autorig/05-coverage-gaps.md b/prompts/avatar-autorig/05-coverage-gaps.mdnew file mode 100644index 000000000..6bcc25122--- /dev/null+++ b/prompts/avatar-autorig/05-coverage-gaps.md@@ -0,0 +1,156 @@+# Close auto-rig coverage gaps: MCP `save_avatar`, fork mid-rig, manual/auto double-rig++> One-line: "Paste this into a fresh Claude Code chat at the repo root and execute it fully."++## Operating rules (non-negotiable)+- You are building **three.ws** — a platform meant to compete with the best in the world. Senior-engineer bar: no shortcuts, ship complete polished work.+- **No mocks, no fake data, no placeholders, no TODO comments, no stub functions, no `throw new Error("not implemented")`, no fake setTimeout loading.** Real APIs, real endpoints, real wiring only. If credentials are missing, locate them in `.env` / `vercel env`, else proceed with the real integration.+- **$THREE is the ONLY coin** this platform may reference. Contract: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never name, import, hardcode, or recommend any other token anywhere.+- **Concurrent agents share this worktree.** Stage explicit paths only (never `git add -A`/`git add .`); re-check `git status` and `git diff --staged` immediately before any commit.+- **Changelog:** every user-visible change gets an entry in `data/changelog.json` (date, holder-readable title + summary, tags from feature|improvement|fix|sdk|infra|docs|security); then run `npm run build:pages`. Internal-only chores get no entry.+- **Push to BOTH remotes when asked to push:** `git push threeD main` AND `git push threews main`. NEVER pull/fetch/merge from `threeD`; pulls come from `threews` only.+- **Trap:** `npx vercel build` overwrites `api/*.js` with esbuild bundles — before committing an `api/` diff, check `head -1` for `__defProp`/`createRequire` and `git restore -- api/ public/` if contaminated.+- **Definition of done:** code wired + reachable; every state designed; no console errors/warnings from your code; real API calls verified; existing tests pass (`npm test`); `git diff` self-reviewed; you'd demo it proudly to senior engineers.+- Read `CLAUDE.md` and `STRUCTURE.md` first. Use TodoWrite for 3+ step tasks. Keep communication short.++## Context++This is part 5 of a 9-part auto-rig hardening program in `prompts/avatar-autorig/`. The platform auto-rigs static meshes into animation-ready (skeleton-bearing) avatars so every 3D agent can walk, wave, and emote. The HTTP ingest path (`api/avatars/from-forge.js`) and the on-create library (`api/_lib/auto-rig.js`) already do this correctly: after `createAvatar`, they call `provisionAvatarAgent` and `maybeAutoRigAvatar`.++But several **creation and duplication paths do not run the same code**, so an avatar born through them never gets an agent provisioned and never has an auto-rig job submitted — meaning the auto-rig cron in part 06 has nothing to rescue. This part closes those gaps so EVERY way an avatar can be born or copied ends up first-class and animation-ready, consistent with `from-forge.js`.++The four gaps (all confirmed by reading the code — re-confirm each before changing it):+1. The MCP `save_avatar` tool persists a GLB but never provisions an agent and never submits a rig job.+2. `fork.js` copies tags and `forked_from` but drops the source's rig `source_meta`, so the fork misclassifies (and can carry a stale `rigged` tag onto a row with no rig signal).+3. `handleRegenerate` (manual rig) has no in-flight dedupe, so a user clicking "Animate" while an auto-rig job is already running races two rigged GLBs onto the same row.+4. `from-forge.js` records `is_rigged` as `null` (unknown) when a forged mesh is actually static, so `classifyRig` can't label it "static".++> NOTE — keystone dependency: sibling `01-sibling-materialization.md` changes auto-rig to materialize a rigged SIBLING avatar (`parent_avatar_id` = the static source) rather than swapping the GLB in place on the same row. If 01 has already landed when you start, mirror its sibling model in the wiring you add here (the agent is provisioned for the source row; the rig job's completion produces the sibling). If 01 has NOT landed, wire against today's in-place behavior in `api/_lib/auto-rig.js`. Read `api/_lib/auto-rig.js` first to see which model is live, and match it — do not invent a third behavior.++## Background findings (confirmed by reading the code — re-confirm before editing)++- **`api/_mcp3d/tools/studio.js` — `save_avatar` tool (declared ~line 1632, handler ~1678, `createAvatar` ~1741-1763).** The import block (~lines 18-44) imports `createAvatar, storageKeyFor` from `../../_lib/avatars.js`, `putObject` from `r2.js`, `inspectGlb`/`isValidGlbHeader` from `glb-inspect.js` — but **NOT** `provisionAvatarAgent` (`../../_lib/avatar-agent.js`) and **NOT** `maybeAutoRigAvatar` (`../../_lib/auto-rig.js`). After `createAvatar` the handler returns immediately (~1765-1783). No agent is provisioned and no rig job is ever submitted. Compare to the HTTP twin `from-forge.js` which calls both. Also note: `save_avatar` builds `source_meta.is_rigged: info.isRigged ?? null` (~line 1754) — same `null`-on-static bug as gap 4.++- **`api/avatars/from-forge.js` — `is_rigged` provenance (line 143).** `is_rigged: rigged || info.isRigged || null`. When the GLB is genuinely static (`rigged === false`, `info.isRigged === false`), this evaluates to `null` ("unknown"), not `false` ("static"). `classifyRig` (src/shared/rig-classify.js, lines 36-42) only returns `static` when `flag === false`; a `null` flag falls through to `unknown`, so the UI offers to rig but never shows the "Static" badge, and the rigged/static gallery filter in `api/_lib/avatars.js` (~line 285) treats it as un-inspected. The `rigInfo` passed to `maybeAutoRigAvatar` (line 167) correctly uses `info.isRigged === true`, so the rig job is still submitted — only the stored classification is wrong.++- **`api/avatars/fork.js` — fork drops rig provenance (lines 104-122).** The fork's `source_meta` is `{ forked_from }` only (line 112); the source row's rig signal (`is_rigged`, `skeleton_joint_count`, `auto_rigged`) is never carried over. Worse, `tags: src.tags || []` (line 116) copies the source's tags verbatim — if the source carries a `rigged` tag (stamped by `finalizeAutoRigStage`, auto-rig.js line 215) but the copied GLB's `source_meta` has no rig signal, the fork shows a `rigged` tag on a row `classifyRig` calls `unknown`. The fork also never submits an auto-rig job, so forking a still-static avatar yields a static fork with an idle agent.++- **`api/avatars/_actions.js` — `handleRegenerate` no in-flight dedupe (lines 367-429).** It loads the source row (line 375), gets the provider, submits, and inserts a new `avatar_regen_jobs` row (line 416) — with **no** check for an existing in-flight job on the same `source_avatar_id`. `maybeAutoRigAvatar` (auto-rig.js lines 108-116) DOES guard against this with an `inFlight` query before submitting; the manual path does not. A user opening the "Animate" tab (`src/avatar-rig.js` `startRigging`, lines 84-110) while the on-create auto-rig job is still queued/running fires a second `rerig`, racing two results onto one row.++- **`src/avatar-rig.js` (manual rig panel).** `startRigging` POSTs `/api/avatars/regenerate { sourceAvatarId, mode: 'rerig' }` and on `!res.ok` only special-cases `501` (lines 95-102). It does not handle `409`; today a 409 would surface the generic message. It must instead attach to the returned existing `jobId` and resume polling (`pollUntilDone`, line 112).++## Scope — in / out++**In scope:**+- Wire `provisionAvatarAgent` + `maybeAutoRigAvatar` into MCP `save_avatar`, mirroring `from-forge.js`.+- Carry rig `source_meta` into forks; auto-rig still-static forks; never copy a `rigged` tag onto a row with no rig signal.+- Add in-flight dedupe (409 + existing `jobId`) to `handleRegenerate`; teach `src/avatar-rig.js` to attach on 409.+- Fix `from-forge.js` and `save_avatar` `is_rigged` provenance: `false` when inspected-and-static, `null` only when genuinely uninspected.+- Tests for each path.++**Out of scope:** the sibling-materialization redesign (01), the cron rescue + backfill (06), SSRF guard internals (03), cost/consent gates (04), the completion state machine (02), observability/events plumbing (08). Reuse those modules; do not reimplement them.++## Key files & entry points++- `api/_mcp3d/tools/studio.js` — MCP `save_avatar` tool (gap 1 + 4). Imports ~18-44; handler ~1678-1784.+- `api/avatars/from-forge.js` — the HTTP twin that already wires both (the reference pattern); `is_rigged` bug at line 143.+- `api/avatars/fork.js` — fork endpoint (gap 2); `source_meta`/tags at lines 96-122.+- `api/avatars/_actions.js` — `handleRegenerate` (gap 3) at lines 367-429.+- `src/avatar-rig.js` — manual rig panel; `startRigging` 84-110, `pollUntilDone` 112-147.+- `api/_lib/auto-rig.js` — `maybeAutoRigAvatar` (reuse), `rigInfoIsRigged`, the canonical in-flight query (lines 108-116) to mirror in `handleRegenerate`.+- `api/_lib/avatar-agent.js` — `provisionAvatarAgent({ userId, avatarId, avatarName })` (reuse).+- `src/shared/rig-classify.js` — `classifyRig` contract that consumes `source_meta.is_rigged`.+- `api/_lib/avatars.js` — `createAvatar`; `searchPublicAvatars` rig SQL filter (~266-307).++## Requirements++Each requirement has an acceptance criterion. Build all of them.++1. **MCP `save_avatar` provisions an agent and submits a rig job.**+ In `api/_mcp3d/tools/studio.js`, add imports for `provisionAvatarAgent` (`../../_lib/avatar-agent.js`) and `maybeAutoRigAvatar` (`../../_lib/auto-rig.js`). After `createAvatar` (~line 1763) and before building the response, mirror `from-forge.js` lines 154-170: schedule `provisionAvatarAgent({ userId, avatarId, avatarName })` and `maybeAutoRigAvatar({ userId, avatar, rigInfo: { is_rigged: info.isRigged === true, skeleton_joint_count: info.skeletonJointCount ?? null }, source: 'studio' })`. Both are best-effort and must NOT block or fail the tool response. Since the MCP handler is not a request/response wrapper with `queueMicrotask` lifetime guarantees, `await` both (each already swallows its own errors — `maybeAutoRigAvatar` never throws; wrap the `provisionAvatarAgent` call in a try/catch that logs and continues) so the work is not lost when the lambda freezes.+ *Acceptance:* Calling `save_avatar` with a static GLB inserts one `avatar_regen_jobs` row (`mode='rerig'`, `params.auto_rig=true`, `params.source='studio'`) for the new avatar AND creates an `agent_identities` row for it — verified by the new test and by `grep` showing both calls present. Calling it with an already-rigged GLB inserts NO rig job (`maybeAutoRigAvatar` returns `already_rigged`).++2. **`fork.js` carries rig `source_meta` into the fork.**+ When building the fork's `source_meta` (line 112), merge the source row's rig signal so `classifyRig` is correct. Select `a.source_meta` in the source query (lines 48-56) and carry `is_rigged`, `skeleton_joint_count`, `auto_rigged` (only the keys that exist on the source) into the new `source_meta` alongside `forked_from`. Do NOT carry `unrigged_storage_key` / `rig_job_id` (those point at the source owner's objects).+ *Acceptance:* Forking a rigged avatar produces a fork whose `classifyRig().category === 'rigged'`; forking a static avatar produces `'static'`; forking an uninspected avatar produces `'unknown'`. Covered by the new test.++3. **Forking a still-static avatar kicks auto-rig for the fork.**+ After the fork row + its agent are created, call `maybeAutoRigAvatar({ userId: auth.userId, avatar, rigInfo: { is_rigged: <source rigged>, skeleton_joint_count: <source joints> }, source: 'fork' })` (best-effort, after `recordEvent`). When the source is rigged this no-ops (`already_rigged`); when static it submits a `rerig` job so the fork becomes animation-ready like every other creation path. Use the carried rig signal from requirement 2 to compute `rigInfo` — do NOT re-fetch/re-inspect the GLB (the fork is a byte-identical copy).+ *Acceptance:* Forking a static avatar (with a rerig model configured) inserts one `rerig`/`auto_rig` job for the FORK's id; forking a rigged avatar inserts none. Covered by the new test.++4. **Never copy a `rigged` tag onto a fork with no rig signal.**+ When the source's carried rig signal is NOT rigged (`rigInfoIsRigged` from `auto-rig.js` returns false on the carried signal), strip any `rigged` tag from the copied `tags` array before insert, so a fork never shows a `rigged` badge it can't back up. Keep all other tags. Conversely, when the carried signal IS rigged, preserve the `rigged` tag.+ *Acceptance:* Forking a static-but-`rigged`-tagged source yields a fork whose `tags` excludes `rigged`. Covered by the new test.++5. **`handleRegenerate` dedupes in-flight rerig jobs (409 + existing jobId).**+ In `api/avatars/_actions.js`, before submitting (after the source-row load at line 376, gated to `mode === 'rerig'`), run an in-flight query mirroring `auto-rig.js` lines 108-116 — but match ANY in-flight `rerig` job for the avatar (auto OR manual), i.e. `where source_avatar_id = ${id} and mode = 'rerig' and status in ('queued','running','rigging')`. If one exists, return `409` with body `{ ok: false, error: 'rig_in_flight', error_description: '…', jobId: <existing job_id>, status: <existing status> }`. Only dedupe `rerig`; other modes (remesh/retex/restyle/reconstruct) are unaffected.+ *Acceptance:* Two back-to-back `rerig` POSTs for the same avatar: the first returns `202` with a new jobId, the second returns `409` carrying the SAME jobId. A `remesh` POST is never deduped. Covered by the new test.++6. **Manual rig panel attaches to the in-flight job on 409.**+ In `src/avatar-rig.js` `startRigging` (lines 95-110), when `res.status === 409` and `body.jobId` is present, do not show an error: set `jobId = body.jobId`, transition to the `rigging` phase with a message like "Already rigging this avatar — attaching to the existing job…", and call `pollUntilDone(jobId, Date.now())` so the panel rides the existing job to completion. Keep the existing 501 and generic error handling for all other non-OK responses.+ *Acceptance:* With an auto-rig job already queued for an avatar, opening the Animate tab and clicking rig attaches to that job (no duplicate submission, no error toast) and reaches the rigged result. Manually verified in the browser plus a unit test of the 409 branch if the panel logic is testable in isolation.++7. **Correct `is_rigged` provenance in `from-forge.js` and `save_avatar`.**+ In both, set `source_meta.is_rigged` to: `true` when rigged (forge `rigged` flag OR `info.isRigged === true`); `false` when the GLB was successfully inspected and confirmed static (`info` is a real inspection result AND `info.isRigged === false`); `null` only when inspection did not yield a rig verdict (`info.isRigged` is `undefined`/missing — e.g. `inspectGlb` returned `{}`). Implement as a small local helper, e.g. `resolveRiggedFlag(forgeRigged, info)`, used in both files (or duplicated — they live in different module trees; a 5-line pure function in each is acceptable, do not create a shared import just for this unless one already fits). For `save_avatar` there is no `rigged` input arg, so `forgeRigged` is effectively `false`.+ *Acceptance:* A from-forge save of a confirmed-static GLB stores `source_meta.is_rigged === false` (not `null`), and `classifyRig` returns `'static'`. A save where `inspectGlb` returned `{}` stores `null` and classifies `'unknown'`. Covered by the new test.++8. **Changelog entry.**+ Add one `data/changelog.json` entry (tag `fix` or `improvement`) in holder-readable language — e.g. "Avatars saved from the studio, forked, or generated by agents now reliably become animation-ready, and re-rigging an avatar that's already rigging no longer starts a duplicate job." Run `npm run build:pages`.+ *Acceptance:* `npm run build:pages` succeeds and regenerates `CHANGELOG.md` / `public/changelog.*` with the new entry.++## Implementation notes++- **Mirror `from-forge.js`, do not diverge.** It is the canonical wiring. The order is: `createAvatar` → schedule `provisionAvatarAgent` → schedule `maybeAutoRigAvatar` → `recordEvent` → respond. Keep that order so behavior is identical across the HTTP and MCP twins.+- **`maybeAutoRigAvatar` is self-guarding and never throws** (auto-rig.js lines 85-147): it already checks `rigInfoIsRigged`, provider availability (`supportsMode('rerig')`), and its own in-flight dedupe. You do not need to re-check those at the call sites — just pass an accurate `rigInfo`.+- **`rigInfoIsRigged(rigInfo)`** (exported from `auto-rig.js`, lines 41-46) is the exact predicate to reuse for requirement 4's tag-stripping decision — import it rather than re-deriving the rigged test.+- **MCP handler lifetime:** unlike the `wrap()`-ed HTTP handlers that can lean on `queueMicrotask`, the MCP tool returns a value the transport serializes; background microtasks may be cut off when the function returns and the lambda freezes. `await` the provisioning/rig calls. They are fast (they only submit a job / insert a row, not wait for rigging to finish).+- **Fork rig signal source:** read it from the row you already `select` — add `a.source_meta` to the fork's source query (it currently selects `appearance`, `model_category`, etc. but you must confirm `source_meta` is included; add it if not). Compute `{ is_rigged, skeleton_joint_count }` from `src.source_meta` for the `maybeAutoRigAvatar` call.+- **Dedupe scope:** the auto-rig in-flight guard filters on `(params->>'auto_rig') = 'true'`; the manual `handleRegenerate` guard must NOT include that filter — it must catch BOTH auto and manual in-flight rerigs (a manual rig should also block a second manual rig, and should attach to an in-flight auto-rig). Match only on `source_avatar_id`, `mode='rerig'`, and `status`.+- **Status values:** the in-flight statuses are `'queued','running','rigging'` (see auto-rig.js line 113). Use the same set.+- **Do not log secrets.** Provisioning/rig failures log `err?.message` only, as the existing code does.++## Verification++```bash+# Confirm the wiring is present (no longer missing)+grep -n "provisionAvatarAgent\|maybeAutoRigAvatar" api/_mcp3d/tools/studio.js # both must appear+grep -n "rig_in_flight\|source_avatar_id = \|status in ('queued'" api/avatars/_actions.js+grep -n "source_meta\|maybeAutoRigAvatar\|rigInfoIsRigged" api/avatars/fork.js++# Guard against the esbuild-bundle trap before any commit+head -1 api/avatars/fork.js api/avatars/_actions.js api/_mcp3d/tools/studio.js # must NOT be __defProp/createRequire++# Tests+npm test # full suite stays green+npm test -- fork # the new fork rig-provenance + auto-rig + tag tests+npm test -- regenerate # the new in-flight dedupe test+npm test -- save_avatar # or the studio tool test file you add to++# Changelog+npm run build:pages # must succeed and validate the new entry+```++Manual checks:+- In a browser, open an avatar's editor "Animate" tab while an auto-rig job is in flight for it (e.g. right after a from-forge/studio save of a static GLB). Clicking rig must attach to the existing job (no second job in `avatar_regen_jobs`, no error toast) and reach the rigged result. Verify in DevTools Network: the `/api/avatars/regenerate` call returns `409` with a `jobId`, then `/api/avatars/regenerate-status` polls that same id.+- Fork a static avatar that carries a `rigged` tag; confirm the fork's badge does not show "Rigged" and a `rerig` job exists for the fork.+- Fork a rigged avatar; confirm the fork shows "Rigged", carries the rig `source_meta`, and NO rerig job was submitted.+- Confirm no new console errors/warnings from your code.++## Definition of done++- [ ] `save_avatar` imports and calls `provisionAvatarAgent` + `maybeAutoRigAvatar`, mirroring `from-forge.js`; verified by grep + test.+- [ ] `fork.js` carries rig `source_meta`, auto-rigs still-static forks, and never copies a `rigged` tag onto an unrigged fork.+- [ ] `handleRegenerate` returns `409` + existing `jobId` for an in-flight `rerig`; `remesh`/others unaffected.+- [ ] `src/avatar-rig.js` attaches to the in-flight job on `409` instead of erroring.+- [ ] `from-forge.js` and `save_avatar` store `is_rigged` as `false` (inspected-static) / `null` (uninspected) / `true` (rigged) correctly.+- [ ] New tests cover all five paths and pass; `npm test` is fully green.+- [ ] Changelog entry added; `npm run build:pages` succeeds.+- [ ] `head -1` of every changed `api/*.js` is real source (not an esbuild bundle); `git diff` self-reviewed; staged by explicit path.+- [ ] No console errors/warnings from your code; you'd demo this to senior engineers.++## Out of scope / follow-ups++- **Sibling materialization** (`01-sibling-materialization.md`): if not yet landed, this prompt wires against the live in-place model. When 01 lands, re-confirm these call sites still produce a sibling correctly — no rework expected since they only submit jobs.+- **Cron rescue + rig cache/backfill** (`06-rig-cache-and-backfill.md`): the jobs these paths now submit are what the cron rescues; backfilling avatars created before this fix lives there.+- **Cost & consent gates** (`04-cost-and-consent-gates.md`): whether auto-rig should be gated by cost/consent on the fork/studio paths is decided there, not here.+- **Completion state machine** (`02-completion-statemachine.md`) and **observability/events** (`08-observability-and-events.md`): the lifecycle/status transitions and event emission for these new jobs are owned by those prompts.diff --git a/prompts/production-1b/16-marketplace.md b/prompts/production-1b/16-marketplace.mdnew file mode 100644index 000000000..1c94f3196--- /dev/null+++ b/prompts/production-1b/16-marketplace.md@@ -0,0 +1,131 @@+# 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/production-1b/17-agent-profiles-studio-economy.md b/prompts/production-1b/17-agent-profiles-studio-economy.mdnew file mode 100644index 000000000..4e6e8bb59--- /dev/null+++ b/prompts/production-1b/17-agent-profiles-studio-economy.md@@ -0,0 +1,142 @@+# 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/production-1b/18-wallet-x402-payments.md b/prompts/production-1b/18-wallet-x402-payments.mdnew file mode 100644index 000000000..4938c55a4--- /dev/null+++ b/prompts/production-1b/18-wallet-x402-payments.md@@ -0,0 +1,148 @@+# 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/production-1b/33-onboarding-activation.md b/prompts/production-1b/33-onboarding-activation.mdnew file mode 100644index 000000000..f9e445e8a--- /dev/null+++ b/prompts/production-1b/33-onboarding-activation.md@@ -0,0 +1,102 @@+# 33 — Onboarding & activation funnel++> 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++Activation — a new visitor reaching their first "aha" — is the single biggest lever+on growth. Every dollar of acquisition is wasted if a first-timer can't make+something real in the first minute. three.ws already has the pieces (welcome modal,+"Getting started 0/3" checklist, a "What is three.ws" page, an 88-stop guided 3D+tour), but they must compose into one coherent path with a clear, fast first win and+honest measurement, or the funnel leaks at the top.++## Mission++Turn the first-run experience into a single, polished path that gets a brand-new+visitor from "what is this?" to "I made a 3D thing" in about 60 seconds, with every+step instrumented so activation is measurable.++## Map (trust but verify — files move)++- **Getting-started checklist + welcome modal** — [public/getting-started.js](../../public/getting-started.js)+ (the `STEPS` array: core `create → brain → embed`, optional `onchain → monetize`;+ renders the bottom-right "Getting started N/3" pill), [public/getting-started.css](../../public/getting-started.css).+- **In-product feature discovery** — [public/feature-discovery.js](../../public/feature-discovery.js)+ ("Have you tried…", `tws:feature-done` "what's next" cards), [public/feature-discovery.css](../../public/feature-discovery.css).+- **Intro / explainer pages** — [pages/what-is.html](../../pages/what-is.html) (`/what-is`),+ [pages/start.html](../../pages/start.html) (`/start`).+- **Guided 3D tour** — [src/feature-tour/director.js](../../src/feature-tour/director.js),+ [src/feature-tour/curriculum.js](../../src/feature-tour/curriculum.js),+ [public/tour/curriculum.json](../../public/tour/curriculum.json) (built by+ `scripts/build-tour.mjs`); tour page is `/tour`.+- **First "aha" surfaces** — [pages/forge.html](../../pages/forge.html) ++ [src/forge.js](../../src/forge.js) (free NVIDIA NIM text→3D), `/create` and+ [src/create-prompt.js](../../src/create-prompt.js) (text→avatar). The free lanes+ need no wallet.+- **Analytics taxonomy** — [src/analytics.js](../../src/analytics.js)+ (`FUNNELS.activation`: `landing_viewed → wallet_connect_started →+ wallet_connect_succeeded → agent_created`), [src/acquisition-analytics.js](../../src/acquisition-analytics.js).++## Do this++1. **Walk the real funnel in a browser** (`npm run dev`): open `/` in a fresh+ incognito profile (clear `localStorage`), follow the welcome modal → `/create` →+ finish a free generation. Time it. Note every dead-end, dead click, or moment of+ confusion. The free core path must never demand a wallet.+2. **Make the first win the default.** The fastest aha is the free NIM text→3D /+ text→avatar lane — ensure the welcome modal and `/start` route there first, with a+ one-line prompt suggestion so a blank composer never stalls a first-timer.+3. **Unify the three entry points** so they tell one story: the welcome modal+ (`getting-started.js`), `/what-is`, and `/tour`. Cross-link them; remove+ contradictory copy; ensure the "Getting started N/3" pill resumes correctly across+ pages and reflects real milestones (verify the `done()` route matchers in `STEPS`+ still point at live routes via `vercel.json`).+4. **Instrument activation honestly.** Confirm `AGENT_CREATED` / first-generation and+ each checklist `complete()` fire `track()` events through `src/analytics.js`+ (extend `FUNNELS.activation` or `ANALYTICS_EVENTS` if a step in the real path isn't+ covered — keep names in the existing taxonomy, never invent ad-hoc strings). No raw+ wallet addresses or PII as props (use `shortWallet()`).+5. **Design every onboarding state:** welcome modal has focus trap + Escape + "Maybe+ later" (verify), the checklist has an empty/first-run state and a celebratory+ complete state, and `tws:feature-done` "what's next" cards point only at confirmed+ live routes.+6. **Reduce time-to-value.** Cut any step that isn't required for the first win;+ defer wallet/on-chain prompts until after the user has made something. Lazy-load+ the heavy tour director so it never delays the homepage LCP.+7. **Verify resume + opt-out.** `data-getting-started="off"`, "Hide this", and the+ immersive-route exclusions must all work; progress persists across reloads and+ pages; the tour rehydrates from `sessionStorage` mid-flow.+8. **Run tests + changelog.** `npx vitest run` for any touched module and the tour+ build (`node scripts/build-tour.mjs` stays clean). Add a `data/changelog.json`+ entry for the user-visible onboarding improvement and run `npm run build:pages`.++## Must-not++- Do not gate the free core path behind a wallet, sign-up, or payment — the first aha+ must be free.+- Do not ship a fake progress bar or `setTimeout` "loading"; generation progress comes+ from real API responses only.+- Do not send PII (raw wallets, emails) to analytics; route through the taxonomy in+ `src/analytics.js` and truncate with `shortWallet()`.+- Do not reference any coin other than `$THREE`; the optional "monetize" step settles+ in `$THREE` only.+- Do not break the existing resume/opt-out behavior or double-mount the guide+ (`window.__twsGuide` idempotency).++## Acceptance (all true before claiming done)++- [ ] A fresh incognito visitor reaches a finished free 3D creation in ≤60s with no+ wallet and no console errors/warnings.+- [ ] Welcome modal, `/what-is`, and `/tour` tell one consistent story and cross-link;+ every CTA target is a live route.+- [ ] "Getting started N/3" pill resumes across pages, reflects real milestones, and+ has designed first-run + complete states.+- [ ] Each activation step fires a taxonomy event via `src/analytics.js` with no PII;+ `FUNNELS.activation` reflects the real path.+- [ ] Opt-out (`data-getting-started="off"`, "Hide this", immersive exclusions) and+ tour mid-flow rehydration all work.+- [ ] Touched tests pass, `scripts/build-tour.mjs` is clean, and the changelog entry+ is added with `npm run build:pages` clean.diff --git a/prompts/production-1b/34-home-landing-conversion.md b/prompts/production-1b/34-home-landing-conversion.mdnew file mode 100644index 000000000..10c18cf5e--- /dev/null+++ b/prompts/production-1b/34-home-landing-conversion.md@@ -0,0 +1,101 @@+# 34 — Home / landing conversion++> 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 homepage is where ad spend, press, and word-of-mouth all land. A first-time+visitor decides in about 5 seconds whether to stay. If the hero doesn't instantly+communicate "give your AI a body" and offer an obvious, fast next action, the+acquisition funnel dies before activation (prompt 33) even begins. A clear,+fast-loading, mobile-first, socially-proven landing page is the cheapest growth lever+the platform has.++## Mission++Make the home page make a cold visitor understand the product in 5 seconds and act:+sharp hero, one above-the-fold primary CTA, a live demo they can touch, credible+social proof, benefit-led copy, fast LCP, and flawless mobile.++## Map (trust but verify — files move)++- **Home page** — [pages/home.html](../../pages/home.html) (`/`). Hero h1 currently+ "The 3D agent layer of the internet." with bullets Create/Embed/Earn and the+ `.hero-cta-row` (`/create`, `/forge`, `#embed`, `/tour`). All inline `<style>` ++ `<script type="module">`.+- **Live demo embeds** — [src/home-forge.js](../../src/home-forge.js) (mini Forge:+ real `/api/forge` text→3D in-page), [src/forge-showcase.js](../../src/forge-showcase.js)+ ("Fresh from the Forge" community feed), [src/home-live-token.js](../../src/home-live-token.js)+ (live $THREE price), [src/api-playground.js](../../src/api-playground.js) and the+ `<agent-3d>` web component embed (`agent-3d/latest/agent-3d.js`).+- **Social proof / press strip** — the `.press-row` block in+ [pages/home.html](../../pages/home.html) (Anthropic, Coinbase, IBM, AWS, Google+ Cloud, Alibaba Cloud, Solana, CoinMarketCap, CoinGecko, HackerNoon) with SVGs in+ [public/featured-logos/](../../public/featured-logos).+- **CTA + funnel instrumentation** — `data-cta` / `data-cta-loc` attributes on every+ CTA, consumed by [src/acquisition-analytics.js](../../src/acquisition-analytics.js)+ → [src/analytics.js](../../src/analytics.js) (`CTA_CLICKED`, `LANDING_VIEWED`).+- **Performance budget** — Core Web Vitals work lives in+ `prompts/production-1b/11-*`; SEO/structured data in `prompts/production-1b/12-*`.++## Do this++1. **Open `/` cold on mobile and desktop** (`npm run dev`; emulate 320 / 768 / 1440).+ Read the hero as a stranger: in 5 seconds, is it obvious this turns your AI into an+ embeddable 3D avatar? Sharpen the h1/sub/bullets toward the plain promise ("give+ your AI a body" — make a 3D agent, embed it anywhere) without losing the existing+ voice or the i18n `data-i18n-*` hooks.+2. **One unmistakable primary CTA above the fold.** The hero has four buttons; keep+ the primary "Build your agent" visually dominant and make the rest clearly+ secondary so the eye has one path. Verify each `href` resolves in `vercel.json` and+ carries `data-cta`/`data-cta-loc`.+3. **Prove it with a live demo, not a screenshot.** Confirm the mini-Forge+ (`home-forge.js`) and the `<agent-3d>` embed actually run real generations / render+ live on load, with real elapsed time and designed loading/empty/error states (no+ `setTimeout` fakery). The showcase strip hides itself when empty — verify it never+ shows a hollow row.+4. **Make social proof credible and honest.** Keep the press/partner strip truthful+ (only real, linkable mentions — the SVGs in `public/featured-logos/`); ensure logos+ are lazy, accessible (alt/label), and don't push down the hero. Do not invent or+ overstate any endorsement.+5. **Fast LCP.** The hero text/CTA must be the LCP and must not wait on the 3D embed+ or model-viewer scripts — defer/lazy-load heavy modules (tour director, model+ viewer, showcase) below the fold. Preload the hero font/critical CSS only. Confirm+ no layout shift from late-loading logos or demos.+6. **Mobile is first-class.** At 320px the hero, CTA, and one demo must be usable+ without horizontal scroll; the CTA stays reachable (sticky or repeated near the+ fold). Touch targets ≥44px; the press strip wraps, never overflows.+7. **Wire the funnel.** Every CTA fires `CTA_CLICKED` with `cta`/`location`; the page+ fires `LANDING_VIEWED` once with referrer + UTM (already in+ `acquisition-analytics.js`) — verify it loads on `/` and no PII leaks.+8. **Verify + changelog.** Lighthouse the page locally (LCP, CLS), run touched tests+ (`npx vitest run`), add a `data/changelog.json` entry for the conversion+ improvement, and run `npm run build:pages`.++## Must-not++- Do not invent press/partner logos or overstate endorsements — only real, linkable+ mentions; this is a trust surface, not a dark pattern.+- Do not block LCP on the 3D embed, model-viewer, or any third-party script.+- Do not ship a fake/looping demo or a `setTimeout` progress bar — the demo is the+ real pipeline or it is not shown.+- Do not reference any coin other than `$THREE` (the live token widget is $THREE only).+- Do not strip `data-i18n-*`, `data-cta`, or accessibility attributes from existing+ elements.++## Acceptance (all true before claiming done)++- [ ] A cold visitor understands "give your AI a body" in ≤5s; one dominant+ above-the-fold CTA; all CTA `href`s resolve.+- [ ] The live demo runs the real pipeline on load with designed loading/empty/error+ states; the showcase never shows a hollow row.+- [ ] Press/partner proof is truthful, accessible, lazy, and does not push the hero+ below the fold.+- [ ] LCP is the hero (not the 3D embed); no CLS from late logos/demos; verified in+ Lighthouse locally.+- [ ] Usable at 320 / 768 / 1440 with no horizontal scroll and ≥44px touch targets.+- [ ] `LANDING_VIEWED` + every `CTA_CLICKED` fire with no PII; no console+ errors/warnings.+- [ ] Touched tests pass; changelog entry added and `npm run build:pages` clean.diff --git a/prompts/production-1b/35-pricing-monetization.md b/prompts/production-1b/35-pricing-monetization.mdnew file mode 100644index 000000000..575cb8bde--- /dev/null+++ b/prompts/production-1b/35-pricing-monetization.md@@ -0,0 +1,104 @@+# 35 — Pricing & monetization surfaces++> 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++Revenue is the proof a platform is worth $1B. A visitor must understand what's free,+what costs, and exactly what they get for the money — in seconds, with no surprise+charges. three.ws monetizes two ways: a public pricing page (Free + paid generation)+and per-call x402 micropayments priced from a single catalog. If costs are opaque,+inconsistent across surfaces, or ever leak a vendor's billing internals, trust and+conversion both collapse.++## Mission++Make pricing and monetization clear, consistent, and value-aligned everywhere: one+source-of-truth catalog driving the pricing page, the x402 pay-per-call flow, and the+`/pay` surface, with transparent costs, honest upgrade paths, and zero vendor billing+exposure.++## Map (trust but verify — files move)++- **Pricing catalog (source of truth)** — [api/_lib/pricing/catalog.js](../../api/_lib/pricing/catalog.js)+ (`CATALOG`, `publicCatalog()`, `priceForAction()`, `catalogEntry()`; prices in USD,+ settled in `$THREE`; Forge tier prices READ from `forge-tiers.js`, not duplicated),+ [api/_lib/pricing/charge-three.js](../../api/_lib/pricing/charge-three.js),+ [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js) (free draft tier on NVIDIA NIM).+- **Public pricing page** — [pages/pricing.html](../../pages/pricing.html) (`/pricing`),+ [public/pricing.css](../../public/pricing.css). Has a Free tier ("$0/forever, no+ credit card") + paid tiers in `#pricing-tiers`.+- **x402 pay surfaces** — [public/pay/index.html](../../public/pay/index.html) (`/pay`),+ [public/pay/calls/index.html](../../public/pay/calls), [public/pay/c/index.html](../../public/pay/c),+ the buyer-side checkout endpoint [api/x402-checkout.js](../../api/x402-checkout.js)+ (the `/pay` modal POSTs `/x402-checkout?action=prepare|encode`),+ [public/x402-pay-core.js](../../public/x402-pay-core.js), [public/x402.js](../../public/x402.js).+- **Paid endpoints (catalog consumers)** — [api/x402/](../../api/x402) (e.g.+ `forge.js`, `skill-call.js`, `service.js`, `mint-to-mesh.js`),+ [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js),+ [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js).+- **Conversion instrumentation** — [src/analytics.js](../../src/analytics.js)+ (`token_*` and CTA events). Trading/PnL disclaimers live with the market surfaces.++## Do this++1. **Map every price to the catalog.** Confirm `pages/pricing.html` and every `/pay`+ surface read from `api/_lib/pricing/catalog.js` (or `publicCatalog()` over an+ endpoint) — no hardcoded dollar amounts duplicated in HTML/JS that can drift from+ the catalog. Where a number is hardcoded today, wire it to the catalog or document+ why it's a fixed marketing figure.+2. **Walk the buyer flow in a browser** (`npm run dev`): `/pricing`, then a real+ per-call purchase via the `/pay` modal (`x402-checkout`). Confirm the quote is+ shown in USD with the `$THREE` settle amount, costs are explicit before signing,+ and the success/receipt state is clear (link to `my-receipts`).+3. **Never expose vendor billing.** Audit every error path in the pay/x402 chain: a+ provider quota/credit/billing message, raw 402/429/5xx body, or vendor URL must be+ masked to neutral, actionable copy ("Payment couldn't complete — try again");+ server logs keep the detail. This is a hard `/CLAUDE.md` rule.+4. **Value-metric alignment.** Make the unit of charge obvious and tied to value+ delivered (per generation / per call / per tier), not opaque "credits" with no+ anchor. If a credits model is shown, it must convert transparently to the same+ catalog prices.+5. **Design every state on the pay surfaces:** loading (quote fetching), empty (no+ wallet connected → connect path), error (masked, retryable), and success+ (receipt). The free tier must be clearly the default with no card required.+6. **Honest upgrade paths.** From the free Forge draft, the path to Standard/High (and+ from a free agent to monetizing it) must be discoverable and benefit-led, never a+ nag or a forced wall in front of the free aha. No dark patterns (no fake scarcity,+ no pre-checked add-ons, no hidden recurring charges).+7. **Instrument conversion.** Fire the existing `token_*` / CTA taxonomy events+ through `src/analytics.js` on pricing views, buy intent, quote shown, and settle —+ no raw wallet/PII (use `shortWallet()`).+8. **Test + changelog.** Run the pricing/x402 tests (`npx vitest run` over+ `tests/**/x402*`, `tests/**/pricing*`, `tests/**/forge-tiers*` as present), add a+ `data/changelog.json` entry for any user-visible pricing change, and run+ `npm run build:pages`.++## Must-not++- Do not surface any third party's billing page, credit balance, quota text, or raw+ error to a buyer — mask to neutral copy, log detail server-side.+- Do not duplicate prices: the catalog (`api/_lib/pricing/catalog.js`) is the single+ source of truth; surfaces read from it.+- Do not use dark patterns — no fake scarcity/countdowns, pre-checked upsells, hidden+ recurring charges, or a wall in front of the free aha.+- Do not reference, price, or settle in any coin other than `$THREE` (USD is the quote+ unit; `$THREE` is the settle unit).+- Do not show a trading/PnL/market figure without the required disclaimer.++## Acceptance (all true before claiming done)++- [ ] `/pricing` and every `/pay` surface read prices from the catalog; no drifting+ hardcoded amounts.+- [ ] A real per-call purchase completes in-browser with USD quote + `$THREE` settle+ shown before signing and a clear receipt after.+- [ ] Every pay/x402 failure mode yields neutral, actionable copy — no vendor billing+ internals — verified by tests.+- [ ] Free tier is the obvious default (no card); upgrade paths are benefit-led with+ no dark patterns.+- [ ] Loading/empty/error/success states designed on the pay surfaces; no console+ errors/warnings.+- [ ] Conversion events fire through the taxonomy with no PII.+- [ ] Pricing/x402 tests pass; changelog entry added and `npm run build:pages` clean.diff --git a/prompts/production-1b/36-growth-analytics.md b/prompts/production-1b/36-growth-analytics.mdnew file mode 100644index 000000000..ddc63fa50--- /dev/null+++ b/prompts/production-1b/36-growth-analytics.md@@ -0,0 +1,111 @@+# 36 — Growth analytics instrumentation++> 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++You cannot grow what you cannot measure. To scale acquisition, activation, and+retention deliberately, every meaningful step in the funnel must emit a clean,+consistently-named event — and never leak PII, or the platform becomes a privacy+liability instead of a $1B business. three.ws already has the spine (PostHog ++Vercel Web Analytics injected by Vite, a typed event taxonomy in `src/analytics.js`,+a first-party error reporter). The job is to complete coverage across the full funnel+without drift and without leaking.++## Mission++Complete privacy-respecting, consistently-taxonomied event instrumentation across the+activation → conversion → retention funnels, with dashboards/funnels that line up and+zero PII in any event.++## Map (trust but verify — files move)++- **Event taxonomy + facade (source of truth)** — [src/analytics.js](../../src/analytics.js)+ (`ANALYTICS_EVENTS`, `FUNNELS.activation`, `FUNNELS.three`, `track()`,+ `trackFunnelStep()`, `identifyUser()` / `resetIdentity()`, `trackError()`,+ `shortWallet()`). `track()` validates against the catalog and rejects unknown+ events — never bypass it.+- **Acquisition instrumentation** — [src/acquisition-analytics.js](../../src/acquisition-analytics.js)+ (`LANDING_VIEWED` once + delegated `CTA_CLICKED` over `data-cta`/`data-cta-loc`).+- **Existing call sites** — [src/wallet-auth.js](../../src/wallet-auth.js),+ [src/account.js](../../src/account.js), [src/create-agent.js](../../src/create-agent.js),+ [src/marketplace.js](../../src/marketplace.js), [src/three-token-page.js](../../src/three-token-page.js),+ [src/swap-jupiter.js](../../src/swap-jupiter.js), [src/agent-detail.js](../../src/agent-detail.js),+ [src/dashboard-next/shell.js](../../src/dashboard-next/shell.js).+- **Provider injection (do not duplicate)** — the `posthog-analytics`,+ `vercel-analytics`, and `client-error-reporter` plugins in+ [vite.config.js](../../vite.config.js) (PostHog snippet, `person_profiles:+ 'identified_only'`, ingest proxied through `/ingest`).+- **Server-side event/error sinks** — [public/error-reporter.js](../../public/error-reporter.js)+ → [api/client-errors.js](../../api/client-errors.js); per-surface analytics in+ [api/marketplace/analytics.js](../../api/marketplace/analytics.js),+ [api/walk/analytics.js](../../api/walk/analytics.js),+ [api/creators/skill-analytics.js](../../api/creators/skill-analytics.js).+- **Privacy reference** — [public/legal/privacy.html](../../public/legal/privacy.html)+ ("no IPs, no fingerprints", "no third-party advertising cookies"). Instrumentation+ must stay true to this.++## Do this++1. **Inventory before adding.** Grep for `track(`, `trackFunnelStep(`, `data-cta`, and+ `ANALYTICS_EVENTS` to map what already fires. Do not reinvent the spine — extend+ `src/analytics.js`. List the funnel gaps (any real step with no event).+2. **Complete the funnels by journey.** Ensure each stage emits a taxonomy event:+ acquisition (`landing_viewed`, `cta_clicked`), activation (`agent_created`,+ first-generation, checklist steps from prompt 33), conversion (the `token_*` and+ pay/x402 events from prompt 35), retention (return visits, key surfaces opened via+ `SURFACE_OPENED`, share actions). Add missing event names to `ANALYTICS_EVENTS` and+ wire them into `FUNNELS` so PostHog funnel insights line up automatically.+3. **One taxonomy, no drift.** All events go through the validating `track()` /+ `trackFunnelStep()` facade — no raw `window.posthog.capture()` ad-hoc strings in+ feature code. Names are snake_case and live only in `ANALYTICS_EVENTS`.+4. **PII audit — hard requirement.** No raw wallet addresses, emails, prompt text, or+ tokens as event props. Truncate wallets with `shortWallet()`; drop free-text+ prompts (send a length/category, not content). Verify `person_profiles:+ 'identified_only'` and that `identifyUser()` is called only after auth resolves+ with non-PII identifiers. Reconcile with `public/legal/privacy.html`.+5. **Fail-safe by design.** Every analytics call must no-op when PostHog is absent or+ blocked (`window.__posthog_blocked`) — verify the app works identically with an ad+ blocker on, in an embed iframe, and offline. Analytics can never break the page.+6. **Verify events fire in a browser** (`npm run dev`): with PostHog network calls+ visible, walk landing → create → a free generation → a pay flow and confirm each+ expected event fires once with correct, PII-free props. Confirm dedupe (e.g.+ `LANDING_VIEWED` fires exactly once).+7. **Dashboards/funnels.** Document the canonical activation, conversion, and+ retention funnels (the `FUNNELS` map is the contract) so PostHog funnel/insight+ definitions match the code. Keep this in the existing analytics docs, not a new+ throwaway file.+8. **Test + changelog.** Run touched tests (`npx vitest run`, including any+ `tests/**/analytics*`); add a `data/changelog.json` entry only if a user-visible+ surface changed (pure instrumentation is internal and usually skips the changelog —+ see `/CLAUDE.md`). Run `npm run build:pages` if you touched anything that feeds it.++## Must-not++- Do not send PII as event props — no raw wallets, emails, prompt/message text, or+ tokens. Truncate and categorize.+- Do not bypass the `track()` facade with ad-hoc `posthog.capture()` calls or invent+ event names outside `ANALYTICS_EVENTS`.+- Do not add a second analytics vendor, advertising pixel, or fingerprinting — stay+ within the existing PostHog + Vercel stack and the privacy policy.+- Do not let an analytics failure (blocked/offline/embed) break or block the app.+- Do not reference any coin other than `$THREE` in event names or props.++## Acceptance (all true before claiming done)++- [ ] Every funnel stage (acquisition → activation → conversion → retention) emits a+ taxonomy event through `track()` / `trackFunnelStep()`; gaps closed.+- [ ] No ad-hoc event strings or raw `posthog.capture()` in feature code; all names in+ `ANALYTICS_EVENTS`.+- [ ] PII audit passes — no raw wallets/emails/prompt text/tokens in any event;+ consistent with `public/legal/privacy.html`.+- [ ] App behaves identically with PostHog blocked, in an embed iframe, and offline+ (no errors, no broken flows).+- [ ] Each expected event verified firing once with PII-free props in a real browser+ session.+- [ ] `FUNNELS` matches documented PostHog funnels; docs updated in place (no+ throwaway file).+- [ ] Touched tests pass; changelog handled per `/CLAUDE.md` and `npm run build:pages`+ clean if it was touched.diff --git a/prompts/production-1b/38-referral-virality.md b/prompts/production-1b/38-referral-virality.mdnew file mode 100644index 000000000..29b62a156--- /dev/null+++ b/prompts/production-1b/38-referral-virality.md@@ -0,0 +1,96 @@+# 38 — Referral & virality loops++> 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++Paid acquisition does not scale to a billion-dollar platform — loops do. Every+creation a user makes is a potential ad: a share card that lands in a feed, an+embedded `<agent-3d>` widget on someone else's site carrying a "made with three.ws"+mark, a referral link that pulls in the next builder. The platform already has+OG-image endpoints, embeddable web components, and a referral schema — this prompt+turns those scattered parts into closed, measurable viral loops.++## Mission++Make sharing a creation one click, make every shared/embedded artifact carry+attribution back to three.ws, and make the existing referral mechanics complete,+rewarding, and instrumented end-to-end.++## Map (trust but verify — files move)++- **Share cards (@vercel/og)** — [api/forge-og.js](../../api/forge-og.js),+ [api/avatar-og.js](../../api/avatar-og.js), [api/agent-og.js](../../api/agent-og.js),+ [api/agent-detail-og.js](../../api/agent-detail-og.js), [api/play-og.js](../../api/play-og.js),+ [api/trader-og.js](../../api/trader-og.js), [api/walk-og.js](../../api/walk-og.js),+ [api/page-og.js](../../api/page-og.js), [api/u-og.js](../../api/u-og.js).+- **Share UI** — [src/share-panel.js](../../src/share-panel.js),+ [src/share-panel-builders.js](../../src/share-panel-builders.js),+ [src/share-panel.css](../../src/share-panel.css),+ [src/pose-share.js](../../src/pose-share.js); server share endpoints+ [api/forge-share.js](../../api/forge-share.js), [api/agent-share.js](../../api/agent-share.js),+ [api/oracle-share.js](../../api/oracle-share.js).+- **Embeddable web components** — `<agent-3d>` in [src/element.js](../../src/element.js),+ `<agent-stage>` in [src/stage-element.js](../../src/stage-element.js); embed loaders+ [public/embed.js](../../public/embed.js), [public/embed/v1.js](../../public/embed/v1.js).+- **Referral mechanics** — [api/users/referrals.js](../../api/users/referrals.js),+ [api/users/referral-claim.js](../../api/users/referral-claim.js),+ [api/friends/index.js](../../api/friends/index.js), schema in+ [api/_lib/migrations/001_add_referrals.sql](../../api/_lib/migrations/001_add_referrals.sql).+- **"Made with three.ws" attribution** — search current usage in+ [src/avatar-page.js](../../src/avatar-page.js), [public/studio/studio.js](../../public/studio/studio.js).++## Do this++1. **One-click share on every creation surface** (Forge result, avatar page, agent+ profile, pose, oracle, walk). Use the Web Share API where available, with a copy-link+ + X/Telegram/Farcaster fallback. Wire the existing `share-panel.js` everywhere a+ creation is finished; no surface should dead-end without a share affordance.+2. **Verify every OG endpoint renders a real, branded card** for real entity IDs (not a+ 1px or fallback image): correct title, creator, thumbnail, consistent brand. Fix any+ `*-og.js` that throws or renders an empty card; add the `og:`/`twitter:` meta tags on+ the shareable pages so the card actually appears when pasted into a social platform.+3. **Embed carries attribution.** Every `<agent-3d>` / `<agent-stage>` / iframe embed+ renders a subtle, non-intrusive "made with three.ws" mark that links back with a+ referral/UTM param. Confirm it survives the embed-strip build step and shows in a+ third-party iframe.+4. **Close the referral loop.** Audit `referrals.js` + `referral-claim.js`: a user gets+ a unique link, a new user arriving via it is attributed, the referrer is credited,+ and the reward is real (not a no-op). Build the user-facing referral UI (link, copy+ button, status: invited / joined / rewarded) if it's missing.+5. **Attribution params flow through.** Embed marks, share links, and referral links all+ set a consistent UTM/ref param; landing pages read it, persist it through signup, and+ credit the right referrer. No param dropped on redirect.+6. **Instrument the loop** so growth analytics (see prompt 36) can measure it: emit+ events for share-initiated, share-completed, embed-impression, referral-click,+ referral-signup. Use the existing analytics plumbing, not a new one.+7. **Design every state**: share success toast, copy-confirmed, share-unsupported+ fallback, referral empty state ("invite your first builder"), and rewarded state.+8. Run the relevant tests (`npx vitest run` over share/og/referral specs), add a+ `data/changelog.json` entry (tag `feature`) for the new sharing/referral UX, and+ `npm run build:pages`.++## Must-not++- Do not generate share cards or referral copy that reference any coin other than+ `$THREE`.+- Do not register a service worker from inside embeds, and do not strip the attribution+ mark — both must survive `scripts/strip-sw-from-embeds.mjs`.+- Do not fake referral rewards or counts; credit only real, verified signups.+- Do not break working OG routes; verify each renders before and after edits.+- No `setTimeout` fake share progress; real async only.++## Acceptance (all true before claiming done)++- [ ] Every creation surface (forge, avatar, agent, pose, oracle, walk) has working+ one-click share with a copy-link fallback.+- [ ] Every `*-og.js` renders a real branded card for real IDs; shareable pages carry+ `og:`/`twitter:` meta and preview correctly when pasted.+- [ ] Embeds show a "made with three.ws" mark linking back with a ref/UTM param,+ surviving the embed-strip build.+- [ ] Referral link → attributed signup → real reward works end-to-end with a+ user-facing referral UI (all states designed).+- [ ] Loop events are instrumented through the existing analytics layer.+- [ ] Tests pass; changelog updated; `npm run build:pages` clean.diff --git a/prompts/production-1b/39-trust-safety-moderation.md b/prompts/production-1b/39-trust-safety-moderation.mdnew file mode 100644index 000000000..956821b73--- /dev/null+++ b/prompts/production-1b/39-trust-safety-moderation.md@@ -0,0 +1,88 @@+# 39 — Trust, safety & moderation++> 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 where anyone can generate and upload 3D content, avatars, and text is one+NSFW front-page screenshot away from losing app-store listings, payment processors,+and press goodwill. Brands, the chains we integrate with, and the press logos in our+footer all need to trust that three.ws is safe by default. Trust & safety is not a+cost center at scale — it is the license to operate.++## Mission++Gate every generation and upload path through content moderation, give users real+report/abuse flows, and back it all with rate-limited anti-spam — so unsafe content+is caught before it ships and removable after.++## Map (trust but verify — files move)++- **Text moderation** — [api/_lib/moderation.js](../../api/_lib/moderation.js)+ (`moderateAnonInput`, `moderationEnabled`, `parseVerdict`, `refusalReply`).+- **Image/vision moderation** — [api/_lib/vision.js](../../api/_lib/vision.js)+ (`describeImage`, `describeImageJson`, `visionConfigured`, `assertSafeImageUrl`).+- **Current call sites** — moderation is already used in [api/chat.js](../../api/chat.js),+ [api/brain/chat.js](../../api/brain/chat.js), [api/pump/[action].js](../../api/pump/[action].js),+ [api/widgets/[id]/[action].js](../../api/widgets/[id]/[action].js),+ [api/sns-subdomain.js](../../api/sns-subdomain.js), [api/wk.js](../../api/wk.js);+ vision in [api/ibm/vision.js](../../api/ibm/vision.js). Generation entry:+ [api/forge.js](../../api/forge.js), avatar reconstruct in [api/avatars/](../../api/avatars).+- **Rate limiting** — [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js).+- **Alt-text / description helpers** — [api/_lib/avatar-alt-text.js](../../api/_lib/avatar-alt-text.js)+ (uses vision; a hook point for upload-time checks).++## Do this++1. **Map every user-generated input path**: text→3D prompts, text→avatar prompts,+ selfie/image uploads, image→3D, agent chat, page text, marketplace listings,+ usernames/SNS subdomains. For each, confirm whether moderation/vision is applied —+ build a coverage table.+2. **Close the gaps on generation.** Every prompt-driven generation (forge, avatars)+ must run text through `moderateAnonInput` before spending compute; block disallowed+ prompts with `refusalReply()`-style neutral copy (no echo of the unsafe text).+3. **Gate uploads.** Every selfie/image upload and image→3D path runs through+ `vision.js` NSFW/safety checks before reconstruction; reject unsafe images with a+ clear, non-judgmental message and no provider internals leaked.+4. **Fail safe, not open.** When a moderation provider is unconfigured or errors,+ decide the policy explicitly per surface (block vs. allow-with-flag) — never silently+ skip the check on a public generation path. Use the existing cockatiel resilience+ helper for provider calls.+5. **Report/abuse flow.** Add a "Report" affordance on user-facing content (avatars,+ agents, marketplace listings, embedded pages) that writes to a real moderation queue+ (a table + `api/` handler), captures reporter, target, and reason, and rate-limits+ submissions. No client-only fake report.+6. **Takedown path.** Reported/flagged content must be hideable/removable: a real admin+ action that sets a moderation status which the public surfaces respect (hidden content+ 404s or shows a removed-content state).+7. **Anti-spam.** Apply `rate-limit.js` to generation, upload, report, and any unauthenticated+ write path so a single client can't flood the platform. Tune limits per surface; return+ a proper 429 with a designed retry message.+8. Run `npx vitest run` over moderation/vision/rate-limit specs (add cases for+ NSFW-blocked, unconfigured-provider, and over-limit). Note any policy-visible change in+ `data/changelog.json` (tag `security`) and `npm run build:pages`.++## Must-not++- Do not echo the unsafe user input back in any error, log line shown to the user, or+ share card.+- Do not let a public generation/upload path run when moderation is unconfigured without+ an explicit, documented fail-safe decision.+- Do not leak vendor/provider internals (billing, model names, raw verdicts) to end users.+- Do not reference any coin other than `$THREE` in moderation copy, tests, or fixtures.+- No mock moderation, no `// TODO: moderate later`, no stubbed report endpoint.++## Acceptance (all true before claiming done)++- [ ] Coverage table shows every user-generated input path and its moderation status;+ no public generation/upload path is unprotected.+- [ ] Prompt generation blocks unsafe text via moderation before spending compute, with+ neutral copy and no echo.+- [ ] Image uploads / image→3D run NSFW/safety vision checks before reconstruction.+- [ ] Unconfigured/erroring providers fail safe per an explicit per-surface policy.+- [ ] Real report/abuse flow writes to a moderation queue and rate-limits; takedown+ hides flagged content on every public surface.+- [ ] Generation, upload, report, and unauth writes are rate-limited with a designed 429.+- [ ] Moderation/vision/rate-limit tests pass with new safety cases; changelog updated.diff --git a/prompts/production-1b/40-legal-compliance-tos-privacy.md b/prompts/production-1b/40-legal-compliance-tos-privacy.mdnew file mode 100644index 000000000..8442add25--- /dev/null+++ b/prompts/production-1b/40-legal-compliance-tos-privacy.md@@ -0,0 +1,100 @@+# 40 — Legal, compliance, ToS & privacy++> 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 handles wallets, on-chain trading, user uploads, and PII cannot scale+without a defensible legal posture. Enterprise customers, app stores, payment rails,+and the chains we integrate with all require accurate ToS, a real privacy policy with+GDPR/CCPA data rights, financial disclaimers on trading surfaces, and correct+open-source attribution for the vendored three.js and animation libraries. One missing+disclaimer or one un-attributed MIT library is an avoidable legal and reputational risk.++## Mission++Make the legal pages accurate to what the platform actually does, wire real GDPR/CCPA+data-rights and consent flows, place financial/custody disclaimers on every trading and+wallet surface, and ensure every vendored library is correctly attributed.++## Map (trust but verify — files move)++- **Legal pages** — [public/legal/privacy.html](../../public/legal/privacy.html)+ (already has GDPR/Cookie/Retention sections), [public/legal/tos.html](../../public/legal/tos.html)+ (has a disclaimer + wallet section), [public/legal/eula.html](../../public/legal/eula.html),+ [public/legal/aws-marketplace-eula.html](../../public/legal/aws-marketplace-eula.html).+- **Footer links** — [public/footer.html](../../public/footer.html) (`/legal/privacy`,+ `/legal/tos`), [public/footer.js](../../public/footer.js); routes in+ [vercel.json](../../vercel.json).+- **Surface-specific legal** — [pages/extension-privacy.html](../../pages/extension-privacy.html),+ [pages/extension-terms.html](../../pages/extension-terms.html),+ [pages/irl-privacy.html](../../pages/irl-privacy.html),+ [extensions/walk-avatar/PRIVACY.md](../../extensions/walk-avatar/PRIVACY.md),+ [extensions/walk-avatar/TERMS.md](../../extensions/walk-avatar/TERMS.md).+- **Wallet / trading surfaces (need disclaimers)** — [pages/pricing.html](../../pages/pricing.html),+ Oracle / trader / pump.fun surfaces (search `pages/` and `src/` for `agent-trade`,+ `oracle`, `trader`, `pumpfun`), x402 payment UI in+ [src/payment-modal.js](../../src/payment-modal.js).+- **Vendored OSS to attribute** — [character-studio/LICENSE](../../character-studio/LICENSE)+ (Atlas Foundation, MIT), [public/scene-studio/LICENSE](../../public/scene-studio/LICENSE)+ (three.js authors, MIT), [public/animations/LICENSES.md](../../public/animations/LICENSES.md)+ (per-clip upstream + license), [public/environments/LICENSES.md](../../public/environments/LICENSES.md).+- **Data-rights backend hook** — referral/user data in [api/users/](../../api/users),+ privacy-center task reference at+ [tasks/irl-hardening/H5-privacy-center-forget-me.md](../../tasks/irl-hardening/H5-privacy-center-forget-me.md).++## Do this++1. **Audit ToS + Privacy against reality.** Read `tos.html` and `privacy.html` line by+ line; verify every claim matches what the platform actually collects, stores, and+ does (uploads, wallet addresses, on-chain activity, analytics, cookies, third-party+ providers). Fix anything inaccurate; remove anything no longer true.+2. **GDPR/CCPA data rights — make them real.** Confirm the privacy policy lists the data+ collected, retention periods, and lawful basis. Provide working "export my data" and+ "delete my account / forget me" flows (a real `api/` endpoint backed by the user/referral+ tables), not a "contact us" stub. Reference the H5 privacy-center task for scope.+3. **Cookie / consent.** If analytics or any non-essential storage runs, add a consent+ mechanism (banner or settings) that actually gates those scripts; record consent and+ respect "reject." If everything is strictly necessary, document that explicitly so the+ policy is truthful.+4. **Financial / trading disclaimers.** Every surface that shows prices, trading, the+ Oracle, pump.fun launches, or token data must carry a clear "not financial advice / no+ warranty / DYOR" disclaimer placed in-context (not buried). Wire it as a shared,+ reusable component so it's consistent everywhere.+5. **Custody / wallet disclosures.** Wallet and x402 payment surfaces must disclose+ custody model, that on-chain transactions are irreversible, and fee/risk notes. Verify+ the disclosure appears in `payment-modal.js` and any agent-wallet UI.+6. **Open-source attribution.** Cross-check vendored libraries: three.js (scene-studio),+ character-studio (Atlas Foundation), and every animation clip's upstream license. Ensure+ each is attributed in a reachable place (an `/legal/licenses` or open-source page linked+ from the footer), and that the per-clip `LICENSES.md` is complete for shipped clips.+7. **$THREE-only sweep of legal copy.** Ensure no legal/disclaimer text names any token+ other than `$THREE`; trading disclaimers stay coin-agnostic about user-supplied mints.+8. Add a `data/changelog.json` entry (tag `security` or `docs`) for the legal/privacy+ updates, run `npm run build:pages`, and confirm footer links resolve via `audit:pages`.++## Must-not++- Do not write legal claims you cannot verify against the actual implementation.+- Do not ship a "delete my data" or "export" button that doesn't actually do it.+- Do not omit attribution for any vendored MIT/OSS library or animation clip.+- Do not reference any coin other than `$THREE` in legal, disclaimer, or consent copy.+- Do not gate consent with a banner that doesn't actually block the non-essential scripts.++## Acceptance (all true before claiming done)++- [ ] ToS and Privacy accurately describe real data practices, providers, retention, and+ on-chain/wallet behavior.+- [ ] Working data-export and account-deletion ("forget me") flows backed by real+ endpoints, linked from the privacy policy.+- [ ] Cookie/consent mechanism gates non-essential scripts and records the choice (or the+ policy truthfully states all storage is strictly necessary).+- [ ] Financial/DYOR disclaimers appear in-context on every trading/Oracle/pump/token+ surface via a shared component.+- [ ] Custody/wallet/irreversibility disclosures present on wallet + x402 payment UIs.+- [ ] Every vendored library (three.js, character-studio, animation clips) attributed on a+ footer-linked licenses page; per-clip `LICENSES.md` complete.+- [ ] No non-`$THREE` coin referenced in any legal copy; footer legal links resolve;+ changelog updated and `npm run build:pages` clean.diff --git a/prompts/production-1b/41-i18n-completion.md b/prompts/production-1b/41-i18n-completion.mdnew file mode 100644index 000000000..968a9cf9a--- /dev/null+++ b/prompts/production-1b/41-i18n-completion.md@@ -0,0 +1,87 @@+# 41 — i18n completion++> 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 billion-dollar platform is global. Most of the world's builders and traders do not+read English, and the markets where 3D + on-chain adoption grows fastest are not+English-first. The i18n machinery already exists (extract → translate → lint, runtime+locale swap, a `<lang-switcher>` element), but coverage is thin — only `en` and `es`+catalogs ship, and hardcoded strings leak everywhere. Finishing i18n unlocks entire+regions at near-zero marginal cost.++## Mission++Get full user-facing string extraction and translation coverage, working locale+switching with RTL and locale-aware number/date/currency formatting, and zero hardcoded+user-facing strings on the primary surfaces.++## Map (trust but verify — files move)++- **i18n config** — [.i18nrc.json](../../.i18nrc.json) (entry, entryLocale, output dir,+ outputLocales, localeNames), schema at+ [scripts/i18n-rc.schema.json](../../scripts/i18n-rc.schema.json).+- **Pipeline scripts** — [scripts/i18n-extract.mjs](../../scripts/i18n-extract.mjs)+ (`npm run i18n:extract`), [scripts/i18n-translate.mjs](../../scripts/i18n-translate.mjs)+ (`npm run i18n:translate`, and `--lint` → `npm run i18n:lint`). Combined:+ `npm run i18n`.+- **Locale catalogs** — [public/locales/](../../public/locales) (`en.json`, `es.json`,+ `manifest.json` — the `manifest.locales[]` list each with `code`, `name`, `dir`).+- **Runtime i18n** — [src/i18n.js](../../src/i18n.js) (client-side locale swap, fetches+ `/locales/<code>.json`, sets `document.documentElement.dir`, dispatches `i18n:change`,+ defines `<lang-switcher>`).+- **Surfaces to cover** — `pages/*.html` (~168) and `src/` modules; start with the+ conversion-critical ones (home, forge, pricing, marketplace, docs landing, wallet).++## Do this++1. **Run the pipeline and read the lint output.** `npm run i18n:extract` then+ `npm run i18n:lint` to see missing/extra keys per locale and the current coverage gap.+ This is your worklist.+2. **Find hardcoded user-facing strings.** Grep the high-traffic `pages/*.html` and `src/`+ modules for literal English in markup/JS that isn't going through the i18n key system.+ Wrap them with the project's translation mechanism (match how `src/i18n.js` consumers+ already do it). Prioritize the conversion funnel surfaces first.+3. **Expand target locales.** Add a sensible set of high-impact locales to+ `.i18nrc.json` `outputLocales` + `localeNames` and the `manifest.json` `locales[]`+ (include at least one RTL locale, e.g. `ar`, with `dir: "rtl"`). Run+ `npm run i18n:translate` to generate the catalogs against the real translation provider+ — no hand-faked translations, no machine-gibberish left unreviewed for key terms.+4. **Locale switching works end-to-end.** Verify `<lang-switcher>` appears when ≥2 locales+ exist, swaps the catalog at runtime without a full reload, persists the choice, and+ updates `document.documentElement.dir`. Test on home + forge in a real browser.+5. **RTL correctness.** With an RTL locale active, audit layout: logical CSS properties+ (`margin-inline`, `text-align: start`), mirrored icons/arrows where appropriate, and no+ broken flex/grid direction. Fix the worst offenders on the primary surfaces.+6. **Locale-aware formatting.** Replace ad-hoc number/date/currency string-building with+ `Intl.NumberFormat` / `Intl.DateTimeFormat` keyed off the active locale (counts, prices,+ timestamps, $THREE amounts). No `toFixed`-then-concat money formatting.+7. **Don't break the brand or the coin.** "three.ws" and "$THREE" stay verbatim across+ locales (mark them as non-translatable terms); never let a translation invent a coin.+8. Run `npm run i18n:lint` (must pass), exercise locales in the browser, add a+ `data/changelog.json` entry (tag `improvement`) for the new languages, and+ `npm run build:pages`.++## Must-not++- Do not hand-write or fake translations to pass the lint — generate them through the real+ `i18n:translate` provider.+- Do not leave hardcoded user-facing English on the primary conversion surfaces.+- Do not translate "three.ws", "$THREE", or the contract address; keep brand/coin verbatim.+- Do not ship an RTL locale that visibly breaks layout on home/forge/pricing.+- Do not introduce a second i18n system — extend the existing `src/i18n.js` + scripts.++## Acceptance (all true before claiming done)++- [ ] `npm run i18n:lint` passes with no missing/extra keys across all configured locales.+- [ ] No hardcoded user-facing strings remain on the primary funnel surfaces (home, forge,+ pricing, marketplace, wallet, docs landing).+- [ ] `outputLocales` expanded (incl. ≥1 RTL locale); catalogs generated via the real+ translate provider, not faked.+- [ ] `<lang-switcher>` swaps locale at runtime, persists, and sets `dir`; verified in browser.+- [ ] RTL layout is correct on the primary surfaces; no mirrored-layout breakage.+- [ ] Numbers/dates/currency use `Intl` keyed to the active locale, including $THREE amounts.+- [ ] Brand and coin stay verbatim across locales; changelog updated; `build:pages` clean.diff --git a/prompts/production-1b/42-pwa-offline-notifications.md b/prompts/production-1b/42-pwa-offline-notifications.mdnew file mode 100644index 000000000..042df5a54--- /dev/null+++ b/prompts/production-1b/42-pwa-offline-notifications.md@@ -0,0 +1,95 @@+# 42 — PWA, offline & notifications++> 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++Installable, offline-capable, re-engageable web apps retain users like native apps at+a fraction of the cost — and three.ws is exactly the kind of "open it daily" product+(your agent did something, a launch moved, a trade filled) that web push was built for.+But a misconfigured service worker is a footgun: it can poison caches across the origin,+break embeds in third-party iframes, or serve stale JS that makes the app look broken.+This prompt makes the PWA correct, installable, gracefully offline, and able to bring+users back — without any caching bugs.++## Mission++Verify service-worker correctness (including the embed-strip behavior), polish the+install experience and manifest, ship a real offline fallback, and add web push for+agent activity — with zero SW caching bugs.++## Map (trust but verify — files move)++- **PWA / SW config** — [vite.config.js](../../vite.config.js) (`VitePWA({ … })` ~line+ 1856: `registerType: 'autoUpdate'`, `workbox.globPatterns: ['**/*.{js,css,ico,woff2}']`+ — HTML deliberately excluded — `navigateFallback: null`,+ `maximumFileSizeToCacheInBytes: 5MB`).+- **Embed SW strip** — [scripts/strip-sw-from-embeds.mjs](../../scripts/strip-sw-from-embeds.mjs)+ (post-build; removes the `vite-plugin-pwa:register-sw` `<script>` from embed-surface+ HTML — `widget.html`, `embed.html`, `agent-embed`, `a-embed`, `avatar-embed`). Vite+ also strips it via a `transformIndexHtml` hook (`vite.config.js` ~line 515).+- **Web manifest** — [public/site.webmanifest](../../public/site.webmanifest) (name,+ icons `pwa-192`/`pwa-512` any+maskable, `display: standalone`, theme `#050505`).+- **Offline fallback** — existing example at [public/cz/offline/index.html](../../public/cz/offline)+ (pattern to generalize for the main app).+- **Embed surfaces** — [public/embed.js](../../public/embed.js),+ [public/embed/v1.js](../../public/embed/v1.js); the `<agent-3d>` element in+ [src/element.js](../../src/element.js).+- **Agent-activity sources for push** — agent/wallet/launch events in [api/](../../api)+ (find the activity/feed handlers under `api/_lib/feed.js` and friends).++## Do this++1. **Verify SW correctness with a real build.** `npm run build`, serve `dist/`, and in+ DevTools → Application confirm the SW registers on the main app, `autoUpdate` activates+ the new SW, and there's no stale-asset trap (cached JS/CSS update on deploy). HTML must+ not be precached (it's intentionally excluded) — pages always come from network.+2. **Confirm embeds never register a SW.** Inspect built embed HTML (`widget.html`,+ `embed.html`, `*-embed`) for the absence of the `vite-plugin-pwa:register-sw` script;+ load an embed inside a third-party iframe and confirm no SW is installed for the origin.+ This is a hard correctness/privacy requirement — keep the strip step working.+3. **Install experience.** Validate `site.webmanifest` against Lighthouse PWA criteria:+ icons resolve (192/512, any + maskable), `start_url`, scope, `display`. Add a tasteful,+ dismissible "Install three.ws" prompt using the `beforeinstallprompt` event (no nag+ loop; respect dismissal). Test install on desktop Chrome and Android.+4. **Real offline fallback.** Generalize the `public/cz/offline` pattern into an offline+ page for the main app: when navigation fails offline, show a branded offline screen with+ what's cached/available, not a browser error. Wire it correctly given `navigateFallback`+ is currently `null` — choose the right workbox strategy without breaking the network-first+ HTML rule.+5. **Web push for agent activity.** Implement push end-to-end: VAPID keys from env, a+ real subscribe flow (permission prompt only on user intent, never on load), a+ `PushSubscription` persisted to a real table, and an `api/` send path that fires on real+ agent-activity events (e.g. agent acted, launch update, trade filled). No fake/test pushes+ shipped.+6. **Notification UX + controls.** Notifications deep-link to the relevant surface, are+ throttled/de-duped, and the user can manage/disable them in settings. Respect denied+ permission gracefully.+7. **Audit cache scope.** Confirm runtime caching (if any) is scoped so it can't serve a+ user another user's data, and that signed-in/API responses aren't cached as static.+8. Run `npm run build`, the SW/embed checks above, relevant tests, add a+ `data/changelog.json` entry (tag `feature`/`improvement`) for install + notifications,+ and `npm run build:pages`.++## Must-not++- Do not register a service worker from any embed surface — the strip step must keep working.+- Do not precache HTML or cache authenticated/API responses as static assets.+- Do not request notification permission on page load — only on explicit user intent.+- Do not ship fake/test push notifications or a stubbed subscribe endpoint.+- Do not reference any coin other than `$THREE` in notification or offline copy.++## Acceptance (all true before claiming done)++- [ ] Built SW registers + auto-updates on the main app with no stale-asset trap; HTML+ stays network-first.+- [ ] Embed surfaces register no SW; verified inside a third-party iframe; strip step intact.+- [ ] Manifest passes Lighthouse PWA install criteria; dismissible install prompt works on+ desktop + Android without nagging.+- [ ] Offline navigation shows a branded offline fallback, not a browser error.+- [ ] Web push works end-to-end (VAPID, user-intent subscribe, persisted subscription, real+ agent-activity trigger); notifications deep-link and are manageable.+- [ ] No cross-user or stale API data served from cache.+- [ ] `npm run build` clean; tests pass; changelog updated; `npm run build:pages` clean.diff --git a/prompts/production-1b/43-brand-press-social-proof.md b/prompts/production-1b/43-brand-press-social-proof.mdnew file mode 100644index 000000000..20dd87d24--- /dev/null+++ b/prompts/production-1b/43-brand-press-social-proof.md@@ -0,0 +1,98 @@+# 43 — Brand, press & social proof++> 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++Trust is the conversion multiplier. A first-time visitor decides in seconds whether+three.ws is a serious company or a side project — and the signals that decide it are+brand consistency, real press coverage, and visible social proof. three.ws has genuine+coverage (Business Insider, IBM partnership, Yahoo Finance, Crunchbase, Vogue, KuCoin+listing) and partner logos already in the repo, but they're scattered in the footer and+a `/news` feed instead of working as a coherent credibility story. Surfacing them well+turns existing assets into acquisition leverage.++## Mission++Lock brand consistency across the platform (logo, OG images, voice), build a real press+page that surfaces the existing coverage, and weave testimonials/case studies and trust+signals into the high-intent surfaces.++## Map (trust but verify — files move)++- **Brand mark** — [public/brand.js](../../public/brand.js) (universal top-left brand+ chip; opt-out via `data-no-brand-mark`), logos in [public/](../../public)+ (`logo.png`, `favicon.svg`, `favicon.ico`, `pwa-192x192.png`, `pwa-512x512.png`).+- **Partner / featured logos** — [public/featured-logos/](../../public/featured-logos)+ (`anthropic.svg`, `coinbase.svg`, `solana.svg`, `googlecloud.svg`,+ `alibabacloud.svg`, `coinmarketcap.svg`, `hackernoon.svg`), plus+ [public/ibm-partner-logo.png](../../public/ibm-partner-logo.png).+- **Existing press links** — [public/footer.html](../../public/footer.html) (Business+ Insider, IBM community, Yahoo Finance, Crunchbase, Vogue, KuCoin, TradingView),+ echoed in [public/features.json](../../public/features.json).+- **News / announcements** — [public/news/](../../public/news) (~107 items),+ [public/news/index.html](../../public/news/index.html) ("News & Announcements"),+ build via `npm run build:news`; [public/launch-week.html](../../public/launch-week.html).+- **Default OG image** — [public/og-image.png](../../public/og-image.png),+ [public/ibm-og.png](../../public/ibm-og.png); per-surface OG endpoints `api/*-og.js`+ (see prompt 38).+- **Voice / brand copy** — [public/llms.txt](../../public/llms.txt) and home copy in+ [pages/home.html](../../pages/home.html) (the canonical brand description).++## Do this++1. **Brand consistency audit.** Walk the main pages and confirm `brand.js` (or a native+ header) puts the same logo, same wordmark casing ("three.ws"), and same theme color+ on every standalone surface. Fix any page with a stray/old logo treatment or missing+ mark. Confirm favicon + PWA icons are consistent.+2. **OG image consistency.** Verify every shareable page has an `og:image` (default+ `og-image.png` or its per-surface `*-og.js` card) with consistent brand framing —+ same logo placement, type, and color. No page should fall back to a broken or+ off-brand preview when pasted into a social platform.+3. **Build a real press page.** Create `/press` (a static page under `public/`, routed in+ `vercel.json` like `/news`) that surfaces the existing coverage as a credible+ "as seen in" wall: outlet logos linking to the real articles already in the footer,+ plus the IBM partnership and the news feed. Pull from real data+ (`public/features.json` / footer links / `public/news/`) — no invented quotes or+ fabricated outlets.+4. **"As seen in" trust strip on high-intent surfaces.** Add a tasteful logo strip+ (using `public/featured-logos/` + real press outlets) to the home page and pricing+ page, linking through to the press page. Real partners/coverage only.+5. **Testimonials / case studies.** Surface real social proof — genuine user creations,+ real quotes, or verifiable usage stats from platform data (e.g. agents created,+ launches, embeds). Build a testimonials/case-study section sourced from real records;+ do not write fake testimonials or attribute quotes to people who didn't say them.+6. **Trust signals throughout.** Place credibility cues where decisions happen: security+ note near wallet/payment, "open source / MIT" near SDKs/docs, partner logos near the+ integration story, real counts near the marketplace. Each must link to something real.+7. **Voice consistency.** Align headline/CTA copy with the canonical brand description+ ("The 3D agent layer of the internet …" from the manifest/`llms.txt`). Remove+ off-brand or contradictory taglines.+8. Verify all new images via `npm run check:images`, run `npm run audit:pages` and+ `npm run seo:meta`, add a `data/changelog.json` entry (tag `feature`) for the press+ page + trust strip, and `npm run build:pages`.++## Must-not++- Do not fabricate press coverage, partner relationships, testimonials, or stats — only+ surface what's real and verifiable from the repo/platform data.+- Do not reference any coin other than `$THREE` in brand, press, or social-proof copy.+- Do not break the `brand.js` chromeless opt-out for embeds/iframes.+- Do not ship off-brand or broken OG images; every shareable page previews correctly.+- No placeholder logos, "logo here" boxes, or lorem-ipsum testimonials.++## Acceptance (all true before claiming done)++- [ ] Logo, wordmark casing, theme color, favicon, and PWA icons are consistent across all+ main standalone pages.+- [ ] Every shareable page has a consistent, on-brand `og:image` that previews correctly.+- [ ] A real `/press` page surfaces the existing coverage (real outlets → real articles)+ and is routed + linked from the footer/nav.+- [ ] An "as seen in" trust strip appears on home + pricing using real partner/press+ logos, linking to the press page.+- [ ] Testimonials/case-study section sourced from real data — no fabricated quotes/stats.+- [ ] Trust signals (security, OSS, partners, real counts) placed at decision points, each+ linking to something real.+- [ ] `check:images`, `audit:pages`, `seo:meta` clean; changelog updated; `build:pages` clean.diff --git a/prompts/production-1b/44-launch-readiness-review.md b/prompts/production-1b/44-launch-readiness-review.mdnew file mode 100644index 000000000..bceb79d99--- /dev/null+++ b/prompts/production-1b/44-launch-readiness-review.md@@ -0,0 +1,102 @@+# 44 — Launch-readiness review (final 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. **This is the last prompt in the program — the go/no-go gate.**++## Why this matters for $1B++Everything in prompts `01`–`43` is only real if it survives a single, ruthless,+end-to-end review. A platform aiming at $1B cannot launch on vibes: it launches when+every audit is green, the full test suite passes, security review is clean, and the+`/CLAUDE.md` Definition of Done is verifiably true across every surface. This gate exists+to catch the one red that would otherwise become the incident, the chargeback, or the+front-page screenshot. Its job is to **block launch** — not to bless it by default.++## Mission++Run every audit, the full test suite, and a security review across the whole platform;+verify the Definition of Done on every surface; produce a single scorecard; and return a+go/no-go that is **no-go on any red**.++## Map (trust but verify — files move)++- **The coverage map** — prompts [01](../../prompts/production-1b) through+ [43](../../prompts/production-1b) in [prompts/production-1b/](../../prompts/production-1b).+ Each prompt's **Acceptance** section is a checklist this gate re-verifies at a spot-check+ level; treat them as the requirements traceability matrix.+- **Audit scripts** (in [package.json](../../package.json)) — `audit:deploy`,+ `audit:pages`, `audit:handlers`, `audit:web`, `audit:mcp`, `check:images`, `seo:meta`,+ `check:dist`, `check-api-not-bundled` (in [scripts/](../../scripts)).+- **Verify / smoke** — `verify`, `verify:solana`, `verify:onchain`, `verify:ibm`,+ `verify:zauth`, `smoke:onchain`, `smoke:mcp`, `smoke:agent-wallet`, `snapshot`.+- **Tests** — `npm test` (`vitest run && playwright test`), `test:all`, `test:gate`,+ `lint`, `typecheck`; CI at [.github/workflows/ci.yml](../../.github/workflows/ci.yml)+ (jobs: lint, test, guards, typecheck).+- **Definition of Done + operating rules** — [/CLAUDE.md](../../CLAUDE.md).+- **Changelog integrity** — [data/changelog.json](../../data/changelog.json) →+ `npm run build:pages` → [public/changelog.json](../../public/changelog.json),+ [public/changelog.xml](../../public/changelog.xml), [CHANGELOG.md](../../CHANGELOG.md).++## Do this++1. **Run the full audit battery and capture results.** Execute and record pass/fail ++ key output for each: `npm run lint`, `npm run typecheck`, `npm test`, `npm run audit:deploy`,+ `audit:pages`, `audit:handlers`, `audit:web`, `audit:mcp`, `check:images`, `seo:meta`,+ `check:dist`. Do not summarize away failures — every red is a launch blocker until fixed+ or explicitly waived with a stated reason and owner.+2. **Run the on-chain / integration verifiers.** `npm run verify`, `verify:solana`,+ `verify:onchain`, `smoke:onchain`, `smoke:mcp`, `smoke:agent-wallet`. These touch real+ chains/services — record real results, never assume green.+3. **Run a security review** (`/security-review`) over the platform's exposed surface:+ authz, input validation, SSRF, secrets/env hygiene, rate limiting, moderation gates,+ and payment/wallet flows. Cross-check against prompts `05`, `07`, `08`, `31`, `39`.+ Any high/critical finding is an automatic no-go.+4. **Build a clean production artifact.** `npm run build`; then `check:dist` and verify no+ `api/*.js` source got bundle-overwritten (`head -1` for `__defProp`/`createRequire`, per+ `/CLAUDE.md`). A poisoned `api/` diff is a no-go.+5. **Verify the Definition of Done across surfaces.** For each top product surface (Forge,+ Marketplace, Agent Studio, Wallet/x402, Walk/Page-Agent, Scene/Animation Studio,+ Character Studio, Pump/Oracle/$THREE, MCP, SDK, Worlds): spot-check the `/CLAUDE.md` DoD+ — reachable, no console errors, real API calls, every state designed, hover/focus,+ empty/error states, mobile. Note any surface that fails.+6. **Spot-check the Phase 4 growth & compliance prompts (33–43)** specifically: onboarding+ funnel, conversion, pricing, analytics, docs accuracy, virality/attribution, moderation+ gates, legal/privacy + disclaimers, i18n lint, PWA/SW + embed-strip, brand/press. Each+ must meet its own Acceptance; record gaps.+7. **$THREE-only sweep.** Grep the repo (source, copy, fixtures, docs, OG, tests, commit+ messages staged) for any non-`$THREE` coin reference; the contract address must be+ `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` where present. Any other coin is an+ automatic no-go and must be removed.+8. **Changelog + freshness.** Confirm every user-visible change from this program has a+ `data/changelog.json` entry; run `npm run build:pages` and confirm it validates and+ regenerates `CHANGELOG.md` + public changelog feeds cleanly.+9. **Produce the scorecard and verdict.** Emit a single scorecard: one row per area+ (Phase 0–4 + each audit + security + DoD), each marked GREEN / YELLOW / RED with a+ one-line reason and, for non-green, the blocking item and owner. End with an explicit+ **GO** or **NO-GO**. NO-GO if *any* row is RED.++## Must-not++- Do not declare GO with any RED row, any failing audit/test, or any+ high/critical security finding — no exceptions, no "we'll fix it after launch."+- Do not skip a flaky or slow audit/test — re-run it; investigate the cause; record the+ real result. A skipped check is treated as RED.+- Do not mask or summarize away a failure to make the scorecard look green.+- Do not run `npm run changelog:push` as part of the gate (that's post-deploy).+- Do not introduce new features here — this is verification only; fix blockers, don't gold-plate.+- Do not reference any coin other than `$THREE`; flag any that exists as a blocker.++## Acceptance (all true before claiming done — i.e., before a GO)++- [ ] `lint`, `typecheck`, `npm test` (vitest + playwright), and all `audit:*` ++ `check:images` + `seo:meta` + `check:dist` pass; results recorded.+- [ ] All `verify*` and `smoke:*` integration/on-chain checks pass with recorded real output.+- [ ] `/security-review` complete with zero high/critical findings open.+- [ ] Clean production build; no bundle-overwritten `api/*.js`.+- [ ] `/CLAUDE.md` Definition of Done spot-verified on every top product surface.+- [ ] Phase 4 prompts (33–43) each meet their Acceptance; gaps recorded and resolved.+- [ ] $THREE-only sweep clean (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); no other coin.+- [ ] Changelog complete and `npm run build:pages` validates/regenerates cleanly.+- [ ] A scorecard exists (one row per area, GREEN/YELLOW/RED + reason/owner) with an+ explicit **GO / NO-GO** verdict; verdict is **GO only if every row is GREEN**.diff --git a/prompts/production-campaign/A-reliability/00-README.md b/prompts/production-campaign/A-reliability/00-README.mdnew file mode 100644index 000000000..4776850b6--- /dev/null+++ b/prompts/production-campaign/A-reliability/00-README.md@@ -0,0 +1,64 @@+# Track A — Reliability, Observability & Trust++This is the foundation every other track ships on. A platform is worth $1B when it is+**trusted with money, used daily, and built upon by others** — and all three collapse the+moment software loses funds, 500s under load, or fails silently. Track A makes that+impossible. Run it first; keep it green; never let B–G regress it.++Read `prompts/production-campaign/00-README-orchestration.md` and `00b-the-bar.md` first —+the global definition of done and the reliability/performance bars there are inherited by+every prompt below. This README only adds the track-local run order and the file-ownership+map that lets the seven prompts run in parallel without colliding.++> **This is hardening, not greenfield.** three.ws already ships `api/_lib/sentry.js`,+> `_lib/axiom.js`, `_lib/http.js` (the `wrap()` boundary used by ~91 of 100 handlers),+> `_lib/resilience.js` (cockatiel), `_lib/rate-limit.js` (@upstash/ratelimit),+> `api/client-errors.js`, `api/csrf-token.js`, a `pages/status.html`, `.lighthouserc.json`,+> `scripts/test-gate.mjs`, and `.github/workflows/ci.yml`. The gaps are **coverage and+> enforcement**: observability reaches only a handful of handlers and zero workers, ~42+> routes are unrate-limited, ~77 are unvalidated, the resilience helper has one call site,+> and CI gates lint+vitest but not the test gate, Lighthouse, or playwright. Extend what+> exists. Do not rewrite working code.++---++## The seven prompts++| ID | Mission (one line) | Run order / depends on |+|---|---|---|+| **A1** | Wire Sentry + Axiom + trace/request IDs across **every** `api/*.js` handler and every worker; alert on error-rate spikes; readable error dashboard. Make silent failure impossible. | **First.** Foundation for A2–A7's verification. No deps. |+| **A2** | One error-envelope shape, zod validation, `@upstash/ratelimit`, and idempotency keys across the ~100 `api/*.js` endpoints. | After A1 (so new boundaries emit traces). |+| **A3** | Audit every money path (x402 checkout, agent-wallet custody/sends, USDC, billing, mint): idempotency, on-chain confirm before success, "your funds are safe" failed state, no double-spend. | After A1 + A2 (envelope + traces in place). |+| **A4** | Auth, CSRF, secret hygiene (grep the built bundle), per-endpoint authorization, abuse prevention, security headers/CSP. | After A2 (shares the boundary helpers). |+| **A5** | Raise vitest+playwright coverage on money/auth/3D paths, kill flakes, enforce `test:gate` in CI. | After A2/A3/A4 land the code it must cover. |+| **A6** | Lighthouse CI as a gate, hold Core Web Vitals budgets, lazy-load Three.js, compress GLBs, mobile perf. | Parallel with A1–A5 (own lane). |+| **A7** | Circuit breakers (cockatiel), upstream fallback (RPC/3D/LLM/pump.fun), health checks, `/status` page, and fix the Forge "free engines all busy" dead-end into a graceful path. | After A1 (health feeds observability + status). |++**Recommended order:** A1 → (A2 ∥ A6) → (A3 ∥ A4 ∥ A7) → A5. A1 lands the telemetry every+other prompt verifies against; A5 is last because it must cover the code A2–A4 ship.++---++## File-ownership map (run in parallel without colliding)++Each prompt owns a lane. Where two prompts must touch a shared file, the **owner** is named;+the other prompt extends additively and never reformats. `data/changelog.json` and+`data/pages.json` are append-only for everyone.++| Prompt | Owns (primary write lane) | May read / extend additively (not owner) |+|---|---|---|+| **A1** | `api/_lib/sentry.js`, `api/_lib/axiom.js`, `api/_lib/alerts.js`, `api/client-errors.js`, worker telemetry shims, `docs/ops/observability.md` (new) | `api/_lib/http.js` `wrap()` (coordinate with A2) |+| **A2** | `api/_lib/http.js`, `api/_lib/validate.js`, `api/_lib/rate-limit.js`, per-handler validation/limits in `api/*.js`, `docs/API_AUDIT.md` | error-envelope shape consumed by A3/A4 |+| **A3** | `api/x402-checkout.js`, `api/_lib/agent-wallet.js`, `api/_lib/x402-*.js`, `api/_lib/subscription-billing.js`, `src/agent-wallet/`, money-path tests | idempotency keys from A2; envelope from A2 |+| **A4** | `api/csrf-token.js`, `api/_lib/csrf.js`, `api/_lib/auth.js`, `src/auth/`, security headers in `api/_lib/http.js` (coordinate with A2), `docs/security/` | per-endpoint authz wired into A2's boundary |+| **A5** | `vitest.config.js`, `playwright.config.js`, `scripts/test-gate.mjs`, `tests/**`, `.github/workflows/ci.yml` (test jobs) | covers code from A2/A3/A4 |+| **A6** | `.lighthouserc.json`, `.github/workflows/ci.yml` (lighthouse job), `scripts/optimize-glb.mjs`, `scripts/compress-glbs.mjs`, lazy-load wiring in `src/` 3D entry points | shares `ci.yml` with A5 — append jobs, don't reformat |+| **A7** | `api/_lib/resilience.js`, `api/_lib/forge-health.js`, `api/_lib/provider-health.js`, `api/forge.js` + `src/forge.js` busy path, `pages/status.html`, `api/health*.js` | health events flow into A1's telemetry |++**Shared-file protocol:** `api/_lib/http.js` is touched by A1 (telemetry inside `wrap()`),+A2 (envelope/validation/limits), and A4 (headers/CSP). A2 owns its structure; A1 and A4 add+named helpers and call them — no reformatting, stage explicit hunks, re-read `git diff+--staged` before commit. `ci.yml` is shared by A5 (test jobs) and A6 (lighthouse job): each+appends a job, neither rewrites the file.++When this directory contains only this `00-README.md`, Track A is done.diff --git a/prompts/production-campaign/A-reliability/A1-observability-backbone.md b/prompts/production-campaign/A-reliability/A1-observability-backbone.mdnew file mode 100644index 000000000..a428da34e--- /dev/null+++ b/prompts/production-campaign/A-reliability/A1-observability-backbone.md@@ -0,0 +1,93 @@+# A1 — Observability Backbone++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** none —+this is the first prompt in Track A; every other prompt verifies its work against the telemetry+you land here.++## Why this matters for $1B+A platform trusted with money cannot fail silently. The day an x402 settlement or an+agent-wallet send fails and nobody is paged is the day trust dies — and you only find out from+an angry holder, not a dashboard. "Observability is total" is a $1B reliability bar+(`00b-the-bar.md` §1): every error captured, every paid call traced, every worker reporting+health. Right now that bar is half-met, and the half that's missing is where money moves.++## Current state (read before you write)+- `api/_lib/http.js` exports `wrap(handler)` — the boundary ~91 of 100 `api/*.js` handlers+ already use. It calls `captureException(err, { ref, url, method })` on a thrown error and+ stamps a `ref`. That `ref` is the seam to build on.+- `api/_lib/sentry.js` exports `captureException` / `captureMessage` (Sentry guarded by+ `SENTRY_DSN`). `api/_lib/axiom.js` exports `axiomEnabled()`, `ingestEvent(fields)`,+ `recordPaymentMetric(...)`. `api/_lib/alerts.js` exports `sendOpsAlert(title, detail, opts)`.+- `api/client-errors.js` ingests browser errors from `public/error-reporter.js` and logs one+ structured `[client-error]` line; it forwards to Sentry when configured.+- **The gap (measured):** only 3 handlers import sentry directly, **0 import axiom**, and no+ worker (`workers/agent-sniper`, `workers/deploy`, `workers/model-*`, `workers/avatar-*`)+ emits structured telemetry. There is no per-request **trace/request ID** propagated into+ logs, no **error-rate spike** alert, and no single **readable error view**. Silent failure+ is still possible. Verify these counts yourself with grep before writing.++## Your mission+### 1. Make `wrap()` the universal trace + telemetry boundary+In `api/_lib/http.js`, extend `wrap()` (additively — do not change its signature or break the+existing `ref`) to: derive a **request ID** (reuse an inbound `x-request-id` / Vercel+`x-vercel-id` if present, else generate one), set it on the response header, and thread it+through every `captureException` context **and** an `ingestEvent` call to Axiom on both success+(sampled) and failure (always) with `{ route, method, status, durationMs, requestId, ref }`.+Every handler that already uses `wrap()` inherits this for free — that's the leverage. Audit the+~9 handlers NOT using `wrap()` and either wrap them or justify each in `docs/ops/observability.md`.++### 2. Structured logging with trace IDs, one shape+Add a tiny structured logger to `api/_lib/axiom.js` (or a new `api/_lib/log.js` it re-exports)+that emits one JSON line per event — `{ ts, level, route, requestId, msg, ...fields }` — to+stdout (so Vercel log drains capture it) AND to Axiom when enabled. Replace ad-hoc+`console.log`/`console.error` on money/auth paths with it. Make `requestId` flow from `wrap()`+into handlers (attach to `req` or pass via context) so a single request is traceable end to end.++### 3. Bring workers into the same telemetry plane+Workers run outside the `api/` boundary and are currently dark. Add a shared worker telemetry+shim (mirror the axiom/sentry helpers — reuse, don't fork) so every worker in `workers/*`+reports: start, completion, failure (with Sentry capture), and a **heartbeat/health** signal.+Wire it into each worker's main loop / job handler. A worker that dies must page, not vanish.++### 4. Alert on error-rate spikes — not just single errors+`sendOpsAlert` fires per-error today. Add rate-aware alerting: when a route's error rate or a+worker's failure count crosses a threshold over a short window, fire **one** deduped ops alert+(reuse the existing dedupe in `_lib/alerts.js`/`sentry.js`; don't double-page). Money/auth+routes get a tighter threshold than read endpoints. Document thresholds in `docs/ops/`.++### 5. A readable error dashboard / surface+Engineers and the status page both need a human view. Provide a real, reachable surface — a+queryable Axiom dashboard config committed to the repo **and** a small authenticated internal+read endpoint (or extend an existing ops/admin surface) that summarizes recent error counts by+route, top error refs, and worker health. No raw stack traces to unauthenticated users. Wire+its health summary so A7's `/status` page can consume it (the seam between A1 and A7).++### 6. Verify the wiring is live, not theoretical+Trigger a real error on a non-money route and confirm: a Sentry event with the `requestId`, an+Axiom event for the same request, the response carrying the request-ID header, and (by forcing+a burst) exactly one spike alert. Capture the trace IDs in your completion report.++## Definition of done+Clears `00b-the-bar.md` §1 "Observability is total": **every** `api/*.js` handler emits a traced+success/failure event with a propagated request ID; **every** worker reports start/finish/fail ++heartbeat; error-rate spikes page once (deduped); a readable, auth-gated error/health surface+exists and feeds A7's status page. No `console.log` left on money/auth paths. Real triggered+error produces a correlated Sentry + Axiom + header trail (IDs in the report). Inherits the global+definition of done in `00-README-orchestration.md`. If `SENTRY_DSN`/`AXIOM_*` are absent locally,+say so and verify the code paths/no-op guards instead of claiming live capture.++## Operating rules (override defaults)+No mocks/fake data/placeholders/TODOs/stubs. `$THREE` is the only coin. Design tokens only+(`public/tokens.css`) for any UI. Stage explicit paths only (never `git add -A`); re-check+`git diff --staged` before commit. Own the telemetry lane — `api/_lib/sentry.js`,+`_lib/axiom.js`, `_lib/alerts.js`, `api/client-errors.js`, worker shims, `docs/ops/`. You touch+`_lib/http.js` `wrap()` additively; A2 owns that file's structure — coordinate, add named+helpers, don't reformat. Extend the existing helpers; don't rewrite them.++## When finished+Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. sample-rate control, or a+PII scrub on logged fields tied to A4's hygiene). Append a `data/changelog.json` entry (tag:+`infra`) — holders care that the platform watches itself. Then delete this prompt file+(`prompts/production-campaign/A-reliability/A1-observability-backbone.md`) and report what you+shipped, the verification trace IDs, and the health-summary seam you left for A7.diff --git a/prompts/production-campaign/A-reliability/A2-api-hardening.md b/prompts/production-campaign/A-reliability/A2-api-hardening.mdnew file mode 100644index 000000000..fc03a6558--- /dev/null+++ b/prompts/production-campaign/A-reliability/A2-api-hardening.md@@ -0,0 +1,90 @@+# A2 — API Hardening++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** A1+(so the new boundaries you harden emit traces and request IDs).++## Why this matters for $1B+Every public endpoint is attack surface and trust surface at once. An unvalidated body that+500s, a mutating route that double-charges on a retry, or a rate-free endpoint that lets one+client exhaust an upstream — each one breaks the "trusted with money, used daily" promise.+`00b-the-bar.md` §4 is explicit: "Inputs are validated at the boundary and trusted internally.+Rate-limited where abusable. CSRF-protected where state-changing." This prompt makes that true+across all ~100 endpoints with **one** consistent shape so the platform behaves predictably+under load and abuse.++## Current state (read before you write)+- `api/_lib/http.js` is the shared boundary: `wrap()`, `json()`, `error()`, `serverError()`,+ `validationError()`, `rateLimited()`, `readJson()`, `method()`, `cors()`. Error responses+ already force `no-store` and set `x-content-type-options`/`x-frame-options`. This is your base.+- `api/_lib/rate-limit.js` wraps `@upstash/ratelimit` (`limits`, `clientIp`). `api/_lib/validate.js`+ exists. `zod@^3` is a dependency.+- **The gap (measured — verify with grep):** of 100 `api/*.js` handlers, only ~58 import+ rate-limit and only ~23 use zod/validate. Mutating routes lack **idempotency keys**. The+ error response shape is *mostly* consistent but not enforced — different handlers return+ different bodies. There is no single documented envelope contract.++## Your mission+### 1. Define and enforce ONE error-envelope shape+Pin the canonical error body in `api/_lib/http.js` (extend `error()`/`validationError()`/+`serverError()` so they're the only way to emit an error) — e.g.+`{ ok: false, error: { code, message, requestId, ref?, fields? } }` — carrying A1's `requestId`.+Document it once in `docs/API_AUDIT.md`. Migrate handlers returning ad-hoc error bodies to the+helpers. Success responses stay as-is unless trivially normalizable; do not churn working reads.++### 2. Validate input at every boundary with zod+For every handler that reads a body, query, or path params, add a zod schema and parse at the+top, returning `validationError()` (with field-level detail) on failure. Centralize reusable+schemas in `api/_lib/validate.js`. Internal code then trusts its inputs — no defensive+re-checking downstream. Prioritize: mutating routes, money routes, anything taking a wallet+address / mint / amount. Cover the ~77 currently-unvalidated handlers; track progress in+`docs/API_AUDIT.md`.++### 3. Rate-limit every abusable route+Apply `@upstash/ratelimit` via `_lib/rate-limit.js` to the ~42 routes that lack it. Tier the+limits: generous on cheap reads, tight on expensive/abusable ones (generation, LLM proxies,+mint, send, anything that spends an upstream's quota or money). On limit, return the consistent+`rateLimited()` envelope with a `Retry-After`. Use `clientIp` + (for authed routes) the+identity as the key. If Redis is unavailable, fail **open** for reads and **closed** for+money/auth routes — never crash.++### 4. Idempotency keys on every mutating route+Add idempotency to POST/PUT/PATCH/DELETE handlers that create or change state. Accept an+`Idempotency-Key` header (and/or derive a deterministic key from the operation); store+key→result in Redis with a TTL; on a repeat key, return the stored result instead of re-running.+This is the boundary contract; A3 will rely on it for the money paths specifically — so make the+helper reusable and money-path-grade. Build a small `idempotent(handler, keyFn)` helper alongside+`wrap()` and document it.++### 5. Error boundaries at every network/input edge+Audit handlers for un-awaited promises, unguarded `JSON.parse`, and upstream calls without+try/catch. Every network/input boundary must produce an actionable envelope, never a raw 500 or+hung request. Internal logic (post-validation) trusts itself — don't over-wrap pure functions.++### 6. Produce the audit ledger+Update `docs/API_AUDIT.md` into a real per-endpoint matrix: validated ✓, rate-limited ✓,+idempotent ✓ (or N/A for reads), auth-gated (defer detail to A4), envelope ✓. This is the+checklist A5 turns into tests and A4 cross-checks for authz.++## Definition of done+Clears `00b-the-bar.md` §4: all ~100 handlers validate input at the boundary, every abusable+route is rate-limited with a `Retry-After`, every mutating route is idempotent and retry-safe,+and **one** error-envelope shape is enforced through `http.js` helpers carrying A1's requestId.+`docs/API_AUDIT.md` is a complete, accurate matrix. A retried mutating request returns the same+result, not a duplicate. Inherits the global definition of done in `00-README-orchestration.md`.++## Operating rules (override defaults)+No mocks/fake data/placeholders/TODOs/stubs. `$THREE` is the only coin. Design tokens only for any+UI. Stage explicit paths only (never `git add -A`); re-check `git diff --staged` before commit.+**You own `api/_lib/http.js`'s structure**, `_lib/validate.js`, `_lib/rate-limit.js`, the+per-handler validation/limits, and `docs/API_AUDIT.md`. A1 adds telemetry inside `wrap()` and A4+adds headers/CSP — accept their additive helpers; don't undo them. Extend; don't rewrite working+handlers' success paths.++## When finished+Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. a body-size cap or a+content-type guard applied platform-wide via the boundary). Append a `data/changelog.json` entry+(tag: `improvement` or `security`) only if user-visible (e.g. clearer error messages). Then delete+this prompt file (`prompts/production-campaign/A-reliability/A2-api-hardening.md`) and report the+envelope shape, the idempotency helper signature (A3 depends on it), and any route you left+deliberately un-limited and why.diff --git a/prompts/production-campaign/A-reliability/A3-payment-correctness.md b/prompts/production-campaign/A-reliability/A3-payment-correctness.mdnew file mode 100644index 000000000..04d96d5b8--- /dev/null+++ b/prompts/production-campaign/A-reliability/A3-payment-correctness.md@@ -0,0 +1,102 @@+# A3 — Payment Correctness++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** A1+(traces on money paths) and A2 (the idempotency helper + error envelope you'll reuse).++## Why this matters for $1B+This is **the** trust foundation. A platform that loses funds once is worth zero forever — no+feature, no growth, no polish recovers from "it took my money and gave me nothing." `00b-the-bar.md`+§1 states it plainly: "No money is ever lost or double-spent. Payment, mint, send, and trade paths+are idempotent, retry-safe, and confirm on-chain before claiming success. A failed transaction+surfaces a clear 'this did not go through, your funds are safe' state." Every dollar that flows+through three.ws flows through the paths you audit here.++## Current state (read before you write)+- **x402 checkout:** `api/x402-checkout.js` already builds Solana/EVM payment transactions, uses+ `createAssociatedTokenAccountIdempotentInstruction` (idempotent ATA), and has retry/confirm+ logic ("confirm and prompts a clean retry, never a double charge"). `api/_lib/x402-solana-confirm.js`,+ `_lib/x402-spending-ledger.js`, `_lib/x402-spending-cap.js`, `_lib/evm-payment-verify.js`,+ `_lib/x402-errors.js` (the `X402Error` type) are the supporting cast.+- **Agent-wallet custody/sends:** `api/_lib/agent-wallet.js`, `_lib/agent-spend-policy.js`,+ `_lib/solana-transfer.js`, `_lib/evm-transfer.js`, `src/agent-wallet/ownership.js`. Existing+ guard tests: `tests/agent-custody-guards.test.js`.+- **Billing / subscriptions:** `api/_lib/subscription-billing.js`, `_lib/subscription-checkout.js`,+ `_lib/subscription-pricing.js`. Existing: `tests/billing.test.js`.+- **Mint / launch:** `api/pump-launch.js`, `_lib/pump-platform-fee.js`, `_lib/onchain-deploy.js`,+ `_lib/payout.js`, `_lib/royalty.js`, `_lib/fee.js`.+- **The gap:** correctness is strong in places (x402 checkout) and unproven elsewhere. There is no+ single audit guaranteeing **every** money path: (a) is idempotent under retry, (b) confirms+ on-chain before reporting success, (c) has a designed failed/refund state, (d) cannot+ double-spend. Verify each path's current behavior by reading it — do not assume.++## Your mission+### 1. Enumerate every money path, then audit each against four invariants+Build the inventory (x402 checkout + paid-endpoint settlement, agent-wallet sends, USDC+transfers, subscription billing, mint/launch fees, payouts/royalties, copy-trade execution, any+`*-spending-*` ledger write). For each, verify and fix: **(a) Idempotency** — a retried request+with the same idempotency key (A2's helper) never moves funds twice; **(b) Confirm-before-success**+— success is reported only after on-chain confirmation (reuse `x402-solana-confirm.js` /+`evm-payment-verify.js` patterns), never on broadcast; **(c) Failed/refund state**; **(d)+No double-spend** under concurrent requests (Redis lock / atomic ledger write).++### 2. "Your funds are safe" failure state — everywhere money moves+Every money path's failure must produce the exact reassurance pattern from the bar: a clear,+designed state that says *this did not go through, your funds are safe*, with a real retry. No+ambiguous "error" toast on a payment, no spinner that spins after a broadcast, no silent+swallow. Wire this in both the API envelope (A2 shape) and the UI surfaces that call these paths+(Forge high-quality unlock, x402 checkout, agent send, billing). Distinguish "broadcast failed+(funds untouched)" from "broadcast succeeded, confirmation pending" — they need different copy.++### 3. On-chain confirmation gate on every send/mint+No path reports success on a signature alone. Each must poll/confirm to the right commitment+('confirmed'/'finalized' as appropriate) within a budget, then verify the on-chain effect (token+received, ATA funded, fee paid) before flipping state to success. On timeout, return a "pending —+we'll confirm" state, never a false success. Record the signature so a later reconciliation can+resolve pending → success/failed.++### 4. Atomic ledgers and concurrency safety+The spending ledger and any balance/cap accounting must be atomic — concurrent requests on the+same wallet cannot both pass a cap check and both spend. Use Redis atomic ops / a per-wallet lock.+Reconcile pending entries (a sweep that confirms or fails stuck signatures) so the ledger never+drifts from chain truth.++### 5. Reconciliation + alerting on money anomalies+Wire money-path failures and anomalies (a confirm timeout, a ledger mismatch, a refund) into A1's+telemetry with `recordPaymentMetric(...)` and a tighter ops-alert threshold. A stuck or failed+payment must page. Add a reconciliation routine (endpoint or worker) that resolves pending+signatures and flags drift.++### 6. Prove it with tests+Extend `tests/agent-custody-guards.test.js` and `tests/billing.test.js` and add money-path specs:+double-submit returns one effect; broadcast-then-confirm-fail yields the "funds safe" state;+concurrent cap checks can't both pass; a pending signature reconciles correctly. These feed A5's+gate — make them offline-safe so `scripts/test-gate.mjs` can include them.++## Definition of done+Clears `00b-the-bar.md` §1 money clause for **every** path in the inventory: idempotent,+retry-safe, confirm-on-chain-before-success, no double-spend, and a designed "your funds are safe"+failure state in both API and UI. Atomic ledger; reconciliation resolves pending. Money anomalies+page via A1. New tests cover double-submit, confirm-failure, and concurrency, and run in the gate.+Inherits the global definition of done in `00-README-orchestration.md`. Where you cannot exercise a+live mainnet path locally, verify the logic and tests and say so — never claim a live settlement you+didn't observe.++## Operating rules (override defaults)+No mocks/fake data/placeholders/TODOs/stubs — **and no real third-party mints in tests/fixtures**;+use `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or a clearly-synthetic placeholder.+`$THREE` is the only coin. Stage explicit paths only (never `git add -A`); re-check `git diff+--staged` before commit (watch the `npx vercel build` trap that bundles `api/*.js` — check `head -1`+for `__defProp`). **You own the money paths**: `api/x402-checkout.js`, `_lib/agent-wallet.js`,+`_lib/x402-*`, `_lib/subscription-billing.js`, `src/agent-wallet/`, money-path tests. Reuse A2's+idempotency helper and A1's payment metrics; don't fork them. Extend the strong existing logic; don't+rewrite working confirm code.++## When finished+Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. the pending-signature+reconciliation sweep, or a per-wallet daily-spend safety ceiling). Append a `data/changelog.json`+entry (tag: `security` or `fix`) — "your funds are safe" guarantees are exactly what holders want to+read. Then delete this prompt file+(`prompts/production-campaign/A-reliability/A3-payment-correctness.md`) and report the money-path+inventory, which invariants each path already met vs. you fixed, and any path needing live-mainnet+verification you couldn't do locally.diff --git a/prompts/production-campaign/A-reliability/A4-security-hardening.md b/prompts/production-campaign/A-reliability/A4-security-hardening.mdnew file mode 100644index 000000000..b9ea31ec1--- /dev/null+++ b/prompts/production-campaign/A-reliability/A4-security-hardening.md@@ -0,0 +1,92 @@+# A4 — Security Hardening++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** A2+(shares the `http.js` boundary where authz and headers attach).++## Why this matters for $1B+Trust is the whole valuation thesis, and security is its hard edge. One leaked server key in the+client bundle, one endpoint that lets user A move user B's funds, one CSRF hole on a state-changing+route — any of these is a single-incident, reputation-ending event for a platform that holds money+and wallets. `00b-the-bar.md` §4: "No secrets in the client. Every API key lives server-side behind+a proxy. Grep the built client bundle for key patterns as part of done." This prompt makes the+attack surface boring.++## Current state (read before you write)+- `api/_lib/http.js` already sets `x-content-type-options: nosniff`, `x-frame-options: DENY`,+ `referrer-policy: strict-origin-when-cross-origin` on responses — a base to build CSP and the+ rest on. `api/csrf-token.js` + `api/_lib/csrf.js` exist. `api/_lib/auth.js`, `_lib/account-auth.js`,+ `_lib/siwe.js`, `_lib/siws.js`, `_lib/siwx-server.js`, `_lib/zauth.js`, `_lib/privy.js`,+ `_lib/saml.js` cover auth; `src/auth/` (email-auth, walletconnect-bridge) the client side.+- `api/_lib/ssrf-guard.js` / `_lib/ssrf.js`, `_lib/secret-box.js`, `_lib/pii.js`,+ `_lib/moderation.js`, `_lib/granite-guardian.js` exist. Security docs: `docs/security/SECURITY_AUDIT.md`,+ `SECURITY_REMEDIATION.md`.+- **The gap:** CSRF and auth helpers exist but aren't provably applied on **every** state-changing+ and money/auth route; there is no committed proof that **no server secret reaches the client+ bundle**; there is no platform-wide **CSP**; per-endpoint **authorization** (does this identity own+ this resource?) is uneven. Read the helpers and the route list — verify, don't assume.++## Your mission+### 1. Grep the BUILT bundle for secrets — and gate it+Build the client (read how the repo builds; do **not** run `npx vercel build`, which corrupts+`api/*.js` — use the documented `vite`/`build:*` path) and grep the output for key patterns+(`sk-`, `SENTRY_DSN` if private, RPC keys, Privy/Helius/Birdeye/ElevenLabs/OpenAI/Anthropic keys,+`PRIVATE_KEY`, JWT secrets, `process.env.*` leaks). Any hit is a leaked secret — move it behind a+server proxy. Add a committed scanner (a script A5 wires into CI) that fails the build on a future+leak. This is a hard gate, not advisory.++### 2. CSRF on every state-changing route+Confirm `api/csrf-token.js` issues and `_lib/csrf.js` verifies a token, then enforce verification on+**every** POST/PUT/PATCH/DELETE that isn't a signature-authenticated API (where the wallet signature+is the CSRF defense). Cross-check against A2's `docs/API_AUDIT.md` matrix — add a "CSRF ✓" column.+No state-changing browser route may be unprotected.++### 3. Per-endpoint authorization — ownership checks everywhere+Validation (A2) proves the input is well-formed; authorization proves *this caller may do this*. Audit+every endpoint that reads or mutates a user-owned resource (wallet, agent, build, billing, world,+launch) and add an ownership/role check: the authenticated identity must own (or be permitted on) the+target. An IDOR — user A reading/moving user B's wallet by changing an ID — must be impossible. Use the+existing auth/identity helpers; centralize a `requireOwner`/`requireAuth` guard so it's consistent.++### 4. Security headers + a real CSP+Extend the `http.js` header block (additively — A2 owns the file's structure) and the HTML/static+layer with a real Content-Security-Policy (script/style/connect/img/font sources scoped to what the+app actually loads — no blanket `unsafe-inline` for scripts where avoidable), plus `Strict-Transport-Security`,+`Permissions-Policy`, and `Cross-Origin-Opener/Resource-Policy` where appropriate. Test that the CSP+doesn't break Three.js, wallet SDKs, or the existing pages — tighten iteratively, don't ship a CSP+that white-screens a surface.++### 5. Abuse prevention + secret hygiene+Layer on top of A2's rate limits: bot/abuse heuristics on the expensive, money-adjacent, and+auth-bruteforceable routes (login, mint, send, generation). Confirm secrets are read only via+`_lib/env.js`/`_lib/secret-box.js` server-side, never logged (coordinate with A1 so logged fields are+scrubbed of PII/secrets), and rotated-friendly. Verify SSRF guards cover every server-side fetch of a+user-supplied URL.++### 6. Update the security audit ledger+Turn `docs/security/SECURITY_AUDIT.md` into a current, accurate map: bundle-secret scan result, CSRF+coverage, authz coverage, CSP policy, abuse controls, SSRF coverage, open items with owners. This is+the document an external auditor (and Track G) reads.++## Definition of done+Clears `00b-the-bar.md` §4 security clauses: a committed scan proves **zero** server secrets in the+client bundle and gates future leaks; CSRF enforced on every state-changing browser route; an ownership+check on every user-owned-resource endpoint (no IDOR); a real CSP + security headers live without+breaking any surface; abuse controls on auth/money/generation routes; SSRF guarded on every user-URL+fetch. `docs/security/SECURITY_AUDIT.md` reflects reality. Inherits the global definition of done in+`00-README-orchestration.md`.++## Operating rules (override defaults)+No mocks/fake data/placeholders/TODOs/stubs. `$THREE` is the only coin. Design tokens only for any UI.+Stage explicit paths only (never `git add -A`); re-check `git diff --staged` before commit. **Do NOT+run `npx vercel build`** (it bundles `api/*.js` — `head -1` check before any `api/` commit). You own+`api/csrf-token.js`, `_lib/csrf.js`, `_lib/auth.js`, `src/auth/`, the header/CSP block in `http.js`+(additive — A2 owns structure), and `docs/security/`. Reuse existing auth/SSRF/secret helpers; don't+rewrite working auth flows.++## When finished+Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. a CSP report-only collector that+feeds A1, or auth-bruteforce lockout). Append a `data/changelog.json` entry (tag: `security`) — visible+trust signals matter to holders. Then delete this prompt file+(`prompts/production-campaign/A-reliability/A4-security-hardening.md`) and report the bundle-scan result,+the CSP policy shipped, any route you found unauthorized and fixed, and the scanner seam A5 should gate.diff --git a/prompts/production-campaign/A-reliability/A5-test-coverage-ci-gate.md b/prompts/production-campaign/A-reliability/A5-test-coverage-ci-gate.mdnew file mode 100644index 000000000..91084ba47--- /dev/null+++ b/prompts/production-campaign/A-reliability/A5-test-coverage-ci-gate.md@@ -0,0 +1,89 @@+# A5 — Test Coverage & CI Gate++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** A2,+A3, A4 (their new code is what you must cover; their audit ledgers are your test checklists).++## Why this matters for $1B+Reliability that isn't enforced by CI is reliability that regresses on the next deploy. A1–A4 can+make the platform correct today; only a green, enforced gate keeps it correct tomorrow. The $1B+distinction is a platform where a money/auth/3D regression **cannot ship** — the build fails first.+A flaky suite is as bad as no suite: it trains everyone to ignore red, and then a real failure slips+through. This prompt turns the test surface into a trustworthy gate.++## Current state (read before you write)+- 219 specs under `tests/` (`*.test.js`). `vitest.config.js` and `playwright.config.js` configure+ unit + browser tests; `npm test` drives a real browser via Playwright and includes specs that need+ live DB/RPC credentials.+- `scripts/test-gate.mjs` runs a **curated, offline-safe subset** ("money-path confirmation handling,+ the HTTP cache/error boundary, custody spend guards, payment verification") so a regression in those+ FAILS THE DEPLOY. Its header explicitly invites adding new money/auth invariant tests.+- `.github/workflows/ci.yml` runs: Lint (`eslint`), Unit tests (`vitest run`), Source guards+ (`check-api-not-bundled`, `check:images`, `build:pages`), Typecheck (advisory). **It does NOT run+ `scripts/test-gate.mjs`, Playwright, or coverage thresholds.**+- **The gap:** coverage on money/auth/3D paths is unmeasured; flakes are unaddressed; the curated gate+ exists but isn't enforced in CI as the merge-blocking checkpoint; there are no coverage budgets.++## Your mission+### 1. Measure coverage, then raise it on the paths that matter+Turn on vitest coverage (v8/istanbul) and read the real numbers. Set **enforced** thresholds — not a+blanket global, but a meaningful floor on the critical lanes: money paths (A3's inventory),+auth/authz (A4), and the 3D pipeline (`src/glb-canonicalize.js`, `src/animation-retarget.js`,+forge/avatar flows). Write the missing tests to clear the floor. Cover the A2 boundary helpers+(envelope, validation, idempotency, rate-limit) and the A4 guards (CSRF, ownership, bundle-secret+scan) directly.++### 2. Make the money/auth/3D specs gate-grade and offline-safe+Extend `scripts/test-gate.mjs` to include the new A3/A4 invariant tests (double-submit idempotency,+confirm-failure "funds safe", concurrent cap, IDOR/authz rejection) — keeping every gate test+green-offline (no live DB/RPC/browser), per its own header rule. The gate is the fast, deterministic+checkpoint; the heavy suite stays in `npm test`.++### 3. Eliminate flakes — root-cause, don't retry-paper-over+Find the flaky specs (run the suite repeatedly; look for time/order/network nondeterminism). Fix the+cause: fake timers for time-dependent logic, deterministic seeds, awaited async, isolated state,+stable Playwright selectors (`getByRole`/test-ids, not brittle CSS) and proper auto-waiting instead of+arbitrary `waitForTimeout`. A test that's green 100/100 runs or it's deleted/fixed — no `retry: 3`+masking real instability on money/auth paths.++### 4. Enforce `test:gate` (and Playwright) in CI+Wire `scripts/test-gate.mjs` into `.github/workflows/ci.yml` as a **required**, merge-blocking job.+Add a Playwright job for the critical e2e flows (first-run Forge free lane, wallet connect, an x402+checkout dry path, the status page) — run it headless with the right browser deps, artifact traces on+failure. Append jobs additively; **A6 also edits `ci.yml`** for Lighthouse — coordinate, don't reformat+the file, stage explicit hunks.++### 5. Cover the new code from A2/A3/A4 explicitly+Walk A2's `docs/API_AUDIT.md` and A4's `docs/security/SECURITY_AUDIT.md` as checklists: each+"validated/rate-limited/idempotent/CSRF/authz ✓" claim should have a test that proves it. Where a claim+has no test, write one or correct the ledger. The audit and the tests must agree.++### 6. Document the testing contract+Add/refresh a short `docs/ops/testing.md` (or extend an existing testing doc): what runs in the gate+vs. the full suite, how to add a gate-grade test, the coverage floors and where they're enforced, how+to debug a Playwright trace. So the next contributor keeps the gate green by default.++## Definition of done+The critical lanes (money, auth, 3D) meet an **enforced** coverage floor; A2/A3/A4's new logic has+direct tests that match their audit ledgers; flakes are root-caused (no retry-masking on money/auth);+`scripts/test-gate.mjs` and a Playwright critical-path job are **required, merge-blocking** in+`ci.yml`; the testing contract is documented. `00b-the-bar.md`'s "existing tests pass; new logic has+new tests; money/auth/3D paths covered" is enforced by machinery, not goodwill. Inherits the global+definition of done in `00-README-orchestration.md`. Note explicitly which specs need live credentials+and therefore live in the heavy suite, not the gate.++## Operating rules (override defaults)+No mocks of **our own** money/RPC logic — test the real code paths with offline-safe inputs; **no real+third-party mints in fixtures** (use `$THREE` or a synthetic placeholder). `$THREE` is the only coin.+Stage explicit paths only (never `git add -A`); re-check `git diff --staged` before commit. You own+`vitest.config.js`, `playwright.config.js`, `scripts/test-gate.mjs`, `tests/**`, and the test jobs in+`.github/workflows/ci.yml` (shared with A6 — append, don't reformat). Don't weaken a threshold to pass;+fix the code or write the test.++## When finished+Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. coverage trend artifact, or a+mutation-test smoke on the money path). No changelog entry unless something user-visible changed (CI is+an internal chore) — but if a flaky-bug fix changed real behavior, log it (tag: `fix`). Then delete this+prompt file (`prompts/production-campaign/A-reliability/A5-test-coverage-ci-gate.md`) and report the+coverage numbers before/after, the gate job names now blocking merge, and any flake you quarantined with+a follow-up needed.diff --git a/prompts/production-campaign/A-reliability/A6-performance-web-vitals.md b/prompts/production-campaign/A-reliability/A6-performance-web-vitals.mdnew file mode 100644index 000000000..eb68635bb--- /dev/null+++ b/prompts/production-campaign/A-reliability/A6-performance-web-vitals.md@@ -0,0 +1,85 @@+# A6 — Performance & Web Vitals++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** none —+this prompt owns its own lane and can run in parallel with A1–A5 (it shares only `ci.yml` with A5;+coordinate there).++## Why this matters for $1B+Performance is trust the user feels before they read a word. A 3D platform that ships a multi-MB GLB+on the critical path, janks on scroll, or shifts layout under the user's cursor reads as a prototype,+not a $1B product. `00b-the-bar.md` §2 sets the hard numbers: **LCP < 2.5s, CLS < 0.1, INP < 200ms on+a mid-tier mobile over 4G, on every primary surface**; 3D loads progressively; no FOUC. Speed is also+growth — every 100ms of LCP is activation lost. This prompt makes the numbers real and keeps them real.++## Current state (read before you write)+- `.lighthouserc.json` already exists. `scripts/optimize-glb.mjs` and `scripts/compress-glbs.mjs`+ exist for asset compression. `inject-theme-boot.mjs` boots the theme before paint (the status page+ and others already inline the theme-boot script — no-flash is partly solved).+- `.github/workflows/ci.yml` runs lint/vitest/source-guards/typecheck but **does not run Lighthouse**.+- Three.js powers the 3D surfaces (Forge, avatar presence, viewers). It's heavy; verify how/where it's+ imported and whether it's on the critical path of pages that don't need it immediately.+- **The gap:** Core Web Vitals are not measured or budgeted in CI; `.lighthouserc.json` is unenforced;+ GLB compression isn't proven applied to shipped assets; Three.js lazy-loading and GPU disposal are+ inconsistent. Read the actual import graph and asset sizes before optimizing — measure first.++## Your mission+### 1. Wire Lighthouse CI as an enforced gate with real budgets+Flesh out `.lighthouserc.json` with assertions that enforce the §2 budgets (LCP < 2.5s, CLS < 0.1,+INP < 200ms — plus TBT/total-byte-weight guards) on the **primary surfaces** (home, Forge, an agent+profile, the marketplace, the status page). Add a Lighthouse job to `.github/workflows/ci.yml` that runs+on a mobile/4G throttle profile and **fails the build** when a budget regresses. Append the job+additively — **A5 also edits `ci.yml`** (test jobs); coordinate, don't reformat, stage explicit hunks.++### 2. Lazy-load Three.js and every heavy module off the critical path+Trace the Three.js import graph. Any surface that doesn't render 3D above the fold must not pay for+Three.js in its initial bundle — dynamic-`import()` it on demand behind a real loading skeleton (not a+spinner, not a `setTimeout` fake). Same for other heavy deps (wallet SDKs, charting). Verify in the+network tab that the 3D chunk loads only when a 3D surface is actually entered.++### 3. Compress GLBs and load them progressively+Run `scripts/optimize-glb.mjs` / `scripts/compress-glbs.mjs` over the shipped GLB assets (draco/meshopt)+and confirm the size drop. No surface blocks on a multi-MB model: stream/lazy-load the GLB with a+skeleton that matches the final layout, and **dispose GPU resources on unmount** (geometries, materials,+textures, renderer) so navigating away doesn't leak memory or tank the next surface's frame rate.+Target 60fps on the avatar presence and no jank on scroll.++### 4. Kill layout shift and FOUC on every primary surface+Confirm theme/tokens/fonts resolve before content paints (build on `inject-theme-boot.mjs`); reserve+space for async content (images, 3D canvases, lists) with explicit dimensions/aspect-ratios so nothing+shifts; preload the critical font; set `font-display` sensibly. CLS < 0.1 means the page doesn't move+under the user — verify with the Lighthouse trace, not by eye.++### 5. Mobile performance pass+Test the budgets on a mid-tier mobile profile at 320px and 768px. Debounce input handlers, paginate long+lists, use `transform`/`will-change` for animations (and honor `prefers-reduced-motion`), avoid main-+thread-blocking work during interaction (INP). Defer non-critical third-party scripts. The first-run+path (`00b-the-bar.md` §5: value in < 60s) must be fast on a phone, not just a laptop.++### 6. Prove the numbers and hold them+Run Lighthouse on each primary surface before/after and record the LCP/CLS/INP deltas in your report.+The CI gate then holds them: a future PR that regresses a budget fails. Document the budgets and how to+read a failing Lighthouse run in `docs/ops/`.++## Definition of done+Clears `00b-the-bar.md` §2: every primary surface meets LCP < 2.5s, CLS < 0.1, INP < 200ms on a+mobile/4G profile, enforced by a **merge-blocking** Lighthouse CI job; Three.js and heavy modules are+lazy-loaded behind real skeletons; shipped GLBs are draco/meshopt-compressed with progressive load and+GPU disposal; no FOUC or layout shift on primary surfaces; mobile is fast at 320/768px. Before/after+numbers in the report. Inherits the global definition of done in `00-README-orchestration.md`.++## Operating rules (override defaults)+No mocks/fake data/placeholders/TODOs/stubs — **no `setTimeout` fake-loading or fake progress bars**;+real async with real skeletons only. `$THREE` is the only coin. Design tokens only (`public/tokens.css`)+for any skeleton/loading UI. Stage explicit paths only (never `git add -A`); re-check `git diff --staged`+before commit (watch the `npx vercel build` `api/*.js` bundling trap if you build). You own+`.lighthouserc.json`, the Lighthouse job in `ci.yml` (shared with A5 — append, don't reformat), the GLB+scripts, and the lazy-load wiring in `src/` 3D entry points. Don't rewrite working render code — extend+its loading/disposal.++## When finished+Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. a route-level prefetch of the 3D+chunk on hover, or an OG-image perf win). Append a `data/changelog.json` entry (tag: `improvement`) —+"the app got faster" is user-visible. Then delete this prompt file+(`prompts/production-campaign/A-reliability/A6-performance-web-vitals.md`) and report the before/after+Web Vitals per surface, the GLB size reductions, and any surface that can't yet hold a budget and why.diff --git a/prompts/production-campaign/C-surfaces/C3-launch-trading-surfaces.md b/prompts/production-campaign/C-surfaces/C3-launch-trading-surfaces.mdnew file mode 100644index 000000000..56be162dc--- /dev/null+++ b/prompts/production-campaign/C-surfaces/C3-launch-trading-surfaces.md@@ -0,0 +1,106 @@+# C3 — Launch & trading surfaces to the bar++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**+Track A reliability green (these surfaces show money/RPC/feed states it produces).++## Why this matters for $1B++These are the **money surfaces** — where users launch coins, read intel, follow traders, and+watch live trades. Trust is won or lost here: nobody launches a coin or follows a strategy+through software that 500s on an empty feed, shows a chart with no data and no explanation, or+leaves a "Launch" button that looks live but does nothing. Per the $1B thesis, a platform is+worth $1B when it is **trusted with money** — and trust on a trading surface is communicated+by every state being honest: real prices, real feed status, real "this didn't go through,+your funds are safe" recovery. Polish here is not cosmetic; it's the difference between a+tool people wire wallets to and one they bounce from.++## Surfaces in scope (the real pages)++- **Launch a coin:** `pages/launch.html` → `src/launch*`; detail `pages/launch-detail.html` →+ `src/launch-detail.js`; feed `pages/launches.html` → `src/launches.js`;+ `pages/bulk-launch.html`, `pages/autopilot.html` → `src/autopilot.js`+- **Launchpad studio:** `pages/launchpad.html`; launch-week `pages/three-ws-launch-week.html`+- **Coin intel / oracle / radar:** `pages/coin-intel.html`; `pages/oracle.html` →+ `src/oracle-graph.js`, `src/ibm-oracle.js`; `pages/radar.html` (coin radar)+- **Trader leaderboard / live trades:** `pages/trader.html`; `pages/leaderboard.html`;+ `pages/trades.html`; live feed `pages/live.html`, `pages/three-live.html`,+ `pages/pump-live.html`; `pages/smart-money.html`+- **Sniper arena:** `pages/play/arena.html`; sniper dashboard+ `pages/dashboard-next/sniper.html` (`/dashboard/sniper`) → `api/sniper/*`+- **Strategy lab / watchlist / activity:** `public/strategy-lab.html` (`/strategy-lab`);+ `pages/watchlist.html`; `pages/activity.html`+- **Claim wallet:** `pages/claim-wallet.html`+- **3D visualizer:** `pages/pump-visualizer.html`; `pages/scan.html`; `pages/arm.html` →+ `src/arm.js` (`/oracle/arm`)+- Data sources: `api/coin/*`, `api/sniper/*`, `api/oracle-share`, pump.fun feed, Solana RPC.++## Current state (read before you write)++These surfaces stream real data (pump.fun feed, Solana RPC, `api/coin/*`, `api/sniper/*`).+The gaps to find: **live feeds with no empty/connecting/disconnected state** (a blank list+while a websocket warms, no "reconnecting…" on drop); **charts that render nothing on no-data+without saying so**; **error states that swallow an RPC/feed failure** instead of offering+retry; **launch/claim CTAs whose pending/success/failure states aren't all designed** (this is+the money path — a failed tx must show "did not go through, funds safe"). Audit **overflow**:+a leaderboard of 1000 traders, a $0 and a $10M position, a 200-char coin name, a feed firehose.++## Your mission++### 1. Audit every surface for the five states — money paths included+**Loading** = skeleton rows/charts and honest connection status (no fake tickers). **Empty** =+a quiet, branded empty feed that explains what will appear and how to start (launch, add to+watchlist, follow a trader). **Error** = names the failure (feed down, RPC error, tx rejected)+and offers retry; money actions show an explicit safe-funds recovery state. **Populated** =+token-consistent rows/cards with microinteractions. **Overflow** = pagination/virtualization+for huge leaderboards and feeds, number/name truncation, extreme-value formatting ($0 → $10M).++### 2. Make live feeds honest and reconnecting+Live/trades/sniper streams must show connecting → live → reconnecting states from the **real**+socket/SSE status — never a frozen list that looks live. On drop, auto-retry with a visible+indicator. No `setTimeout` fake ticks.++### 3. Launch & claim CTA state machines+Every launch / bulk-launch / claim button has a full designed state machine wired to the real+API: idle → submitting → on-chain pending → confirmed (with the link) → failed (safe-funds+recovery). No button that looks live but no-ops. Confirm on-chain before claiming success.++### 4. Mobile, a11y, microinteractions+Charts, tables, and the 3D visualizer are usable at **320 / 768 / 1440px** (tables scroll or+reflow; the visualizer lazy-loads Three.js with a skeleton). Tables/feeds are+keyboard-navigable and screen-reader-labelled; live regions use `aria-live="polite"`. Honor+`prefers-reduced-motion`. Hover/active/focus on every control.++### 5. Dead-path elimination + design tokens+Every CTA does something real (launch, follow, add to watchlist, open detail, claim). Replace+hardcoded colors/spacing/fonts with `public/tokens.css` tokens. Wire cross-links: a coin in+the feed → coin-intel; a trader → their leaderboard profile; a launch → its 3D visualizer.++## Definition of done++Clears `00b-the-bar.md` §3 (five states, responsive, a11y), §1 (money paths idempotent with+honest failure states), §2 (lazy 3D, no jank on the feed firehose). Inherits the **global+definition of done** in `00-README-orchestration.md`: real APIs only, `$THREE` the only coin+the platform promotes, tokens only, verified in a browser at `npm run dev` with zero console+errors from your code and real network calls, existing tests pass (money/feed paths covered).+State which bars you cleared and how you verified each.++## Operating rules (override defaults)++No mocks / fake data / placeholders / TODOs / stubs / sample arrays / fake tickers. `$THREE`+(`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only coin the platform promotes; the+launch directory, coin-intel for a user-supplied mint, and agent launch history render+runtime user-launched mints and are the sole mechanical exception per `CLAUDE.md` — never+hardcode, market, or recommend a non-`$THREE` mint in source or copy. Design tokens only+(`public/tokens.css`). Stage explicit paths only (never `git add -A`); check `head -1` of any+`api/*.js` you touch for the `__defProp` bundle trap. Own **only the pages listed here**;+extend, don't rewrite, the shared nav/tokens.++## When finished++Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. a connection-quality+badge on live feeds, a $0/$10M-safe number formatter shared across tables, or a "copy this+trader's strategy" path into strategy-lab). Append a holder-readable `data/changelog.json`+entry if user-visible (`npm run build:pages` to validate). Then delete this prompt file+(`prompts/production-campaign/C-surfaces/C3-launch-trading-surfaces.md`) and report what you+shipped, which bars you cleared and how you verified them, and any seam for the next agent.diff --git a/prompts/production-campaign/C-surfaces/C4-agent-wallet-surfaces.md b/prompts/production-campaign/C-surfaces/C4-agent-wallet-surfaces.mdnew file mode 100644index 000000000..321c8e682--- /dev/null+++ b/prompts/production-campaign/C-surfaces/C4-agent-wallet-surfaces.md@@ -0,0 +1,100 @@+# C4 — Agent & wallet surfaces to the bar++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**+Track A reliability green (wallet/RPC error states it produces render here).++## Why this matters for $1B++This is the **logged-in home** — the wallet, the dashboard, the agents a user owns and earns+from. It's the surface a returning user sees daily, so it carries the **retention** and+**trust-with-money** pillars at once. A dashboard that shows a blank balance while RPC warms,+an agent list that's empty with no "create your first agent" path, or an edit form that loses+work on a network blip will quietly bleed the daily-active users a $1B valuation is built on.+The logged-in surface must feel as considered as the marketing pages — more, because this is+where money actually moves.++## Surfaces in scope (the real pages)++- **Agent wallet:** `pages/agent-wallet.html` → `src/agent-wallet.js`, `src/agent-wallet/`,+ `src/agent-wallet-hub/`; chat variant `pages/avatar-wallet-chat.html`+- **Dashboard:** `pages/dashboard-next/index.html` (`/dashboard`) → `src/dashboard/`,+ `src/dashboard-next/`; tabs: `dashboard-next/portfolio.html`, `holders.html`,+ `referrals.html`, `monetize.html`, `analytics.html` (audit the dashboard shell + its tabs)+- **Account:** `pages/dashboard-next/account.html` (`/dashboard/account`)+- **My agents:** `pages/dashboard-next/agents.html` (`/dashboard/agents`)+- **Agent detail / edit:** `pages/agent-detail.html` → `src/agent-detail.js`,+ `src/agent-detail-market.js`; `pages/agent-edit.html`+- **Agent economy / exchange / trade:** `pages/agent-economy.html` → `src/agent-economy.js`;+ `pages/agent-exchange.html` → `src/agent-exchange.js`; `pages/agent-trade.html` →+ `src/agent-trade.js`+- Data sources: `api/agents/*` (solana register/card/reputation/skills),+ `api/agents/[id]/*`, wallet/balance endpoints, `api/discover-detail.js`.++## Current state (read before you write)++These pages render real wallet balances, agent metadata, and economy data. The gaps to find:+**balance/portfolio loading** that shows `0` or blank before RPC resolves (must skeleton, then+show real value); **empty agent list** with no onboarding path ("create your first agent");+**edit forms** with no dirty-state guard, no inline validation, and no save-failure recovery;+**error states** that swallow an RPC/API failure. Audit **overflow**: a wallet with $0 and one+with $10M, an agent with a 200-char name, a portfolio of 1000 holdings, an account with no+connected wallet at all.++## Your mission++### 1. Audit every surface for the five states — auth-aware+**Loading** = skeletons for balance, portfolio, agent cards (no flash of `0`). **Empty** =+designed onboarding: no agents → "create your first agent" with a CTA into the studio; no+wallet → a clear connect/claim path. **Error** = names the failure (RPC down, save failed) and+recovers. **Populated** = token-consistent, with microinteractions. **Overflow** = $0/$10M+formatting, long names, big portfolios, the not-signed-in state on every gated surface.++### 2. Harden the edit/account forms+`agent-edit` and `account` get real inline validation at the boundary, a dirty-state guard+(warn before navigating away from unsaved edits), an honest saving → saved → failed state+machine wired to the real API, and a save-failure path that preserves the user's input. No+silent loss of work.++### 3. Wallet & economy correctness in the UI+Balances, P&L, and economy numbers format correctly across the full range ($0 → $10M),+show their source-freshness, and never display a stale value as live. The not-signed-in state+on every gated surface routes to auth, not a blank page.++### 4. Mobile, a11y, microinteractions+Dashboard, wallet, and detail layouts work at **320 / 768 / 1440px** (cards stack, tables+reflow or scroll). Forms and tab navigation are fully keyboard-operable with labelled inputs+and visible focus rings; balance updates announced via `aria-live`. Honor+`prefers-reduced-motion`. Hover/active/focus on every control.++### 5. Dead-path elimination + design tokens+Every dashboard tab, agent CTA, and wallet action does something real. Replace hardcoded+colors/spacing/fonts with `public/tokens.css` tokens. Wire cross-links: an owned agent →+its public profile/detail; the economy → the exchange/trade surface; account → claim/SNS.++## Definition of done++Clears `00b-the-bar.md` §3 (five states, responsive, a11y), §1 (no fund-related action+without an honest failure state), §4 (inputs validated at the boundary). Inherits the+**global definition of done** in `00-README-orchestration.md`: real APIs only, `$THREE` the+only coin, tokens only, verified in a browser at `npm run dev` (signed-in and signed-out) with+zero console errors from your code and real network calls, existing tests pass (auth/wallet+paths covered). State which bars you cleared and how you verified each.++## Operating rules (override defaults)++No mocks / fake data / placeholders / TODOs / stubs / sample arrays. `$THREE`+(`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only coin — agent launch history and+the economy render runtime user-launched mints and are the sole mechanical exception per+`CLAUDE.md`. Design tokens only (`public/tokens.css`). Stage explicit paths only (never+`git add -A`); check `head -1` of any `api/*.js` you touch for the `__defProp` bundle trap.+Own **only the pages listed here**; extend, don't rewrite, the shared nav/tokens.++## When finished++Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. a dirty-state guard+shared by all forms, a unified $0/$10M number formatter, or a one-click "create your first+agent" empty state on `/dashboard/agents`). Append a holder-readable `data/changelog.json`+entry if user-visible (`npm run build:pages` to validate). Then delete this prompt file+(`prompts/production-campaign/C-surfaces/C4-agent-wallet-surfaces.md`) and report what you+shipped, which bars you cleared and how you verified them, and any seam for the next agent.diff --git a/prompts/production-campaign/C-surfaces/C5-worlds-clash-social-surfaces.md b/prompts/production-campaign/C-surfaces/C5-worlds-clash-social-surfaces.mdnew file mode 100644index 000000000..58dd0648e--- /dev/null+++ b/prompts/production-campaign/C-surfaces/C5-worlds-clash-social-surfaces.md@@ -0,0 +1,101 @@+# C5 — Worlds, clash & social surfaces to the bar++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** none+(Track A reliability green so live/multiplayer error states render real).++## Why this matters for $1B++Worlds, clash, the club, and communities are the **come-back-tomorrow** surfaces — the social+and real-time layer that turns a one-time generation into a habit. These are the most+heavily-3D, most live pages on the platform, so they carry both the **retention** pillar and+the hardest **performance** bars: a world that drops frames, a club that loads on a multi-MB+GLB with no skeleton, or a clash with no "waiting for players" state reads as broken, and a+broken social surface kills the network effect a $1B platform compounds on. These are also the+most shareable moments — every one must screenshot well and unfurl with an OG card.++## Surfaces in scope (the real pages)++- **Coin clash:** `pages/clash.html` → `src/clash.js`, `src/clash.css` → `api/clash/*`+- **Worlds:** `pages/worlds.html` → `src/worlds*`+- **City:** `pages/city.html` → `src/city/`+- **Club (3D venue):** `pages/club.html` → `src/club.js`, `src/club-venue.js`,+ `club-crowd.js`, `club-camera.js`, `club-audio.js`, `club-entrance.js`, `club-gate.js`,+ `club-sequence.js`, `club-perf.js` → `api/club/*`+- **Community / communities:** `pages/community.html`, `pages/communities.html` →+ `src/community/` → `api/community/*`+- **Bounties:** `pages/bounties.html` → `src/bounties.js`; detail `pages/bounty.html`+- Data sources: `api/clash/*`, `api/club/*`, `api/community/*`, and the live/multiplayer+ signaling these surfaces use.++## Current state (read before you write)++These are real-time 3D surfaces backed by `api/clash/*`, `api/club/*`, `api/community/*`.+The gaps to find: **3D scenes that block on asset load** with no progressive skeleton; **live+states** (waiting for opponents, empty club, lobby filling) that show nothing instead of a+designed "waiting" state; **error/disconnect** handling when signaling or an upstream drops;+**empty communities/bounties** lists with no "start one / be the first" path. The club's perf+module (`src/club-perf.js`) exists — confirm it actually holds frame rate and degrades quality+gracefully on weak devices rather than janking. Audit **overflow**: a clash with 0 vs many+entrants, a bounty list of 1000, a 200-char community name, a packed vs empty venue.++## Your mission++### 1. Audit every surface for the five states — real-time aware+**Loading** = progressive 3D load with a real skeleton/loading scene, never a frozen black+canvas. **Empty** = designed "waiting for players / empty venue / no bounties yet" states that+explain what happens next and offer an action (invite, start a bounty, enter the club).+**Error** = names a disconnect/upstream failure and offers reconnect/retry. **Populated** =+token-consistent HUD/overlays with microinteractions. **Overflow** = 0/1/1000 entrants,+bounties, community members; long names; full vs empty venue.++### 2. Make the 3D load honestly and hold frame rate+Lazy-load Three.js and scene assets, show a real loading skeleton/scene, draco/meshopt where+applicable, and **dispose GPU resources on exit/scene-change**. Verify `club-perf.js` actually+degrades quality on weak hardware to hold ~60fps; no jank on the avatar/crowd presence.++### 3. Real-time connection states+Clash and club show connecting → connected → reconnecting from the **real** signaling status,+with a visible reconnect path on drop. No frozen lobby that looks live. No `setTimeout`-faked+"finding opponent" — wire it to the real matchmaking/feed.++### 4. Mobile, a11y, microinteractions+2D overlays/HUD/lists usable at **320 / 768 / 1440px**; the 3D canvas degrades gracefully or+offers a 2D fallback on low-power mobile. Overlays are keyboard-reachable and+screen-reader-labelled; the 3D canvas has an ARIA label and a non-3D way to read state. Honor+`prefers-reduced-motion` (calm the camera/crowd motion). Hover/active/focus on every control.++### 5. Dead-path elimination + design tokens + shareability+Every CTA (enter clash, join club, claim bounty, open community) does something real. Replace+hardcoded colors/spacing/fonts with `public/tokens.css` tokens. Ensure each shareable moment+(a clash result, a bounty, a community) has a working share action / OG card and links to its+detail. Wire cross-links: a community → its members' agent profiles; a bounty → the agent+that can fulfill it.++## Definition of done++Clears `00b-the-bar.md` §3 (five states, responsive, a11y), §2 (progressive 3D, 60fps, GPU+disposal, no FOUC). Inherits the **global definition of done** in+`00-README-orchestration.md`: real APIs only, `$THREE` the only coin, tokens only, verified in+a browser at `npm run dev` with zero console errors from your code and real network calls,+existing tests pass. State which bars you cleared and how you verified each (the frame rate,+the disconnect recovery, the empty-venue screenshot).++## Operating rules (override defaults)++No mocks / fake data / placeholders / TODOs / stubs / sample arrays / faked matchmaking.+`$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only coin — clash/community+surfaces that render user-launched coins use the runtime user-launch exception per `CLAUDE.md`;+never hardcode or recommend a non-`$THREE` mint. Design tokens only (`public/tokens.css`).+Stage explicit paths only (never `git add -A`); check `head -1` of any `api/*.js` you touch+for the `__defProp` bundle trap. Own **only the pages listed here**; extend, don't rewrite,+the shared nav/tokens.++## When finished++Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. a shared 3D-scene+loading skeleton, a low-power 2D fallback for the club, or a "be the first" empty state on+communities/bounties). Append a holder-readable `data/changelog.json` entry if user-visible+(`npm run build:pages` to validate). Then delete this prompt file+(`prompts/production-campaign/C-surfaces/C5-worlds-clash-social-surfaces.md`) and report what+you shipped, which bars you cleared and how you verified them, and any seam for the next agent.diff --git a/prompts/production-campaign/C-surfaces/C6-learn-chat-pay-surfaces.md b/prompts/production-campaign/C-surfaces/C6-learn-chat-pay-surfaces.mdnew file mode 100644index 000000000..f07d2a892--- /dev/null+++ b/prompts/production-campaign/C-surfaces/C6-learn-chat-pay-surfaces.md@@ -0,0 +1,106 @@+# C6 — Learn, chat & pay surfaces to the bar++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** none.++## Why this matters for $1B++Docs, tutorials, the glossary, and "what is three.ws" are the **onboarding and ecosystem**+surfaces — the pages that turn a curious visitor into a user and a user into a builder. Per+the $1B thesis, an outside developer must go from zero to a working integration in 10 minutes+using these pages; a docs surface with a dead anchor, a broken copy-button, or no search reads+as an abandoned project. Chat is the conversational front door (the talking page guide, the+avatar chat); pay is a **money surface** where x402/$THREE payments settle — a payment page+with an undesigned pending/failed state is a trust leak on the most sensitive interaction+there is. These pages must be the most polished on the platform, because they set expectations+for everything else.++## Surfaces in scope (the real pages)++- **Docs:** `/docs` → `docs/index.html` (and the docs sub-pages it links) — the developer+ reference and quickstart+- **Tutorials:** `pages/tutorials.html`; single tutorial `pages/tutorial.html`+- **Chat:** `/chat` → `chat/index.html` → `api/chat.js` (and `api/chat/proxy.js`,+ `api/brain/chat.js`); avatar chat `pages/avatar-wallet-chat.html`+- **Pay:** `/pay` → `public/pay/index.html` → x402 / payment endpoints+ (`api/x402-checkout`, `public/x402.js`, `public/x402-pay-core.js`)+- **Avatar SDK page:** `pages/avatar-sdk.html` — the SDK landing/quickstart+- **Glossary:** `pages/glossary.html` → `src/glossary/`+- **What is three.ws:** `pages/what-is.html`+- **AR:** `pages/ar.html` → `src/forge-ar.js` (AR view-in-space surface)+- Data sources: `api/chat.js`, the x402/payment endpoints, the docs/tutorial content.++## Current state (read before you write)++Docs/tutorials/glossary/what-is are largely static content; chat and pay are live. The gaps to+find: **docs/tutorials** missing on-page search, a working copy-to-clipboard on every code+block, anchor links that all resolve, a "you're on the latest" freshness signal, and a+designed 404/empty for a missing doc; **chat** missing a streaming-response state, an empty+"start the conversation" state, a typing indicator from the **real** stream (no `setTimeout`+fake typing), and an error/retry on a failed `api/chat.js` call; **pay** missing a full+payment state machine (idle → awaiting signature → settling → settled → failed-with-recovery)+and an honest "did not go through, funds safe" state. Audit **overflow**: a 200-message chat,+a doc page with a huge code block, a glossary of 1000 terms, a payment for $0.000001 vs a+large amount.++## Your mission++### 1. Audit every surface for the five states+**Loading** = skeleton for docs/chat history; honest streaming status for chat; real awaiting+state for pay. **Empty** = "start the conversation" for chat, a "search the docs / popular+guides" for an empty docs landing, a designed "nothing here yet" for a missing tutorial.+**Error** = chat/pay failures named in plain language with retry; a designed docs 404.+**Populated** = token-consistent typography and code styling with microinteractions.+**Overflow** = long chats, huge code blocks, big glossaries, tiny-to-large payment amounts.++### 2. Make docs and tutorials a 10-minute on-ramp+Every code block has a working copy button; every anchor/cross-link resolves (no dead+fragments); add on-page search/filter to the glossary and docs if absent; surface a clear+quickstart path from the avatar-sdk page into the docs. This maps to `00b-the-bar.md` §6 —+zero-to-integration in 10 minutes.++### 3. Chat: honest streaming and recovery+Wire the chat UI to the **real** `api/chat.js` stream — a real typing/streaming indicator,+token-by-token render where supported, an empty starter state with example prompts, and an+error/retry on stream failure. No faked typing, no spinner that never resolves.++### 4. Pay: a complete, honest payment state machine+The pay surface gets a full state machine on the **real** x402/payment flow: idle → awaiting+signature → settling → settled (with receipt/link) → failed (with a "funds safe, here's what+happened" recovery). Confirm settlement before claiming success. `$THREE` and x402 USDC are+the only payment rails referenced.++### 5. Mobile, a11y, microinteractions, tokens+All four surfaces work at **320 / 768 / 1440px** (docs nav collapses, code blocks scroll, chat+composer stays reachable above the keyboard). Full keyboard nav, labelled inputs, `aria-live`+for chat/pay status, focus management on the chat composer, contrast ≥ WCAG AA. Honor+`prefers-reduced-motion`. Replace hardcoded colors/spacing/fonts with `public/tokens.css`+tokens; every interactive element gets hover, active, and focus states.++## Definition of done++Clears `00b-the-bar.md` §3 (five states, responsive, a11y), §6 (10-minute on-ramp from docs),+§1 (pay path idempotent with honest failure recovery). Inherits the **global definition of+done** in `00-README-orchestration.md`: real APIs only, `$THREE` the only coin, tokens only,+verified in a browser at `npm run dev` with zero console errors from your code and real+network calls (real chat stream, real payment flow), existing tests pass (the+`x402-checkout` tests included). State which bars you cleared and how you verified each.++## Operating rules (override defaults)++No mocks / fake data / placeholders / TODOs / stubs / sample arrays / faked typing or progress.+`$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only coin — never name another+token in docs, glossary, copy, or examples; x402 USDC is a payment rail, not a promoted coin.+Design tokens only (`public/tokens.css`). Stage explicit paths only (never `git add -A`); check+`head -1` of any `api/*.js` you touch for the `__defProp` bundle trap (the `api/x402-checkout`+and `public/x402*.js` files are live — review their diffs carefully). Own **only the pages+listed here**; extend, don't rewrite, the shared nav/tokens.++## When finished++Run `CLAUDE.md`'s five self-review checks. Ship one improvement (e.g. on-page docs search, a+shared copy-button component, or example prompts on the empty chat state). Append a+holder-readable `data/changelog.json` entry if user-visible (`npm run build:pages` to+validate). Then delete this prompt file+(`prompts/production-campaign/C-surfaces/C6-learn-chat-pay-surfaces.md`) and report what you+shipped, which bars you cleared and how you verified them, and any seam for the next agent.diff --git a/prompts/production-campaign/D-monetization/00-README.md b/prompts/production-campaign/D-monetization/00-README.mdnew file mode 100644index 000000000..14bbe9980--- /dev/null+++ b/prompts/production-campaign/D-monetization/00-README.md@@ -0,0 +1,58 @@+# Track D — Monetization & $THREE Economy++**Goal:** turn users into **real, reconciled revenue**. Not pricing pages that don't bill,+not paid endpoints that don't settle, not "holder perks" that mean nothing on the page next+door. Every dollar this track touches is quoted to the user, charged on a real rail, settled+on-chain or through a real processor, and **reconciled** against a ledger you can audit. The+$1B thesis pillar this owns is *monetization depth*: revenue × multiple = valuation, and a+multiple only exists when the revenue is real and the books balance.++The platform already has the bones: holder tiers (`api/_lib/three-tier.js`,+`three-access.js`), a fee module (`api/_lib/fee.js`, `marketplace-platform-fee.js`), royalty+ledger (`api/_lib/royalty.js`), payouts (`api/_lib/payout.js`, `api/billing/`), an x402+catalog at `/.well-known/x402.json` (`api/wk.js`), and ~28 paid endpoints under `api/x402/`.+This track **completes and connects** them — it does not rewrite the payment plumbing.++**The only coin is `$THREE`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). It appears+nowhere as a recommendation outside that one address; no other token appears anywhere — code,+copy, tests, fixtures. Runtime user-launch mints are the sole mechanical exception (CLAUDE.md).++---++## Prompts++| # | File | Mission (one line) |+|---|---|---|+| **D1** | `D1-three-holder-value-system.md` | One $THREE-holder value system — balance → tier → perks → upgrade path — applied identically on every gating surface. Foundational. |+| **D2** | `D2-billing-pricing-metering.md` | Real billing: a pricing surface, usage metering, invoices/receipts, and the AWS Marketplace metering + entitlement path. Real charges, real reconciliation. |+| **D3** | `D3-x402-paid-endpoints-network.md` | Complete and verify the x402 paid-endpoint network + discovery indexing (CDP Bazaar / x402scan / 402index). Every paid endpoint quotes price, settles USDC, is discoverable. |+| **D4** | `D4-marketplace-economics.md` | Marketplace economics: platform fees, creator royalties, payment splits (@0xsplits/splits-sdk), creator payouts, on-chain skill licenses. Trustless where possible. |++## Run order++```+D1 (holder value system) ← FOUNDATIONAL. Run first.+ │ one helper, one tier ladder, one upgrade UX — everything else gates and prices off it+ ├── D2 (billing / pricing / metering) ← consumes D1 tier discounts in the priced ledger+ ├── D3 (x402 paid network + discovery) ← consumes D1 tier discounts at quote time+ └── D4 (marketplace economics) ← consumes D1 tiers for creator perks; D2 ledger for payouts+```++D1 is the gate: it establishes the single tier ladder, the single balance/tier helper, and+the single upgrade UX that D2's pricing, D3's quotes, and D4's creator perks all reference.+Run D1 to completion first. D2–D4 may then run in parallel; each reads D1's contracts, never+forks its own copy of "what does holding $THREE get you."++## File-ownership map++Stage explicit paths only — never `git add -A`. Shared files (`data/changelog.json`) are+append-only. Lanes:++| Prompt | Owns (edit freely) | Reads / extends (do not rewrite) |+|---|---|---|+| **D1** | `api/_lib/three-tier.js`, `three-access.js`, `three-gate.js`, a shared client gate module under `public/`, the `/account`-tier surface | `forge-tiers.js`, `holder-pass.js`, `balances.js` |+| **D2** | `api/billing/*`, a pricing page under `pages/`, `api/aws-marketplace/*`, a metering/entitlement lib in `api/_lib/` | `api/_lib/fee.js`, `api/config.js`, D1's tier helper |+| **D3** | `api/x402/*`, `api/wk.js`, `.well-known/x402.json` build path, `scripts/verify-x402-discovery.mjs`, a registration script | `public/x402*.js`, `api/x402-checkout.js`, D1's tier helper |+| **D4** | `api/_lib/royalty.js`, `payout.js`, `marketplace-platform-fee.js`, a splits lib in `api/_lib/`, `contracts/skill-license/*`, `api/_lib/skill-license-onchain.js`, `api/creators/*` | D1's tier helper, D2's ledger |++When this directory contains only `00-README.md`, Track D is done.diff --git a/prompts/production-campaign/D-monetization/D1-three-holder-value-system.md b/prompts/production-campaign/D-monetization/D1-three-holder-value-system.mdnew file mode 100644index 000000000..cf2c64f20--- /dev/null+++ b/prompts/production-campaign/D-monetization/D1-three-holder-value-system.md@@ -0,0 +1,107 @@+# D1 — One $THREE-Holder Value System, Everywhere++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:** none+— this is the foundation D2/D3/D4 price and gate against.++## Why this matters for $1B++Holding $THREE is the platform's deflation-free status lever: hold (don't spend) to unlock+perks. That promise is only worth a multiple if it is **consistent** — the same balance must+mean the same tier, the same perks, the same discount, on every surface that gates on it.+Today Forge gates "High quality" on holders but the tier ladder, the perk copy, the upgrade+path, and the balance check live in separate places and are wired into exactly one surface.+A holder who sees a "Silver perk" on one page and a dead "for holders only" string on another+does not believe the token has value — and a token nobody believes in has no market cap to+multiply. One helper, one UX, everywhere is what makes the economy legible.++## Current state (read before you write)++- `api/_lib/three-tier.js` — the **source of truth**: the `TIERS` ladder (Member → Bronze →+ Silver → …), `minUsd` thresholds, `discountBps`, `rateMultiplier`, perks, and the signed+ tier pass (`signTierPass`/`verifyTierPass`) the multiplayer server verifies. Resolves a+ tier from the live USD value of $THREE held; degrades to Member on a price/RPC hiccup.+- `api/_lib/three-access.js` — `featureId → { minLevel, enforced, label, why, payPerUse }`+ registry + `resolveAccess(user, featureId)` (async, for display) and `accessFromTierLevel`+ (pure, for enforcement). This is the platform-wide access table — but inventory it: how many+ real `featureId`s are registered vs. how many surfaces actually gate?+- `api/_lib/three-gate.js` — raw on-chain balance check (`checkThreeBalance`), fails **open**.+- `api/_lib/holder-pass.js` — the per-coin world-entry pass; `balances.js` — wallet balances.+- `api/_lib/forge-tiers.js` — Forge's quality tiers; the one surface that gates today.+- **The gap:** the ladder and access table exist server-side, but there is no single **client**+ module that every page imports to (1) read the user's tier, (2) render the same tier badge ++ perk list, (3) gate an affordance with a consistent locked state, and (4) route to one+ upgrade path. Each surface that wants to gate re-implements the check and the copy.++## Your mission++### 1. Lock the tier ladder + access registry as the single source of truth+Audit `TIERS` in `three-tier.js` for completeness (every tier has perks, a `discountBps`, a+`rateMultiplier`, and reachable, sensible `minUsd` thresholds). Inventory `three-access.js`:+register a `featureId` for **every** surface that should gate on holding — Forge high quality+(exists), private/branded worlds, priority MCP routing, higher free quotas, early-access pages.+Each entry needs honest `label`/`why` copy a holder reads in the UI. No invented perks that+aren't wired — if you register it, the gating surface honors it in this PR or a sibling prompt.++### 2. Ship ONE client holder-value module — `public/three-tier-client.js`+A single ES module every gating surface imports. It must:+- Resolve the signed-in user's tier from a real endpoint (extend/confirm an+ `api/account/tier` or `api/three/access` endpoint that returns `{ tier, usdHeld, nextTier,+ usdToNext, perks }` from `resolveUserTier`). No client-side balance math — server is truth.+- Export `renderTierBadge(el, tier)`, `gateAffordance(el, { featureId, onUnlock })`, and+ `requireTier(featureId)` returning `{ allowed, tier, upgradeUrl }`.+- A consistent **locked state**: disabled affordance + a tooltip/popover stating the exact+ requirement ("Hold $25 of $THREE to unlock — you hold $8") and a single upgrade CTA.+- Cache the tier for the session; refresh on wallet/auth change. Never block paint on the fetch.++### 3. Build the canonical upgrade path — one `/account` (or `/three`) tier surface+One page renders the full ladder: current tier highlighted, every tier's perks, the live+$-to-next-tier delta, and a real "Hold more $THREE" action that links to the $THREE acquisition+flow (the existing $THREE token/buy surface — `$THREE` CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+Every locked state across the platform routes here. Design all five states (loading skeleton+of the ladder, empty/not-signed-in with a connect CTA, error, populated, overflow at $10M+).++### 4. Replace the per-page reinventions with the shared module+Migrate the Forge "High quality" gate to consume `three-tier-client.js` + `three-access.js`+instead of its bespoke check. Then wire the shared gate into the other registered surfaces+(private worlds, priority routing) so they show the same badge, locked state, and upgrade+route. Delete any duplicated tier copy/threshold literals you find — one ladder, referenced.++### 5. Make holding *visibly* pay off where the user already is+Surface the holder discount and quota multiplier inline at the point of value: a tier badge in+the nav/account menu, the holder discount line on any priced action (a seam D2/D3 consume),+and the perk the user just unlocked called out on the relevant surface. Holding must feel like+it did something, not just change a number on a settings page.++### 6. Test the ladder and the gate+Extend tests so the tier resolution, the fail-open balance behavior, the pure+`accessFromTierLevel` enforcement, and the signed tier-pass round-trip are covered. Add a test+asserting every `three-access.js` `featureId` maps to a real tier level and has non-empty copy.++## Definition of done++Clears 00b-the-bar.md's monetization bar ("$THREE holding unlocks visible, consistent value+across every surface that gates on it — same tiering, same upgrade path, everywhere") and the+polish bar (all five states designed on the tier surface and the locked state). Inherits the+global definition of done in `00-README-orchestration.md`. Specifically: one client module is+the only holder gate in the codebase; Forge and ≥2 more surfaces consume it; the upgrade page+is reachable from every locked state; tier resolution degrades gracefully and is tested;+`npm test` green; verified in a browser with a real wallet at a real and a zero balance.++## Operating rules (override defaults)++No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,+hardcode, or recommend any other token (runtime user-launch mints are the sole mechanical+exception per CLAUDE.md). Design tokens only. Stage explicit paths only (never `git add -A`).+Own the holder-value lane (`three-tier.js`, `three-access.js`, `three-gate.js`, the client+module, the tier surface); extend `balances.js`/`holder-pass.js`/`forge-tiers.js`, don't+rewrite them.++## When finished++Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. an empty-state illustration+on the tier surface, or a keyboard-navigable ladder). Append a `data/changelog.json` entry+(holder-readable, tag `feature` or `improvement`) since this is user-visible. Then delete this+prompt file (`prompts/production-campaign/D-monetization/D1-three-holder-value-system.md`) and+report what you shipped + the seam D2/D3/D4 consume (the tier-resolution endpoint shape and the+`discountBps`/`rateMultiplier` contract they price against).diff --git a/prompts/production-campaign/D-monetization/D2-billing-pricing-metering.md b/prompts/production-campaign/D-monetization/D2-billing-pricing-metering.mdnew file mode 100644index 000000000..41beb2194--- /dev/null+++ b/prompts/production-campaign/D-monetization/D2-billing-pricing-metering.md@@ -0,0 +1,112 @@+# D2 — Production Billing: Pricing, Metering, Invoices & AWS Marketplace++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**+`D1-three-holder-value-system.md` — pricing applies the holder discount from D1's tier ladder.++## Why this matters for $1B++A platform is "trusted with money" only when its books balance. Right now revenue accrues in+fragments — a fee here, a royalty ledger there, a payout endpoint elsewhere — with no single+pricing surface a customer can read, no usage meter they can audit, and no invoice/receipt+they can expense. Enterprises buying through **AWS Marketplace** (the deps are installed:+`@aws-sdk/client-marketplace-metering`, `@aws-sdk/client-marketplace-entitlement-service`)+will not sign without metered billing and entitlement checks that actually call AWS. Real,+reconciled billing is the difference between "we charge sometimes" and a revenue line an+acquirer can underwrite at a multiple. This prompt makes the meter real, the invoice real, and+the AWS path real.++## Current state (read before you write)++- `api/billing/` — `fee-info.js` (public fee rate via `getFeeBps`), `revenue.js` (aggregated+ per-agent earnings dashboard), `receipts.js`, `summary.js`, `payout-wallets/`,+ `withdrawals/`. `tests/billing.test.js` exists. Read each — what's a real ledger query vs. a+ display stub.+- `api/_lib/fee.js` — `getFeeBps`, the platform fee rate. `api/config.js` — public client+ config (the pattern for surfacing capability flags to the browser).+- `api/aws-marketplace/` — `register.js`, `link.js`, `issue-key.js`, `subscription.js`; page+ `pages/aws-marketplace/welcome.html`. **Inspect:** do these actually call the AWS Marketplace+ metering/entitlement SDKs, or do they stub the entitlement/metering record? That is the gap.+- The deps `@aws-sdk/client-marketplace-metering` and `-entitlement-service` are in+ `package.json` but **grep shows no import** — wire them.+- **The gap:** no single customer-facing pricing page; usage is not metered into a queryable+ ledger that produces invoices/receipts; the AWS Marketplace path issues keys but does not+ `BatchMeterUsage`/`MeterUsage` against AWS or check entitlements via `GetEntitlements`.++## Your mission++### 1. A real pricing surface — `pages/pricing.html`+One canonical page that reads pricing from a server source of truth (not hardcoded HTML): the+per-action USDC prices (`forge-tiers.js` `priceUsdcAtomics` is already the truth for Forge;+generalize to a `/api/pricing` endpoint that returns every priced action + the platform fee ++the holder-tier discount table from D1). Render tiers, per-action prices, the live holder+discount, and a "you hold $THREE, your price" personalization when signed in. All five states+designed. This page is what a buyer reads before they spend a cent.++### 2. Usage metering into a queryable ledger+Establish one metering primitive — `api/_lib/metering.js` — that every priced action calls+after it succeeds (`recordUsage({ userId, action, units, priceUsdcAtomics, settlementRef })`)+writing to a `usage_events` table (Postgres via `api/_lib/db.js`, the pattern `royalty.js`+already uses). It must be **idempotent** on a settlement/request key so a retried charge is+never double-metered (00b reliability bar: no double-spend). Back-link each row to its+on-chain settlement (x402) or processor reference. Wire it into the existing priced endpoints+that currently charge but don't meter.++### 3. Invoices & receipts from the ledger+Turn `api/billing/receipts.js` into a real per-charge receipt (action, units, price, fee,+holder discount applied, settlement tx link, timestamp) and add a periodic **invoice** view+(`api/billing/invoices` + a `/billing` or `/account/billing` surface) that rolls usage_events+into a statement the user can read, download (PDF or printable), and reconcile against their+wallet/card. Every line item traces to a settlement ref. Design the empty state ("no usage+yet — here's what gets billed") and the populated statement.++### 4. Wire the real AWS Marketplace metering + entitlement path+In `api/aws-marketplace/`, make the metering and entitlement calls **real**: on a metered+action, call `BatchMeterUsage`/`MeterUsage` (`@aws-sdk/client-marketplace-metering`) with the+customer's AWS identifier and the dimension/units; gate entitled features by `GetEntitlements`+(`@aws-sdk/client-marketplace-entitlement-service`). Resolve the customer via the existing+`register.js`/`link.js` token flow. Handle the AWS error surface at the boundary (throttling,+expired entitlement) with an actionable state. Credentials come from `vercel env` / `.env`+(`AWS_*`, `AWS_MARKETPLACE_PRODUCT_CODE`); if absent, the path ships **inert** (like the fee+module) and never fakes a meter — never invents a metering record AWS didn't accept.++### 5. Reconciliation — the books must balance+Add a reconciliation pass (a script under `scripts/` or a worker) that cross-checks+`usage_events` settlement refs against actual on-chain USDC settlements (and AWS metering+acknowledgements) and flags any usage with no matching settlement, or settlement with no+usage. Surface the reconciliation status on the revenue dashboard so an operator can see "all+charges reconciled" vs. "N unreconciled." This is the trust bar made concrete.++### 6. Test the money paths+Extend `tests/billing.test.js`: metering idempotency (a duplicate settlement key meters once),+invoice rollup math (sum of line items = statement total, fee + holder discount applied+correctly), and the AWS metering call shape (mock the AWS client at the SDK boundary in tests+only — never a fake meter in product code). Money math has tests.++## Definition of done++Clears 00b-the-bar.md's monetization bar ("revenue surfaces … actually charge, actually+settle, actually reconcile") and the trust/correctness bar (idempotent, no double-charge,+inputs validated at the boundary). Inherits the global definition of done in+`00-README-orchestration.md`. Specifically: a pricing page reads server truth and shows the+holder price; every priced action meters idempotently into one ledger; receipts and an invoice+statement reconcile to settlements; the AWS path calls real metering/entitlement SDKs (or ships+inert without faking); `npm test` green; verified with a real charge end-to-end.++## Operating rules (override defaults)++No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,+hardcode, or recommend any other token (runtime user-launch mints are the sole mechanical+exception per CLAUDE.md). Design tokens only. Stage explicit paths only (never `git add -A`).+Own the billing lane (`api/billing/*`, `api/aws-marketplace/*`, the pricing page, the metering+lib); extend `api/_lib/fee.js` and consume D1's tier helper — don't rewrite the fee or tier+modules.++## When finished++Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. an invoice PDF download, or a+"reconciled" badge on the revenue dashboard). Append a `data/changelog.json` entry+(holder-readable, tag `feature`) since pricing/invoices are user-visible. Then delete this+prompt file (`prompts/production-campaign/D-monetization/D2-billing-pricing-metering.md`) and+report what you shipped + the seam for the next agent (the `recordUsage` contract and the+`/api/pricing` shape D3/D4 meter and price against).diff --git a/prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.md b/prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.mdnew file mode 100644index 000000000..91ab3f5e1--- /dev/null+++ b/prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.md@@ -0,0 +1,114 @@+# D3 — The x402 Paid-Endpoint Network & Discovery Indexing++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**+`D1-three-holder-value-system.md` — quotes apply D1's holder discount at price time.++## Why this matters for $1B++x402 is how three.ws gets paid by **other agents** — machine-to-machine USDC settlement with+no signup, no invoice, no human. A network of paid endpoints that are *discoverable* is a+distribution-and-revenue flywheel: an agent in CDP Bazaar finds our endpoint, pays, settles,+and we're indexed as a provider others build on. The platform that other products pay to call+is the one that compounds. But discoverability is brittle — a single newline in a Solana+`payTo` once delisted all 43 of our resources. Every paid endpoint must quote a real price,+settle real USDC, and pass the indexers' own validation, continuously verified. This is+revenue and network effect in one rail.++## Current state (read before you write)++- `api/x402/` — ~28 paid endpoints (`forge.js`, `skill-call.js`, `crypto-intel.js`,+ `vanity.js`, `mint-to-mesh.js`, `tutor.js`, `fact-check.js`, `pay-by-name.js`,+ `my-receipts.js`, …). `api/x402-checkout.js` is the checkout/settlement core.+- `public/x402.js`, `x402-pay-core.js`, `x402-paywall.js`, `x402-discover.js` — the client+ paywall + discovery UI. `public/.well-known`/`api/wk.js` build the catalog.+- **Discovery (from repo memory — read `x402-discovery-indexing.md`):** the catalog is+ published at `/.well-known/x402.json` (built in `api/wk.js`) + `/openapi.json`. Indexers:+ **CDP Bazaar** (catalogs only after a payment SETTLES through the CDP facilitator — EVM/Base,+ not Solana; needs `discoverable:true`; bazaar `info` must validate against its `schema`),+ **x402scan** (Base + Solana; prefers static `/openapi.json`), **402index**+ (`client.register(url)`, all chains, domain-verification = instant).+- **Verifier:** `node scripts/verify-x402-discovery.mjs` (ajv) fetches the live catalog and+ runs the indexers' checks — info-vs-schema, required `accept` fields, `payTo` whitespace,+ Base/Solana coverage, `serviceName` ≤32 ASCII, tags ≤5, `output.example` presence.+- Related scripts already exist: `x402-register-discovery.mjs`, `verify-x402-endpoints.mjs`,+ `x402-paid-sweep.mjs`, `trigger-bazaar.sh`.+- **The gaps (memory's still-open list):** active registration to x402scan + 402index (we're+ passive crawl only); `/openapi.json` covers ~50% of endpoints; most resources lack+ `output.example`; the Solana-first vs CDP-EVM-settlement cataloging tension is unresolved.++## Your mission++### 1. Audit every `api/x402/` endpoint against the paid-endpoint contract+For each endpoint confirm it: (a) returns a real `402 Payment Required` with an `accept` quote+(price in USDC atomics, `payTo`, chain) when unpaid; (b) verifies and **settles** the payment+before doing work; (c) returns a receipt the buyer can reconcile. Fix any endpoint that quotes+but doesn't settle, or settles but doesn't receipt. Apply D1's holder discount to the quoted+price for signed-in holders (a holder pays less to call our paid endpoints — make the discount+real in the `accept` amount, traceable in the receipt).++### 2. Make the catalog pass every indexer's validation, continuously+Bring `/.well-known/x402.json` (via `api/wk.js`) and `/openapi.json` to **100%** coverage of+the live paid endpoints. Every resource: `discoverable:true`, bazaar `info` validating against+its declared `schema`, `payTo` with **zero whitespace/newlines** (the delisting trap),+`serviceName` ≤32 ASCII, ≤5 tags, a real `output.example`, GET=query-params /+POST=`bodyType:"json"`. Run `node scripts/verify-x402-discovery.mjs` until it is fully green —+treat every check it makes as acceptance criteria, not advice.++### 3. Close the `/openapi.json` and `output.example` gaps+Generate the missing half of `/openapi.json` from the same source of truth that builds+`x402.json` (don't maintain two catalogs by hand — derive both). Backfill a realistic, schema-+valid `output.example` on every resource so x402scan and the bazaar render and validate the+endpoint. Examples use only `$THREE` or clearly-synthetic placeholders — **never** a real+non-`$THREE` mint, creator, or holder address.++### 4. Active registration, not just passive crawl+Make `scripts/x402-register-discovery.mjs` a real, idempotent registration to **x402scan**+(`x402scan.com/resources/register`) and **402index** (`client.register(url)`, no auth, domain+verification). It must be safe to re-run (no duplicate listings), report what it registered,+and confirm the listing landed. CDP Bazaar is settlement-triggered — ensure a real settlement+fires through the CDP facilitator so Bazaar catalogs us (the `trigger-bazaar.sh` / paid-sweep+path), and document which endpoints are EVM/Base-settling for that purpose.++### 5. Resolve the Solana-first vs CDP-EVM-settlement tension honestly+Solana is the platform default (repo memory), but CDP Bazaar catalogs on EVM/Base settlement.+Decide per endpoint: expose a Base `accept` option where Bazaar cataloging matters, keep Solana+as the default rail elsewhere, and make the catalog declare both chains where an endpoint+settles on both. The user/agent always sees an honest, settleable quote on whichever chain+they pay. Don't hide the dual-rail — surface it in the paywall (`public/x402-paywall.js`).++### 6. Wire discovery into the product, not just the indexers+The endpoints we publish should also be discoverable **inside** three.ws: surface the paid-+endpoint catalog on a `/x402` or services page (extend `public/x402-discover.js`) so a human or+agent on the platform can browse, see the price, and pay — and so a newly added endpoint shows+up everywhere at once (00-README's "wire surfaces together"). Add a CI/cron guard that runs the+verifier after any catalog change so a regression can't silently delist us again.++## Definition of done++Clears 00b-the-bar.md's monetization bar (x402 paid endpoints "actually charge, actually+settle, actually reconcile") and the trust bar (idempotent settlement, no funds lost, honest+quotes). Inherits the global definition of done in `00-README-orchestration.md`. Specifically:+`verify-x402-discovery.mjs` is fully green; `/.well-known/x402.json` and `/openapi.json` cover+100% of paid endpoints with valid `output.example`s; every endpoint quotes→settles→receipts;+active registration to x402scan + 402index is idempotent and confirmed; the catalog is browsable+in-product; a real paid call (Solana and Base where dual-rail) verified end-to-end.++## Operating rules (override defaults)++No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,+hardcode, or recommend any other token; `output.example`s use `$THREE` or synthetic+placeholders only (runtime user-launch mints are the sole mechanical exception per CLAUDE.md).+Design tokens only. Stage explicit paths only (never `git add -A`). Own the x402 lane+(`api/x402/*`, `api/wk.js`, the catalog, the verifier + registration scripts); extend+`api/x402-checkout.js` and `public/x402*.js` and consume D1's tier helper — don't rewrite the+settlement core.++## When finished++Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. the in-product services+catalog page, or the CI verifier guard). Append a `data/changelog.json` entry (holder-readable,+tag `feature` or `infra`) if user-visible. Then delete this prompt file+(`prompts/production-campaign/D-monetization/D3-x402-paid-endpoints-network.md`) and report+what you shipped + the verifier's final state + the seam for the next agent (which endpoints+settle on which chains, and the catalog source-of-truth shape).diff --git a/prompts/production-campaign/D-monetization/D4-marketplace-economics.md b/prompts/production-campaign/D-monetization/D4-marketplace-economics.mdnew file mode 100644index 000000000..abd91c8d9--- /dev/null+++ b/prompts/production-campaign/D-monetization/D4-marketplace-economics.md@@ -0,0 +1,117 @@+# D4 — Marketplace Economics: Fees, Royalties, Splits & On-Chain Licenses++You are a senior engineer + product thinker building **three.ws**. Read `CLAUDE.md`,+`STRUCTURE.md`, and `prompts/production-campaign/00b-the-bar.md` first. **Prerequisites:**+`D1-three-holder-value-system.md` (creator/buyer tier perks) and ideally+`D2-billing-pricing-metering.md` (payouts reconcile against D2's ledger).++## Why this matters for $1B++A marketplace is worth a multiple when creators **trust it with their money**. That means a+fee they can see, a royalty they reliably receive, a split that pays every collaborator their+exact share, a payout they can withdraw, and — where possible — a license whose terms are+enforced **on-chain** so nobody has to trust an off-chain ledger. Creators who get paid+correctly, every time, bring more creators; that supply is the network effect. A skill license+that mints and enforces trustlessly is the kind of primitive an acquirer underwrites as+defensible IP. This prompt turns "we take a fee somewhere" into a transparent, trustless+creator economy.++## Current state (read before you write)++- `api/_lib/marketplace-platform-fee.js` — the platform fee on a skill purchase: a **real**+ on-chain USDC transfer appended to the buyer's single transaction, routed to the treasury;+ fee comes out of the listed price, creator nets the remainder, buyer total never marked up;+ ships inert when no treasury wallet or rate is configured. Read its honesty contract — the+ purchase response surfaces a `fee` block.+- `api/_lib/royalty.js` — `billSkillRoyalty` (records a `royalty_ledger` debit after a paid+ skill returns) and `settleRoyalties` (the settle-royalties cron; redeems EIP-7710+ delegations, marks ledger rows settled/failed). EVM USDC, viem.+- `api/_lib/payout.js` — `resolvePayoutAddress(agentId, chain)`; `api/billing/payout-wallets/`,+ `withdrawals/`. `api/_lib/vanity-bounty-payout.js` — an existing payout pattern.+- `contracts/skill-license/` — an Anchor (Solana) program (`src/`, `Anchor.toml`,+ `README.md`, `DEPLOYMENT.md`). `api/_lib/skill-license-onchain.js` — the client that reads/+ writes the on-chain license. `api/creators/[id].js`, `api/creators/skill-analytics.js`.+- **The dep `@0xsplits/splits-sdk` is in `package.json` but grep shows NO import** — payment+ splits among multiple collaborators are not yet wired. That's the headline gap.+- **The gap:** fee + royalty + payout each work in isolation; multi-party **splits** don't+ exist; the on-chain skill license isn't wired into the purchase/enforcement path end-to-end;+ creators lack a single "what I earned, what split where, what I can withdraw" surface.++## Your mission++### 1. Payment splits — wire `@0xsplits/splits-sdk` for multi-collaborator skills+Build `api/_lib/splits.js` so a skill or asset with multiple contributors pays each their exact+share atomically. Use `@0xsplits/splits-sdk` to create/resolve an immutable (or mutable-by-+owner) split contract per multi-party listing, and route the creator's net (after platform fee)+into the split so 0xSplits handles the on-chain distribution — **trustless, no custody**. A+single-creator listing pays the creator directly (no split overhead). The split allocation is+set by the creators at listing time and shown to the buyer ("proceeds split: 70/30"). Handle+the no-split and the N-way cases; validate shares sum to 100%.++### 2. Make platform fee + royalty + split one coherent settlement+Today fee (Solana, in-tx) and royalty (EVM, delegated) are separate. Define the canonical+money flow for a marketplace purchase: buyer pays `price` → platform fee out → creator net →+(if multi-party) into the 0xSplits contract → recorded in `royalty_ledger` / D2's+`usage_events`. Every hop is on-chain or ledgered; the purchase response surfaces the full+breakdown (price, fee, creator net, split recipients) — no hidden cut (CLAUDE.md Rule 1 & 9).+Reuse `marketplace-platform-fee.js`'s honesty contract; don't fork a second fee module.++### 3. Wire the on-chain skill license end-to-end+Connect `contracts/skill-license/` + `api/_lib/skill-license-onchain.js` into the purchase+path: a purchase mints/records an on-chain license proving the buyer's right to call the skill,+and the skill executor **verifies the on-chain license** (or a signed proof of it) before+running — so entitlement is enforced trustlessly, not just by a database row. Follow+`DEPLOYMENT.md` for the deployed program ID / env. Where the program isn't deployed in an+environment, the path degrades to the ledger check and never fakes an on-chain license.++### 4. Creator payouts — a real withdraw flow+Make `api/billing/withdrawals/` + `payout.js` a complete withdraw experience: a creator sees+their settled balance (from the royalty ledger + split distributions), picks a payout wallet+(`payout-wallets/`), and withdraws real USDC on a real chain. Idempotent (no double-payout on+retry — 00b reliability bar), with a clear pending → settled → failed status and a tx link.+Design the empty state ("no earnings to withdraw yet") and the in-flight/failed states.++### 5. A creator economics dashboard+Extend `api/creators/[id].js` + `skill-analytics.js` and ship a `/creators` (or+`/dashboard/earnings`) surface: per-skill revenue, the fee taken, royalties earned, split+recipients and their shares, on-chain license count, and the withdraw action. This is where a+creator decides three.ws is worth building on. All five states; tie into D2's invoices so a+creator's earnings reconcile against the same ledger buyers are billed from.++### 6. Test the economics+Cover the money math: fee + creator net = price (buyer never over-charged); N-way split shares+sum to 100% and each recipient's atomics are exact; royalty ledger debits and settles+idempotently; payout doesn't double-pay on retry; on-chain license verification gates execution.+Fixtures use `$THREE` (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or clearly-synthetic+placeholders — **never** a real non-`$THREE` mint or wallet.++## Definition of done++Clears 00b-the-bar.md's monetization bar ("marketplace fees actually charge, actually settle,+actually reconcile") and the trust bar (trustless where possible, no funds lost, idempotent,+honest breakdown). Inherits the global definition of done in `00-README-orchestration.md`.+Specifically: multi-party splits pay each collaborator their exact share via 0xSplits;+fee+royalty+split form one transparent settlement; the on-chain skill license is minted on+purchase and verified before execution; creators can withdraw real USDC idempotently; a creator+dashboard reconciles to D2's ledger; `npm test` green; a full purchase→split→withdraw verified+end-to-end.++## Operating rules (override defaults)++No mocks/fake data/placeholders/TODOs/stubs. **`$THREE` is the ONLY coin** — never name,+hardcode, or recommend any other token; fixtures use `$THREE` or synthetic placeholders only+(runtime user-launch mints are the sole mechanical exception per CLAUDE.md). Design tokens only.+Stage explicit paths only (never `git add -A`). Own the marketplace-economics lane+(`royalty.js`, `payout.js`, `marketplace-platform-fee.js`, the splits lib, `contracts/+skill-license/*`, `skill-license-onchain.js`, `api/creators/*`); consume D1's tier helper and+D2's ledger — don't rewrite the fee or settlement modules.++## When finished++Self-review (CLAUDE.md's five checks). Ship one improvement (e.g. a "proceeds split"+visualization on the listing, or a tx-link receipt on every payout). Append a+`data/changelog.json` entry (holder-readable, tag `feature`) since creator economics are+user-visible. Then delete this prompt file+(`prompts/production-campaign/D-monetization/D4-marketplace-economics.md`) and report what you+shipped + any seam (the split-contract resolution and the on-chain license verification+contract the skill executor depends on).diff --git a/prompts/production-ready/00-README.md b/prompts/production-ready/00-README.mdnew file mode 100644index 000000000..ec0a3319e--- /dev/null+++ b/prompts/production-ready/00-README.md@@ -0,0 +1,139 @@+# Production-Ready — road to $1B 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/production-ready/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).+- Shared backend libs live in **`api/_lib/`** — know these before adding new ones:+ resilience `resilience.js` (cockatiel) + `db-retry.js`; rate limiting+ `rate-limit.js` + `redis.js` + `redis-usage.js`; HTTP helpers `http.js` ++ `http-params.js`; auth `auth.js`/`account-auth.js`/`zauth.js`/`skill-access.js`;+ data `db.js` + `schema.sql` + `migrations/`; env `env.js`; observability+ `sentry.js` + `usage.js`; health `forge-health.js`/`llm-health.js`/+ `provider-health.js` (+ `api/healthz.js`); the x402 family+ (`x402-paid-endpoint.js`, `x402-spending-cap.js`, `x402-spending-ledger.js`,+ `x402-solana-confirm.js`, `x402-errors.js`, …). **Reuse these, don't reinvent.**+- 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 policy (memory): prefer vetted OSS (cockatiel) 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.++> Note: this folder was authored alongside a parallel set under `prompts/road-to-1b/`.+> If both exist, reconcile to a single canonical folder before running the program.diff --git a/prompts/production-ready/01-test-suite-green-and-ci-gate.md b/prompts/production-ready/01-test-suite-green-and-ci-gate.mdnew file mode 100644index 000000000..04ed2e4cd--- /dev/null+++ b/prompts/production-ready/01-test-suite-green-and-ci-gate.md@@ -0,0 +1,59 @@+# 01 — Test suite green + CI gate++> Part of **Production-Ready** (`prompts/production-ready/`). 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/production-ready/02-dead-paths-and-broken-links.md b/prompts/production-ready/02-dead-paths-and-broken-links.mdnew file mode 100644index 000000000..ad0c00101--- /dev/null+++ b/prompts/production-ready/02-dead-paths-and-broken-links.md@@ -0,0 +1,53 @@+# 02 — Dead paths & broken links++> Part of **Production-Ready** (`prompts/production-ready/`). 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/production-ready/03-zero-console-errors.md b/prompts/production-ready/03-zero-console-errors.mdnew file mode 100644index 000000000..4f4c903a7--- /dev/null+++ b/prompts/production-ready/03-zero-console-errors.md@@ -0,0 +1,53 @@+# 03 — Zero console errors & warnings++> Part of **Production-Ready** (`prompts/production-ready/`). 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. It pairs with the+ server-side `api/_lib/sentry.js` sink (prompt `25`).+- `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/production-ready/04-no-mocks-no-placeholders-sweep.md b/prompts/production-ready/04-no-mocks-no-placeholders-sweep.mdnew file mode 100644index 000000000..14780220b--- /dev/null+++ b/prompts/production-ready/04-no-mocks-no-placeholders-sweep.md@@ -0,0 +1,53 @@+# 04 — No-mocks / no-placeholders sweep++> Part of **Production-Ready** (`prompts/production-ready/`). 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` (read via `api/_lib/env.js`).++## 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/production-ready/05-secrets-and-env-hygiene.md b/prompts/production-ready/05-secrets-and-env-hygiene.mdnew file mode 100644index 000000000..2033d6acc--- /dev/null+++ b/prompts/production-ready/05-secrets-and-env-hygiene.md@@ -0,0 +1,59 @@+# 05 — Secrets & env hygiene++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 0 — Foundation+**Owns:** `.env*`, `vercel.json` (`env`), `api/`, `workers/`, `.gitignore`, `api/_lib/env.js`, anything reading `process.env`.+**Depends on:** none. Run early — a leaked key is a $1B-killer.++## Why this matters for $1B+A single leaked private key (Solana parent secret, RPC key, bot token) can drain+funds and end the company. Diligence teams scan git history for secrets. This must be+airtight.++## Mission+Guarantee no secret is committed, every secret is loaded from the environment with a+clear failure when missing, and the set of required env vars is documented and+validated at boot.++## Map+- Env access is centralized in **`api/_lib/env.js`** — extend it, don't scatter+ `process.env` reads.+- Required secrets referenced across the codebase include (verify the live set):+ `THREEWS_SOL_PARENT_SECRET_BASE58`, Solana RPC keys, `TELEGRAM_BOT_TOKEN`,+ `TELEGRAM_CHANGELOG_CHAT_ID`, OpenAI/Anthropic keys (via worker proxies), x402+ facilitator config, Upstash Redis (`api/_lib/redis.js`), Sentry DSN+ (`api/_lib/sentry.js`).+- `vercel.json` has an `env` block. Functions in `api/`, workers in `workers/`.++## Do this+1. Scan the working tree **and git history** for committed secrets (use+ `git log -p` filtered, or a tool like gitleaks/trufflehog run locally). Treat any+ hit as an incident: rotate the key, purge if feasible, and document.+2. Confirm `.gitignore` excludes `.env`, `.env.*` (except `.env.example`), key files,+ and any wallet keypair JSON. Add what's missing.+3. Create/maintain a complete `.env.example` listing **every** env var the app reads,+ grouped by surface, with a one-line description and whether it's required. Derive+ the list by grepping `process.env.` across `api/`, `workers/`, `src/`, `scripts/`.+4. Extend `api/_lib/env.js` so that, on cold start, it asserts required vars are+ present and fails loud with a precise message naming the missing var — never a+ silent undefined that 500s later. Migrate direct `process.env` reads to go through it.+5. Ensure secrets are read server-side only. Grep `public/` and client `src/` for any+ secret-looking value or `VITE_`-exposed secret that should be server-only. Move+ them behind an API route or worker proxy.+6. Confirm the AI provider keys are only ever used via the worker proxies, never+ shipped to the client (per `/CLAUDE.md` stack notes).+7. Document secret rotation steps in `docs/` (where to rotate each, blast radius).++## Must-not+- Do not print secrets in logs or error messages.+- Do not commit a real key even to `.env.example` — use obvious placeholders.+- Do not expose any secret via a `VITE_`/client-bundled var.++## Acceptance+- [ ] git history + working tree scanned; zero live secrets present (rotations done if found).+- [ ] `.gitignore` covers all secret/keypair patterns.+- [ ] `.env.example` is complete and grouped, derived from actual `process.env` usage.+- [ ] `api/_lib/env.js` validates required vars at boot, naming each missing one; reads centralized.+- [ ] No secret reachable from the client bundle.+- [ ] Rotation runbook written in `docs/`.diff --git a/prompts/production-ready/06-error-handling-and-resilience.md b/prompts/production-ready/06-error-handling-and-resilience.mdnew file mode 100644index 000000000..0f2b87580--- /dev/null+++ b/prompts/production-ready/06-error-handling-and-resilience.md@@ -0,0 +1,64 @@+# 06 — Error handling & resilience++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** `api/` (~960 handlers), `workers/`, `api/_lib/`, client fetch wrappers in `src/`/`public/`.+**Depends on:** `04` (no fake fallbacks).++## Why this matters for $1B+At scale, dependencies fail constantly — RPC nodes time out, providers rate-limit,+pump.fun hiccups. A $1B platform degrades gracefully and self-heals. `/CLAUDE.md`:+"No errors without solutions. Ship working fallbacks and failsafes. Lazy error+propagation is not engineering."++## Mission+Every external call has timeout, retry-with-backoff, circuit-breaking where+appropriate, and a designed failure path. Every handler returns correct status codes+and structured errors. No unhandled rejections.++## Map+- Resilience helpers already exist: **`api/_lib/resilience.js`** (cockatiel —+ retry/circuit-breaker/timeout policies) and **`api/_lib/db-retry.js`** for DB. Reuse+ and extend these — do not hand-roll retry loops.+- Error shaping/sanitizing exists: `api/_lib/x402-errors.js`,+ `api/_lib/mcp-error-sanitize.js`. Build the uniform error contract on these.+- Real upstreams: Solana RPC (recent hardening: "never forward an unvalidated Solana+ RPC body through failover" — see git log; `api/solana-rpc.js`), Pump.fun feed,+ OpenAI/Anthropic worker proxies, x402 facilitator (`api/_lib/x402-*`).+- Precedent: `api/x402-checkout.js` ATA-probe hardening against malformed RPC replies+ — match that rigor.++## Do this+1. Inventory every outbound call in `api/` and `workers/`. For each, confirm:+ explicit timeout, bounded retry with jittered backoff (`resilience.js`), and a+ circuit-breaker for hot paths that hammer a flaky upstream.+2. Migrate unprotected callers to the shared `resilience.js`/`db-retry.js` policies+ (additive — don't churn already-protected code, per memory guidance). Add a shared+ resilient RPC/fetch wrapper in `api/_lib/` if one doesn't already cover the case.+3. Validate and defensively parse every upstream response. Never assume shape;+ malformed replies must not throw raw — they map to a clean error or a safe+ default. (Generalize the x402 ATA-probe and Solana-failover patterns.)+4. Standardize API error responses on `x402-errors.js`/`mcp-error-sanitize.js`-style+ sanitization: correct HTTP status, a stable `{ error: { code, message } }` shape,+ no stack traces or secrets leaked to clients. Log full detail server-side (prompt+ `25`).+5. Add a top-level handler wrapper that catches unhandled rejections/exceptions per+ request and converts them to a clean 5xx with a request id.+6. Client side: every `fetch` has a timeout + abort, and surfaces a designed,+ actionable error state (ties to prompt `12`). Add retry on idempotent GETs.+7. Add tests for the failure paths: simulate timeouts, 429s, malformed JSON, partial+ responses. Confirm graceful degradation, not crashes.++## Must-not+- Do not swallow errors silently or return `200` with empty data on failure.+- Do not leak stack traces, internal URLs, or secrets in error responses.+- Do not retry non-idempotent writes blindly (risk of double-spend/double-mint).++## Acceptance+- [ ] Every external call has timeout + bounded retry via `resilience.js`; hot paths have circuit-breakers.+- [ ] Previously-unprotected handlers migrated to the shared resilient helpers.+- [ ] All upstream responses defensively parsed; malformed input handled, never thrown raw.+- [ ] Uniform sanitized error responses with correct status codes; no leaks.+- [ ] Failure-path tests added and green.+- [ ] No unhandled promise rejections (cross-check prompt `03`).diff --git a/prompts/production-ready/07-security-hardening.md b/prompts/production-ready/07-security-hardening.mdnew file mode 100644index 000000000..837db2e0d--- /dev/null+++ b/prompts/production-ready/07-security-hardening.md@@ -0,0 +1,67 @@+# 07 — Security hardening++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** `api/`, `workers/`, auth libs in `api/_lib/`, `vercel.json` (headers/routes), wallet/payment paths.+**Depends on:** `05` (secrets), `06` (error handling). Pairs with `08` (rate limiting).++## Why this matters for $1B+This platform custodies wallets and moves money (x402, $THREE, skill purchases). One+authz bug = drained funds = dead company. Security is the difference between a+fundable platform and a liability.++## Mission+Close every authn/authz gap, validate every input, set hardening headers, and ensure+money-moving paths are airtight. Run a real security review and fix what it finds.++## Map+- Auth libs: `api/_lib/auth.js`, `account-auth.js`, `zauth.js`, `irl-auth.js`,+ `world-service-auth.js`, `skill-access.js`. Ownership model:+ `agent_identities.user_id` is immutable, one agent = one owner (see+ `prompts/agent-wallets/00-README-orchestration.md`).+- Money paths: `api/x402-*`, `api/_lib/x402-*` (`x402-paid-endpoint.js`,+ `x402-spending-cap.js`, `x402-spending-ledger.js`, `x402-solana-confirm.js`),+ `api/payments/*`, `api/pump/*`, `api/_lib/agent-wallet.js`/`solana-wallet.js`,+ `api/_lib/skill-license-onchain.js`.+- `vercel.json` controls routes + can set headers. Repo has a `/security-review` skill.++## Do this+1. Run `/security-review` over the current state and triage findings by severity.+2. **AuthZ on every mutating endpoint:** confirm the caller owns the resource (via the+ `api/_lib/auth.js` session, not a client-supplied id) before any write/withdraw/+ rebrand/spend. Audit `api/` for endpoints that trust client-supplied+ `user_id`/`agent_id`. Fix every one.+3. **Input validation at boundaries:** validate/normalize every request body, query+ param, and path param (lengths, types, ranges, address formats, amount bounds)+ using the `api/_lib/http-params.js` helpers. Reject early with 400. Prevent+ injection (SQL/NoSQL/command), path traversal, SSRF (especially anywhere a URL is+ fetched on the user's behalf, incl. the Solana RPC failover path).+4. **Money-path invariants:** amount sanity bounds, idempotency keys on+ transfers/mints to prevent double-spend, replay protection on signed requests,+ server-side recomputation of prices (never trust client-sent amounts). Use the+ spending-cap/ledger libs as the source of truth.+5. **Security headers** via `vercel.json` or middleware: `Content-Security-Policy`+ (tightened, not `unsafe-inline` everywhere), `Strict-Transport-Security`,+ `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, frame controls+ for embeds (allow only intended embed routes).+6. **CORS:** lock API CORS to known origins; don't reflect arbitrary `Origin`.+7. **Dependency audit:** `npm audit` (and `--workspaces`); fix high/critical by+ upgrade. Document any accepted advisory with rationale.+8. **Secrets in transit/logs:** confirm prompt `05` outcomes hold; no PII/secrets in+ logs (prompt `25`).+9. Add regression tests for each fixed authz/validation hole.++## Must-not+- Do not trust any client-supplied identity, amount, or price.+- Do not weaken CSP to "make something work" — fix the inline/eval cause.+- Do not retry or replay money-moving requests without idempotency.++## Acceptance+- [ ] `/security-review` findings triaged and resolved (or risk-accepted with written rationale).+- [ ] Every mutating endpoint verifies ownership/session server-side via `api/_lib/auth.js`.+- [ ] All inputs validated at the boundary; injection/traversal/SSRF closed.+- [ ] Money paths have amount bounds + idempotency + server-side price recomputation via the spending libs.+- [ ] Hardening headers + locked CORS in place; CSP tightened.+- [ ] `npm audit` clean of high/critical (or documented).+- [ ] Regression tests cover the fixed holes; `npm test` green.diff --git a/prompts/production-ready/08-rate-limiting-and-abuse.md b/prompts/production-ready/08-rate-limiting-and-abuse.mdnew file mode 100644index 000000000..92c65d5e4--- /dev/null+++ b/prompts/production-ready/08-rate-limiting-and-abuse.md@@ -0,0 +1,58 @@+# 08 — Rate limiting & abuse prevention++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** `api/`, `workers/`, the shared limiter in `api/_lib/rate-limit.js` + `api/_lib/http.js`, Upstash Redis usage (`api/_lib/redis.js`).+**Depends on:** `07` (security hardening) · **Parallel-safe with:** `09`++## Why this matters for $1B+Every expensive call — text-to-3D, image gen, LLM proxy, Solana RPC, mint/launch —+spends real GPU, model, and chain budget. Unmetered, one abuser (or a distributed+flood) drains the spend cap, trips fail-closed lanes, and takes the platform down for+everyone. Abuse = downtime = lost users and burned margin. Metering is what lets a free+tier exist without bankrupting the business.++## Mission+Put per-identity and per-IP rate limits, per-tier quotas, and abuse defenses on every+expensive or money-moving endpoint, standardized on the existing shared limiter.++## Map+- Shared limiter: `api/_lib/rate-limit.js` (Upstash `Ratelimit`, sliding-window,+ in-memory dev fallback, `FORGE_PAID_GLOBAL_HOURLY` platform ceiling, cost limiters+ that fail closed when Redis is unconfigured). Helpers `rateLimited` ++ `setRateLimitHeaders` (with `Retry-After`, RFC 9110 §10.2.3) live in `api/_lib/http.js`.+- Health signal: `api/_lib/forge-health.js` already probes the rate-limiter store+ ("paid generation lanes fail closed" when it is down) — keep this accurate.+- Cost-bearing endpoints: text-to-3D `api/forge.js` (already lane-aware via `rl` /+ `rateLimited`), image gen `api/_mcp3d/text-to-image.js` + `api/_mcp3d/vertex-imagen.js`,+ LLM proxy `api/llm/anthropic.js`, RPC `api/solana-rpc.js`, mint/launch under+ `api/pump/`, the x402 family via `api/_lib/x402-paid-endpoint.js` and `api/x402/`.++## Do this+1. Inventory every cost-bearing / money-moving handler in `api/` and `workers/`. For+ each, record who pays (GPU, model tokens, RPC credits, chain fees) and whether it+ already routes through `rateLimited` from `api/_lib/http.js`.+2. Standardize on `api/_lib/rate-limit.js` — do not hand-roll new limiters. Add+ sliding-window limits keyed by authenticated identity first, then by IP. Never key+ off client-supplied identity (verify the session as `07` requires).+3. Add per-tier quotas: a free tier and a higher-ceiling $THREE-holder tier. Keep the+ platform-wide circuit breaker (`FORGE_PAID_GLOBAL_HOURLY` and the x402 facilitator+ backstop) intact and env-tunable.+4. Protect upload endpoints (size, MIME type, count) before any expensive processing.+5. Add lightweight bot/abuse heuristics (burst detection, repeated-junk-payload+ rejection) and surface a clear `429` with `Retry-After` via `rateLimited`.+6. Add tests under `tests/` simulating burst traffic against the limited endpoints,+ asserting `429` + `Retry-After` once the window is exhausted.++## Must-not+- Do not trust client-supplied identity for keying limits.+- Do not silently drop requests — always return `429` with a reason and `Retry-After`.+- Do not weaken the fail-closed behavior of the cost/money limiters when Redis is down.++## Acceptance+- [ ] Every expensive endpoint has a documented limit + per-tier quota, all routed+ through `api/_lib/rate-limit.js`.+- [ ] `429` responses are designed (reason + `Retry-After`); upload guards in place.+- [ ] Burst tests pass; `npm test` green; `npm run lint` + `npm run typecheck` clean.+- [ ] Changelog `improvement`/`security` entry if user-visible.diff --git a/prompts/production-ready/09-accessibility-wcag.md b/prompts/production-ready/09-accessibility-wcag.mdnew file mode 100644index 000000000..268964386--- /dev/null+++ b/prompts/production-ready/09-accessibility-wcag.md@@ -0,0 +1,62 @@+# 09 — Accessibility (WCAG 2.2 AA)++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** all `pages/*.html`, `src/` UI components, `public/` shared UI (nav, modals, tour, walk companion).+**Depends on:** `02` (dead paths). Pairs with `11`, `12`, `13`.++## Why this matters for $1B+Accessibility is required for enterprise/government sales, reduces legal risk, and is+explicitly non-optional in `/CLAUDE.md`: "Semantic HTML. ARIA labels. Keyboard+navigation. Sufficient color contrast. Focus indicators." It also just makes the+product better for everyone.++## Mission+Bring the whole site to WCAG 2.2 AA: keyboard-operable, screen-reader-coherent,+sufficient contrast, visible focus, respects reduced-motion.++## Map+- 125 pages in `pages/`. Shared interactive UI: `public/nav.js`, payment modals+ (`public/x402*.js`), feature tour (`src/feature-tour/`), walk companion+ (`src/walk-companion.js`, `walk-sdk/`).+- Design tokens live in the global stylesheet (`public/` CSS, `style.css`) — fix+ contrast at the token level where possible (coordinate with prompt `13`).++## Do this+1. Run automated audits (axe-core / Lighthouse a11y) across every page; capture+ violations. Automated catches ~30% — also do manual keyboard + screen-reader+ passes on the top 15 flows (forge, marketplace, agent profile, wallet, checkout,+ tour, walk).+2. **Semantic structure:** one `<h1>` per page, logical heading order, landmarks+ (`<nav> <main> <header> <footer>`), lists for lists, `<button>` for actions and+ `<a>` for navigation (no `<div onclick>`).+3. **Keyboard:** every interactive element reachable and operable by keyboard in a+ logical tab order; no keyboard traps; modals/tour/menus trap focus while open and+ restore it on close; ESC closes overlays. Visible, high-contrast focus ring+ everywhere (never `outline: none` without a replacement).+4. **Screen readers:** ARIA labels/roles on icon buttons, custom controls, tabs,+ dialogs, live regions for async updates (generation progress, toasts, balances).+ `alt` text on meaningful images; `aria-hidden` on decorative.+5. **Contrast:** all text and UI states meet 4.5:1 (3:1 for large text/UI). Fix at+ the token level. Check both themes.+6. **Forms:** every input has a programmatic label; errors are announced and+ associated with their field; required/invalid states are not color-only.+7. **Motion:** honor `prefers-reduced-motion` for the tour, walk companion, 3D+ auto-orbit, and transitions.+8. **3D canvases:** provide accessible alternatives/labels for `<model-viewer>` and+ custom canvases (name, description, keyboard orbit where feasible).+9. Add an axe-core check to the Playwright page sweep so regressions fail CI.++## Must-not+- Do not remove focus outlines without an equally-visible replacement.+- Do not use color as the only signal for state/errors.+- Do not add ARIA that lies about state — incorrect ARIA is worse than none.++## Acceptance+- [ ] axe-core/Lighthouse a11y: 0 serious/critical violations across all pages.+- [ ] Top 15 flows fully keyboard-operable; focus managed in all overlays.+- [ ] Screen-reader pass on top flows is coherent (labels, roles, live regions).+- [ ] All text/UI meets AA contrast in both themes (fixed at token level).+- [ ] `prefers-reduced-motion` honored everywhere motion exists.+- [ ] axe check wired into CI page sweep.diff --git a/prompts/production-ready/10-performance-core-web-vitals.md b/prompts/production-ready/10-performance-core-web-vitals.mdnew file mode 100644index 000000000..2915d5dd0--- /dev/null+++ b/prompts/production-ready/10-performance-core-web-vitals.md@@ -0,0 +1,58 @@+# 10 — Performance & Core Web Vitals++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** `vite.config.js`, `pages/`, `src/`, `public/`, 3D asset loading, build pipeline.+**Depends on:** `03` (clean console). Pairs with `11`, `28`.++## Why this matters for $1B+A 3D-heavy platform that janks or loads slowly loses users at the door and ranks+worse in search. `/CLAUDE.md`: "Performance by default. Lazy-load heavy modules.+Don't ship jank." Speed is conversion is revenue is valuation.++## Mission+Hit good Core Web Vitals on every key page (LCP < 2.5s, INP < 200ms, CLS < 0.1 on a+mid-tier device/throttled network) and keep heavy 3D from blocking first paint.++## Map+- Build: `vite.config.js`, scripts `build`, `build:fast`, `optimize:glb`,+ `compress:glbs`. GLB/CDN assets served via R2 (`npm run apply:r2-cors`).+- Heavy modules: Three.js, `<model-viewer>` (+ `model-viewer-meshopt.js`),+ `character-studio/`, `src/scene-studio/`, walk/tour companions.++## Do this+1. Establish a baseline: run Lighthouse (mobile, throttled) on the top 15 pages.+ Record LCP/INP/CLS/TBT and bundle sizes. Set per-page budgets and a script to+ enforce them in CI.+2. **JS:** code-split per route; lazy-load Three.js, model-viewer, character-studio,+ scene-studio, and other heavy modules so they never block initial render. Defer+ non-critical scripts. Tree-shake; remove dead imports (cross-check prompt `04`).+3. **3D assets:** compress GLBs (`npm run compress:glbs` / `optimize:glb`), use Draco/+ meshopt, lazy-load models below the fold, show a lightweight poster/skeleton until+ the model is ready, and cap texture sizes. Never auto-load a heavy model the user+ can't see yet.+4. **Images:** responsive `srcset`, modern formats (AVIF/WebP), explicit+ width/height to kill CLS, lazy-load offscreen images. Run `npm run check:images`.+5. **Fonts:** `font-display: swap`, preload the critical face, subset if possible.+6. **CSS:** inline critical CSS for above-the-fold; defer the rest. Remove unused CSS.+7. **Caching:** correct `Cache-Control` for static assets (immutable hashed assets,+ sensible TTLs for data) via `vercel.json`. Confirm CDN/R2 caching for GLBs.+8. **Layout stability:** reserve space for async content (models, images, embeds)+ to keep CLS near zero.+9. **INP:** debounce input handlers, break up long tasks, avoid main-thread 3D work+ that blocks interaction; move heavy compute to workers where possible.+10. Re-run Lighthouse; confirm budgets met. Wire the budget check into CI.++## Must-not+- Do not block first paint on Three.js or any 3D module.+- Do not ship uncompressed GLBs or unsized images.+- Do not regress accessibility (prompt `09`) for performance.++## Acceptance+- [ ] Top 15 pages: LCP < 2.5s, INP < 200ms, CLS < 0.1 (mobile, throttled).+- [ ] Heavy modules (Three.js, model-viewer, studios) are lazy/code-split.+- [ ] GLBs compressed (Draco/meshopt) and lazy-loaded with posters/skeletons.+- [ ] Images responsive, sized, modern-format, lazy below fold.+- [ ] Per-page performance budgets enforced in CI.+- [ ] Lighthouse perf score ≥ 90 on key pages.diff --git a/prompts/production-ready/11-mobile-responsiveness.md b/prompts/production-ready/11-mobile-responsiveness.mdnew file mode 100644index 000000000..d3490c486--- /dev/null+++ b/prompts/production-ready/11-mobile-responsiveness.md@@ -0,0 +1,57 @@+# 11 — Mobile responsiveness++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** all `pages/*.html`, `src/` UI, `public/` shared UI + CSS, `solana-mobile/` touchpoints.+**Depends on:** `02`, `13`. Pairs with `09`, `12`.++## Why this matters for $1B+Most first-touch traffic is mobile. Recent git history shows the tour and walk+companion were "effectively broken on phones" until fixed — treat that as a signal+that mobile coverage is uneven. A platform that breaks on phones can't go viral.++## Mission+Every page and flow works and looks intentional at 320px, 768px, and 1440px, with+real touch targets and no horizontal scroll.++## Map+- 125 pages in `pages/`. Mobile-sensitive surfaces flagged in git history: feature+ tour (`src/feature-tour/`), walk companion (`src/walk-companion.js`), nav+ (`public/nav.js` — mobile menu), payment modals, forge (`pages/forge.html`).+- Audio/interaction gotcha: mobile browsers block audio until a tap, and the+ permission resets per page — the tour already handles this; preserve that pattern.++## Do this+1. Sweep every page at 320 / 375 / 768 / 1024 / 1440 (Playwright device emulation ++ real-device spot checks). Capture: horizontal overflow, clipped content, unreadable+ text, overlapping elements, off-screen controls, tiny tap targets.+2. Fix layout with fluid units, flex/grid, and `clamp()` — not fixed widths. Eliminate+ every source of horizontal scroll.+3. **Tap targets ≥ 44×44px** with adequate spacing. Audit all icon buttons, tabs,+ close buttons, and dense control rows.+4. **Reachability:** confirm every desktop action has a mobile equivalent. Any control+ that lives only in a collapsing desktop nav must also appear in the mobile menu+ (this exact bug hit the walk companion — re-audit for siblings).+5. **Modals/sheets:** payment, share, settings, and tour overlays fit small screens,+ scroll internally if needed, and have phone-sized controls.+6. **3D on mobile:** model-viewer/canvases are touch-orbitable, sized to viewport,+ and don't overheat/jank low-end devices; provide a lighter path if needed.+7. **Forms/keyboards:** correct `inputmode`/`type`, no zoom-on-focus jump (16px+ font+ on inputs), visible submit above the on-screen keyboard.+8. **Safe areas:** respect notches/home indicators (`env(safe-area-inset-*)`).+9. Add mobile-viewport assertions (no overflow, tap-target size) to the Playwright+ sweep.++## Must-not+- Do not hide functionality on mobile instead of adapting it.+- Do not ship sub-44px tap targets or fixed-width layouts.+- Do not regress the tour's per-page audio-unlock handling.++## Acceptance+- [ ] Every page clean at 320/768/1440 — no horizontal scroll, no clipping/overlap.+- [ ] All tap targets ≥ 44×44px with spacing.+- [ ] Every desktop action reachable on mobile (incl. nav-collapsed controls).+- [ ] Modals/overlays and 3D canvases usable on phones.+- [ ] Forms behave with on-screen keyboards; safe areas respected.+- [ ] Mobile-overflow + tap-target assertions in CI sweep.diff --git a/prompts/production-ready/12-every-state-designed.md b/prompts/production-ready/12-every-state-designed.mdnew file mode 100644index 000000000..a981b9f20--- /dev/null+++ b/prompts/production-ready/12-every-state-designed.md@@ -0,0 +1,56 @@+# 12 — Every state designed (loading / empty / error)++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** every data-driven view across `pages/`, `src/`, `public/`.+**Depends on:** `04` (no fake fallbacks), `06` (error handling).++## Why this matters for $1B+`/CLAUDE.md`: "Every state is designed. A page with no data should tell the user what+to do, not show a blank void." The gap between an adequate product and a $1B one is+the accumulation of these moments — the empty state that converts, the error that+recovers, the skeleton that reassures.++## Mission+Every async, list, and detail view has intentional loading, empty, error, and+overflow states. No blank voids, no raw spinners where a skeleton belongs, no dead+ends on failure.++## Map+- Data-driven surfaces: marketplace, launches feed, agent profiles, wallet/activity,+ bounties, communities, collections, gallery, forge results, search results.+- Reuse/establish shared components for skeletons, empty states, and error states so+ every surface is consistent (coordinate with prompt `13`).++## Do this+1. Inventory every view that fetches or renders variable data. For each, define all+ four states: **loading**, **empty**, **error**, **populated** (+ overflow:+ pagination/virtualization for large lists).+2. **Loading:** skeleton screens that match the populated layout (preferred over+ spinners), tied to real request lifecycle (no fake `setTimeout`).+3. **Empty:** explain what this is, why it's empty, and the one clear next action+ (CTA) — e.g. "No agents yet — forge your first" with a button. Add a tasteful+ illustration/icon. Empty ≠ blank.+4. **Error:** say what went wrong in human terms and offer recovery (Retry, go back,+ contact). Wire Retry to actually re-run the fetch. Never show raw error objects.+5. **Overflow:** lists handle 0 / 1 / many / very-many (paginate or virtualize at+ scale per prompt `10`); long strings truncate with full value on hover/title;+ layouts survive extreme content.+6. Build shared `Skeleton` / `EmptyState` / `ErrorState` primitives (or the+ vanilla-JS equivalent helpers) and adopt them everywhere for consistency.+7. Verify each state in a real browser by forcing it (throttle, offline, empty+ account, error injection).++## Must-not+- Do not ship a bare spinner where a skeleton fits, or a blank area for empty.+- Do not display raw stack traces / JSON errors to users.+- Do not leave a Retry button that doesn't retry.++## Acceptance+- [ ] Every data view has designed loading, empty, error, and overflow states.+- [ ] Loading uses layout-matched skeletons tied to real async.+- [ ] Empty states have copy + a working CTA, not a void.+- [ ] Error states are human and have working recovery actions.+- [ ] Shared state primitives exist and are reused across surfaces.+- [ ] States verified in-browser by forcing each one.diff --git a/prompts/production-ready/13-design-system-consistency.md b/prompts/production-ready/13-design-system-consistency.mdnew file mode 100644index 000000000..99d575792--- /dev/null+++ b/prompts/production-ready/13-design-system-consistency.md@@ -0,0 +1,56 @@+# 13 — Design-system consistency++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** global CSS / design tokens (`style.css`, `public/*.css`), shared components, every page's styling.+**Depends on:** none. Pairs with `09`, `11`, `12`.++## Why this matters for $1B+Consistency compounds into perceived quality. `/CLAUDE.md`: "Consistent spacing and+typography. Use the existing design tokens / CSS variables." A site that uses the same+spacing scale, type ramp, and component vocabulary everywhere reads as one premium+product — not a pile of separately-built pages.++## Mission+One coherent design system: documented tokens, a consistent type/spacing/color scale,+reusable components, and every page conformed to it. No ad-hoc magic numbers.++## Map+- Existing tokens: the forge page references `--space-md/lg/xl/2xl`, `--text-xs..xl`,+ `--ink`, `--ink-dim`, `--stroke`, `--surface-*`, `--radius-*`, `--font-display/+ body/mono`, `--leading-*`. Treat these as the canonical token set.+- 125 pages in `pages/`, many with inline `<style>` blocks — the main source of drift.++## Do this+1. Catalog the existing tokens (the `--space/--text/--ink/--surface/--stroke/--radius/+ --font/--leading` families). If a token catalog doc doesn't exist, create+ `docs/design-system.md` documenting every token, its value, and when to use it.+2. Audit pages for **hardcoded values** that should be tokens: raw px spacing, hex+ colors, font sizes, border radii, shadows. Replace with the nearest token; if no+ token fits, the scale has a gap — extend the scale deliberately, don't add a+ one-off.+3. **Components:** identify repeated UI (buttons, cards, chips, tabs, modals, inputs,+ toasts, badges) re-implemented per page. Extract canonical, accessible, themeable+ versions and replace duplicates. Match hover/active/focus states everywhere.+4. **Type & spacing rhythm:** enforce the type ramp and an 8pt-ish spacing scale+ site-wide. Fix inconsistent line-heights and vertical rhythm.+5. **Color & theming:** both light and dark themes pass contrast (prompt `09`) and use+ only tokens. No hardcoded colors that break theming.+6. **Microinteractions:** ensure consistent transition timing/easing tokens for+ hover/active/enter/exit (`/CLAUDE.md`: "Transitions matter"). Honor reduced-motion.+7. Add a lint/check (stylelint or a custom scan) that flags hardcoded colors/spacing+ outside the token system, and wire it into CI.++## Must-not+- Do not introduce a parallel token set or rename existing tokens (breaks every page).+- Do not add one-off magic numbers when a token exists.+- Do not refactor working components purely for style — extract shared ones additively.++## Acceptance+- [ ] `docs/design-system.md` documents the full token set and components.+- [ ] Hardcoded color/spacing/type values replaced with tokens (scale extended only deliberately).+- [ ] Canonical reusable components extracted and adopted; duplicates removed.+- [ ] Consistent hover/active/focus + transition tokens across the site.+- [ ] Both themes consistent and contrast-passing.+- [ ] Token-drift lint wired into CI.diff --git a/prompts/production-ready/14-seo-and-structured-data.md b/prompts/production-ready/14-seo-and-structured-data.mdnew file mode 100644index 000000000..b95f6b163--- /dev/null+++ b/prompts/production-ready/14-seo-and-structured-data.md@@ -0,0 +1,61 @@+# 14 — SEO & structured data++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Cross-cutting hardening+**Owns:** `pages/` `<head>`s, `public/sitemap/`, `public/llms.txt`, `public/llms-full.txt`, `data/pages.json`, `scripts/build-page-index.mjs`, `npm run seo:meta`.+**Depends on:** `10` (perf affects ranking). Pairs with `34`.++## Why this matters for $1B+Organic discovery is the cheapest growth channel and a durable moat. 293 pages across+11 sections is a large surface to rank. Done right, search + AI-agent discovery+(llms.txt) compounds for free.++## Mission+Every page is discoverable, correctly titled/described, share-ready, and emits valid+structured data. The sitemap, llms.txt, and AI-discovery surfaces are complete and+current.++## Map+- `npm run seo:meta` audits meta. `npm run build:pages` regenerates page index ++ sitemap + changelog from `data/pages.json` + `data/changelog.json`.+- AI discovery: `public/llms.txt`, `public/llms-full.txt` (regenerated by build).+- x402 endpoint discovery indexing is tracked separately (see memory+ `x402-discovery-indexing`) — don't duplicate that here, but cross-link.++## Do this+1. Run `npm run seo:meta` and fix every page missing or sharing a `<title>` /+ `<meta description>`. Titles unique, descriptive, < ~60 chars; descriptions+ compelling, < ~155 chars.+2. **Open Graph + Twitter cards** on every page: `og:title/description/image/url/type`+ + `twitter:card` and a real share image (per-section default + per-entity dynamic+ for agents/launches/collections — see prompt `35`). Verify with a card validator.+3. **Canonical URLs** on every page; resolve duplicate-content (trailing slash, query+ params) via canonical + `vercel.json` redirects.+4. **Structured data (JSON-LD):** `Organization`/`WebSite` site-wide;+ `BreadcrumbList` on nested pages; `Product`/`Offer` on marketplace/skill pages;+ `Article` on blog posts; `SoftwareApplication` on SDK pages. Validate with the Rich+ Results test.+5. **Sitemap:** confirm `public/sitemap/` includes every public page with sane+ priorities and `lastmod`; submit-ready. `robots.txt` correct (allow public, block+ private/API, point to sitemap).+6. **llms.txt / llms-full.txt:** ensure they describe the full product surface and+ stay regenerated by `build:pages`. This is how agents discover the platform — keep+ it first-class.+7. **Semantic + perf:** correct heading hierarchy (shared with prompt `09`), fast LCP+ (prompt `10`), and crawlable content (no JS-only critical content where avoidable).+8. Wire `seo:meta` into CI so a page can't ship without meta.++## Must-not+- Do not duplicate titles/descriptions across pages.+- Do not reference any coin other than `$THREE` in any meta/structured data/share copy.+- Do not block crawlers from public pages or expose private/API routes in the sitemap.++## Acceptance+- [ ] `npm run seo:meta` clean — every page unique title + description.+- [ ] OG/Twitter tags + share images on every page; validated.+- [ ] Canonicals + redirects resolve duplicate content.+- [ ] Valid JSON-LD on org/breadcrumb/product/article/SDK pages (Rich Results passes).+- [ ] Complete sitemap + correct robots.txt.+- [ ] llms.txt/llms-full.txt complete and regenerated by build.+- [ ] `seo:meta` enforced in CI.diff --git a/prompts/production-ready/15-forge-end-to-end.md b/prompts/production-ready/15-forge-end-to-end.mdnew file mode 100644index 000000000..98a8899a9--- /dev/null+++ b/prompts/production-ready/15-forge-end-to-end.md@@ -0,0 +1,68 @@+# 15 — Forge, end-to-end++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `pages/forge.html`, the forge API lane (`api/forge.js`, `api/forge-*.js`, `api/_mcp3d/*`), `forge_free`/`mesh_forge`/`rig_mesh`/`forge_avatar` MCP tools, viewer (`avatar-sdk/`).+**Depends on:** `06`, `08`, `12`. Pairs with `21`, `23`.++## Why this matters for $1B+Forge is the product's "wow" — text/photos → a textured 3D model in the browser. It's+the top-of-funnel magic that makes people screenshot and share. It must feel+instant, reliable, and delightful, with zero dead ends.++## Mission+Make the full forge flow production-grade: input → generation → preview → rig →+download/AR/share, every mode, every state, on every device.++## Map+- UI: `pages/forge.html` (full-width layout; modes: Describe it / From photos /+ sketch-when-live). Stage uses `<model-viewer>`; idle teaser shows a live community+ model.+- Backend: `api/forge.js` (lane-aware, rate-limited), plus `api/forge-poster.js`,+ `forge-og.js`, `forge-gameready.js`, `forge-rembg.js`, `forge-gallery.js`,+ `forge-enhance.js`, `forge-categorize.js`; image gen in `api/_mcp3d/`. Health:+ `api/_lib/forge-health.js`.+- Engines: free NVIDIA NIM / TRELLIS lane (`forge_free`), `mesh_forge` chain,+ auto-rig (`rig_mesh`, `forge_avatar`). Catalog gating hides engines with no live+ worker (note the hidden sketch tab).+- Auto-rig universality rules: `/CLAUDE.md` "Avatar animation is universal" ++ `src/glb-canonicalize.js`, `src/animation-retarget.js`.++## Do this+1. Exercise every mode end-to-end with real generations: text→3D, photos→3D, and+ sketch (only if a live worker exists — otherwise keep it correctly hidden, no dead+ tab). Confirm real API calls succeed with real data.+2. **Generation lifecycle:** real progress tied to the actual job (no fake bars), with+ honest stages (queued → generating → texturing → rigging → ready). Handle slow+ jobs, timeouts, and partial failures with retry (prompt `06`) — never a hung spinner.+3. **Preview:** orbit, zoom, AR, and lighting all work; mobile touch-orbit smooth;+ poster/skeleton until model loads (prompt `10`, `api/forge-poster.js`); model framed+ nicely by default.+4. **Auto-rig:** generated humanoids drive the canonical clip library (idle/walk,+ legs included) per the universality rule; non-humanoid props fall back cleanly to+ the default rig — never a bind-pose T-pose. Verify with a couple of distinct rigs.+5. **Output actions:** download GLB, view in AR, open in viewer, save to account, and+ share (with a real OG image of the model via `api/forge-og.js`) — every button does+ real work.+6. **States:** designed loading/empty/error (prompt `12`); rate-limit + upgrade path+ for the free lane (prompt `08`); clear messaging when an engine is down+ (`forge-health.js`).+7. **Cross-wiring:** a forged model links into the rest of the platform — save to+ profile, list on marketplace, use as an agent avatar, launch flow. Wire those+ connections (`/CLAUDE.md`: "A marketplace that doesn't link to agent profiles is+ half-built").+8. Add tests for the prepare/generate/rig API paths and a Playwright happy-path.++## Must-not+- Do not show fake progress or fake "done" on failure.+- Do not leave a generated model with no next action.+- Do not hardcode a curated rig allowlist — extend `glb-canonicalize.js` for new skeletons.++## Acceptance+- [ ] Every visible mode produces a real model end-to-end; hidden modes stay hidden until live.+- [ ] Honest progress lifecycle; timeouts/partial failures recover with retry.+- [ ] Preview (orbit/zoom/AR) works desktop + mobile with poster/skeleton.+- [ ] Auto-rig drives canonical clips on humanoids; clean fallback for props.+- [ ] Download / AR / save / share / list-on-marketplace all work and cross-link.+- [ ] Designed states + free-lane rate limiting; API + Playwright tests green.diff --git a/prompts/production-ready/16-marketplace-end-to-end.md b/prompts/production-ready/16-marketplace-end-to-end.mdnew file mode 100644index 000000000..cfaffa083--- /dev/null+++ b/prompts/production-ready/16-marketplace-end-to-end.md@@ -0,0 +1,60 @@+# 16 — Marketplace, end-to-end++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `marketplace/`, `pages/marketplace*.html`, skill APIs (`api/skills/*`, `api/_lib/skill-*.js`), `prompts/monetization/` outcomes.+**Depends on:** `12`, `17`, `18`. Pairs with `32`.++## Why this matters for $1B+A marketplace is a flywheel: creators list, buyers buy, both stick. Marketplace+GMV is the headline metric a $1B 3D-agent platform is valued on. It must be+trustworthy, fast, searchable, and conversion-optimized.++## Mission+A complete, polished marketplace: browse → discover → evaluate → purchase → own →+use, with sorting/filtering/search, real listings, and airtight purchase flows.++## Map+- `marketplace/` dir + `pages/` marketplace surfaces. Skill purchase + on-chain+ licenses: `api/skills/*`, `api/_lib/skill-access.js`, `skill-license-onchain.js`,+ `skill-nft.js`, `skill-price-cache.js`, `skill-pricing-rules.js`, `skill-runtime.js`;+ `contracts/skill-license/` (each purchased skill = a 1/1 SPL NFT + `SkillLicense`+ PDA). Existing monetization prompts: `prompts/monetization/`.++## Do this+1. **Discovery:** listings load from real data with sorting (price, recency,+ popularity, rating) and filtering (category, price range, chain, creator). Add+ real search with sensible relevance. `/CLAUDE.md` innovation standard: if list+ views lack sorting, add it.+2. **Listing detail:** rich, accurate detail page — 3D preview, description, price,+ creator (links to agent profile, prompt `17`), reviews/ratings if present,+ ownership state. Every claim backed by real data.+3. **Purchase flow:** end-to-end with real payments (x402 / Solana Pay, prompt `18`).+ States: prepare → pay → confirming (poll) → owned. Idempotent, replay-safe,+ server-side price via `skill-pricing-rules.js`/`skill-price-cache.js` (prompt `07`).+ On success, the buy button becomes "Owned" and the skill/asset is actually usable.+4. **Ownership & licenses:** reflect on-chain `SkillLicense` state truthfully (via+ `skill-license-onchain.js` / `skill-access.js`); gate access by the real license,+ handle pending/confirmed/failed clearly.+5. **Creator side:** list/edit/unlist flows, pricing, and creator analytics (sales,+ revenue, views) — real data, designed empty states for new creators.+6. **Trust & safety:** report/flag listings, basic content checks (ties to prompt+ `36`), and clear refund/dispute messaging where relevant.+7. **States & scale:** designed loading/empty/error (prompt `12`); paginate/virtualize+ large catalogs (prompt `10`); 0/1/many handled.+8. Add E2E tests for browse + purchase (build on `prompts/monetization/23-*`).++## Must-not+- Do not show listings from sample arrays — real data only.+- Do not trust client-sent prices; recompute server-side.+- Do not mark a purchase complete before on-chain/payment confirmation.+- Do not reference any coin other than `$THREE` in copy (runtime user-launched mints in launch feeds are the allowed exception).++## Acceptance+- [ ] Browse with working sort + filter + search over real listings.+- [ ] Listing detail accurate, with 3D preview and creator link.+- [ ] Purchase flow end-to-end with real payment, idempotent, correct states, real ownership unlock.+- [ ] License/ownership reflects on-chain truth; access gated correctly.+- [ ] Creator list/edit/unlist + analytics work with designed empty states.+- [ ] Report/flag + scale handling present; E2E purchase test green.diff --git a/prompts/production-ready/17-agent-profiles-and-economy.md b/prompts/production-ready/17-agent-profiles-and-economy.mdnew file mode 100644index 000000000..ccf51b6fd--- /dev/null+++ b/prompts/production-ready/17-agent-profiles-and-economy.md@@ -0,0 +1,64 @@+# 17 — Agent profiles & economy++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `pages/agent-*.html` (detail, economy, exchange, trade, studio, wallet, embed), `api/agents/*`, agent identity/reputation (`contracts/`, ERC-8004), AgenC reads.+**Depends on:** `16`, `18`. Pairs with `15`, `22`.++## Why this matters for $1B+Every avatar is an autonomous agent with its own wallet and identity. The agent+profile is the canonical "place" an agent lives — its storefront, reputation, wallet,+and activity. This is the social + economic graph that makes the platform defensible.++## Mission+A complete, beautiful, deeply-wired agent profile and economy: identity, wallet,+launches, skills, reputation, activity, and agent-to-agent interactions — all real,+all cross-linked.++## Map+- Pages: `agent-detail.html`, `agent-economy.html`, `agent-exchange.html`,+ `agent-trade.html`, `agent-studio.html`, `agent-wallet.html`, `agent-embed.html`.+- Backend: `api/agents/*` (incl. `fork.js`), `api/_lib/avatar-agent.js`,+ `api/_lib/agent-wallet.js`, `solana-wallet.js`, `avatar-wallet.js`. Ownership model+ is in `prompts/agent-wallets/00-README-orchestration.md` (one agent = one owner,+ `user_id` immutable, fork mints a fresh wallet). Reputation: ERC-8004 in+ `contracts/`, `agent_reputation` tool. AgenC reads via MCP.++## Do this+1. **Profile page:** 3D avatar (animated, not T-pose), name/vanity, owner, bio,+ reputation, wallet summary, skills owned/offered, launches, and activity — all from+ real data. Designed empty states for new agents (prompt `12`).+2. **Identity & ownership:** display lineage (`meta.forked_from`) honestly; "Fork"+ action mints a new owned agent + fresh wallet (never copies secrets). Only the+ owner sees owner-only controls.+3. **Wallet surface:** balances (Solana + EVM), tip, withdraw (owner-only), spend+ limits, activity — wired to the real custodial wallet. Respect every backend+ invariant (do not change them). Build on `prompts/agent-wallets/` outcomes.+4. **Economy:** agent's launches ($THREE-only promotion rules; user-launched mints in+ the launch feed are the runtime-data exception), skills for sale (links to+ marketplace, prompt `16`), trades/exchange, and earnings.+5. **Reputation:** surface ERC-8004 reputation truthfully; explain how it's earned;+ no fabricated scores.+6. **Agent-to-agent:** delegation/invocation surfaces (`agent_delegate_action`,+ agent-invocation contract) where present — make them real and legible.+7. **Cross-wiring:** marketplace listings link here; launches link here; the walk/+ tour avatars can be these agents; embeds (`agent-embed.html`) render the live+ profile. Wire every connection.+8. **Embed/share:** shareable profile with real OG image of the agent; embeddable+ `<agent-3d>` card.+9. Tests for profile data, fork ownership invariants, and wallet authz.++## Must-not+- Do not violate ownership invariants or expose owner-only controls to non-owners.+- Do not copy wallet secrets on fork.+- Do not show fabricated reputation/earnings; real on-chain/DB data only.+- Do not reference any coin other than `$THREE` outside the allowed runtime launch-feed exception.++## Acceptance+- [ ] Profile renders animated avatar + real identity/wallet/skills/launches/activity with designed empty states.+- [ ] Fork mints a fresh owned agent + wallet; lineage shown; secrets never copied.+- [ ] Wallet actions (tip/withdraw/limits) work and enforce owner-only authz.+- [ ] Economy + reputation surfaces show real data and cross-link to marketplace/launches.+- [ ] Agent-to-agent delegation/invocation surfaces are real where present.+- [ ] Shareable/embeddable profile works; tests for ownership + authz green.diff --git a/prompts/production-ready/18-wallet-and-x402-payments.md b/prompts/production-ready/18-wallet-and-x402-payments.mdnew file mode 100644index 000000000..a4edb40a0--- /dev/null+++ b/prompts/production-ready/18-wallet-and-x402-payments.md@@ -0,0 +1,69 @@+# 18 — Wallet & x402 payments++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `api/x402-*`, `api/x402/*`, `api/_lib/x402-*`, `public/x402*.js`, `x402-buildout/`, `x402-modal-sdk/`, `x402-payment-modal/`, `agent-payments-sdk/`, wallet libs in `api/_lib/`.+**Depends on:** `06`, `07`, `08`. Pairs with `16`, `17`.++## Why this matters for $1B+Payments are the revenue spine. x402 makes the platform machine-payable by other+agents — a structural advantage. Wallets custody real funds. Both must be flawless;+a payment bug is unforgivable and a valuation risk.++## Mission+Production-grade wallet + x402 payments: discoverable paid endpoints, reliable+checkout, correct accounting, idempotency, and a beautiful pay UX on every device.++## Map+- Checkout: `api/x402-checkout.js` (recently hardened ATA probe against malformed RPC).+ Paid-endpoint wrapper: `api/_lib/x402-paid-endpoint.js`. Settlement confirm:+ `api/_lib/x402-solana-confirm.js`. Spend safety: `x402-spending-cap.js`,+ `x402-spending-ledger.js`, `x402-spending-price.js`, `x402-prices.js`. Errors:+ `x402-errors.js`. Buyers: `x402-buyer-fetch.js`/`x402-buyer-axios.js`. Pay-by-name:+ `api/x402/pay-by-name.js` + SNS.+- Core client: `public/x402-pay-core.js`, `public/x402.js`. Modal SDKs:+ `x402-modal-sdk/`, `x402-payment-modal/`.+- Discovery indexing (CDP Bazaar / x402scan / 402index) is tracked in memory+ `x402-discovery-indexing` — keep endpoints indexable; reuse the verifier script.+- Default network is Solana (memory `solana-default-network`); Base/EVM secondary.++## Do this+1. **Checkout reliability:** confirm the full prepare → pay → verify → fulfill path+ is resilient (timeouts, retries, malformed-RPC defenses via prompt `06`; generalize+ the ATA-probe hardening). Idempotency keys so a retry never double-charges or+ double-fulfills (prompt `07`), backed by `x402-spending-ledger.js`.+2. **Accounting correctness:** server recomputes amounts (`x402-spending-price.js`/+ `x402-prices.js`); verify settlement on-chain (`x402-solana-confirm.js`) before+ fulfilling; reconcile pending/confirmed/failed states; no fulfill-before-pay.+ Respect the spending cap.+3. **Pay UX:** the modal SDK shows clear amount, network, recipient, and live status;+ QR + wallet-deeplink; designed loading/confirming/success/error/timeout states;+ phone-sized and accessible (prompts `09`, `11`, `12`).+4. **Pay-by-name:** `*.threews.sol` resolution works end-to-end; clear errors for+ unresolvable names.+5. **Wallet surface:** balances, history, send/withdraw (owner-only), spend limits —+ real custodial wallet (`api/_lib/agent-wallet.js`/`solana-wallet.js`), all backend+ invariants preserved. Fund/onramp path works (USDC). Build on the wallet skills.+6. **Discoverability:** ensure paid endpoints publish correct x402 payment+ requirements and are indexed (run the verifier from the memory note); list them on+ a public "paid services" page so agents and humans can find them.+7. **SDK quality:** `agent-payments-sdk/` + modal SDKs build, are documented, and+ have a working example. Publish-ready (coordinate with prompt `24`).+8. Failure-path + idempotency tests; extend `tests/x402-checkout-prepare.test.js`.++## Must-not+- Do not fulfill before on-chain/payment confirmation.+- Do not trust client-supplied amounts/recipients; recompute/verify server-side.+- Do not retry payments without idempotency keys.+- Do not reference any coin other than `$THREE`; arbitrary user-supplied mints in+ generic plumbing are the allowed runtime exception.++## Acceptance+- [ ] Checkout resilient + idempotent end-to-end; no double-charge/fulfill under retry.+- [ ] Settlement verified on-chain before fulfillment; states reconciled; cap respected.+- [ ] Pay modal: clear, accessible, mobile-ready, all states designed.+- [ ] Pay-by-name resolves; wallet balances/history/withdraw/limits/onramp work owner-only.+- [ ] Paid endpoints publish correct x402 requirements and are indexed (verifier passes).+- [ ] Payment SDKs build, documented, with a working example.+- [ ] Failure + idempotency tests green.diff --git a/prompts/production-ready/19-walk-companion-and-tour.md b/prompts/production-ready/19-walk-companion-and-tour.mdnew file mode 100644index 000000000..e96221c76--- /dev/null+++ b/prompts/production-ready/19-walk-companion-and-tour.md@@ -0,0 +1,63 @@+# 19 — Walk companion & feature tour++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `walk-sdk/`, `src/walk-companion.js`, `src/walk-playground.js`, `src/feature-tour/`, `tour-sdk/`, `page-agent-sdk/`.+**Depends on:** `09`, `11`, `12`. Pairs with `30` (onboarding).++## Why this matters for $1B+The walking 3D guide that strolls the live site and narrates features is a signature,+screenshot-worthy differentiator and a powerful onboarding device. Recent git history+shows both the tour and walk companion were broken on phones and only just fixed —+this surface needs to be bulletproof and genuinely delightful.++## Mission+Make the walk companion and feature tour flawless and delightful across all devices:+reliable narration, smooth avatar locomotion, accessible controls, and a tour that+actually teaches the product.++## Map+- Walk companion (corner mascot + full-page playground + avatar picker): `walk-sdk/`,+ `src/walk-companion.js`, `src/walk-playground.js`. Published as `@three-ws/walk`.+- Feature tour (avatar walks the live site narrating features):+ `src/feature-tour/{director,controls,free-roam,guide-avatar,narrator}.js`,+ `tour-sdk/`. Page-agent drop-in: `page-agent-sdk/` (`<page-agent>`).+- Mobile audio gotcha (already solved — preserve): browsers block audio until a tap,+ permission resets per page; tour unlocks on first tap and shows a "tap for voice"+ cue, then re-speaks the current stop. Launchable from home via "Take the tour".++## Do this+1. **Tour content & flow:** the script visits real, current features in a logical+ order and explains *why each matters to the user* — not just "this is X." Re-audit+ stops against the live site so nothing points to a moved/removed feature.+2. **Narration:** per-page audio unlock works on iOS/Android; clear waiting cue;+ re-speaks current stop; captions/transcript for accessibility and muted contexts+ (prompt `09`). Voice off/on persists.+3. **Locomotion:** the guide avatar walks (legs animated via the canonical clip+ library, per `/CLAUDE.md`), pathing is smooth, and free-roam doesn't clip through+ layout or wander off-screen. Honor reduced-motion.+4. **Controls:** play/pause/next/prev/skip/close with phone-sized tap targets,+ keyboard operable, focus-managed (prompts `09`, `11`).+5. **Walk companion:** corner mascot summonable on desktop **and** mobile (the mobile+ "Walk with me" switch must stay reachable — this exact reachability bug already+ bit it). Idle wander without a mouse; tap opens the full playground.+6. **Avatar picker:** diverse, real avatars; user can choose; choice persists.+7. **SDK quality:** `walk-sdk`, `tour-sdk`, `page-agent-sdk` build, are documented,+ and have working embed examples (`examples/`). Publish-ready (prompt `24`).+8. **Performance:** lazy-load the 3D/companion so it never blocks first paint (prompt+ `10`); throttle on low-end devices.+9. Tests: tour stop integrity, audio-unlock logic, mobile reachability, SDK build.++## Must-not+- Do not regress the per-page audio-unlock or the mobile summon switch.+- Do not let the guide T-pose or clip through the page.+- Do not block first paint loading the companion.++## Acceptance+- [ ] Tour visits current features, explains user value, with captions/transcript.+- [ ] Narration unlocks per page on iOS/Android; controls accessible + phone-sized.+- [ ] Guide walks with animated legs, smooth pathing, reduced-motion respected.+- [ ] Walk companion summonable on desktop + mobile; avatar picker works and persists.+- [ ] walk/tour/page-agent SDKs build, documented, with working examples.+- [ ] Companion lazy-loaded; tests green.diff --git a/prompts/production-ready/20-scene-studio.md b/prompts/production-ready/20-scene-studio.mdnew file mode 100644index 000000000..921261691--- /dev/null+++ b/prompts/production-ready/20-scene-studio.md@@ -0,0 +1,53 @@+# 20 — Scene Studio++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `src/scene-studio/` (`→ /scene`), its vendored three.js editor, GLB import/export, materials/lights.+**Depends on:** `10`, `12`. Pairs with `15`, `21`.++## Why this matters for $1B+Scene Studio turns three.ws from "make one avatar" into "compose worlds" — a creation+surface that increases time-in-product, output value, and shareability. A polished+3D editor is a credibility signal for a 3D platform.++## Map+- `src/scene-studio/` — vendored `mrdoob/three.js` r184 editor (MIT, see+ `src/scene-studio/vendor/README.md` + `vendor/LICENSE`). Route `/scene`. Import GLBs,+ compose scenes, edit materials/lights, export.++## Do this+1. **Round-trip integrity:** import a GLB → edit → export → re-import yields the same+ scene. Verify across several real GLBs (forged models, avatars, club props).+ Materials, transforms, lights, and hierarchy survive the round-trip.+2. **Editor UX polish:** the vendored editor is upstream — wrap it in three.ws+ chrome (nav, theme, design tokens per prompt `13`) so it feels native, not a+ bolted-on tool. Consistent controls and shortcuts.+3. **Save/load:** scenes persist to the user's account (real backend), with a gallery+ of saved scenes, autosave/draft recovery, and designed empty/loading/error states+ (prompt `12`). No data loss on refresh/crash.+4. **Performance:** lazy-load the editor bundle (it's heavy — prompt `10`); handle+ large scenes without locking the main thread; cap/compress on export.+5. **Cross-wiring:** import avatars/agents and forged models directly; export to the+ viewer, to an agent profile background, or to a shareable scene page. Add the+ connections (`/CLAUDE.md` cross-pollination).+6. **Share/embed:** a saved scene gets a shareable URL + OG image + embeddable viewer.+7. **Mobile:** at minimum, scenes are *viewable* and shareable on mobile even if full+ editing is desktop-first; communicate that clearly rather than breaking (prompt+ `11`).+8. **Licensing/attribution:** preserve the vendored three.js editor MIT attribution+ (`vendor/LICENSE`, `vendor/README.md`).+9. Tests for import/export round-trip and save/load.++## Must-not+- Do not lose user work on refresh/crash — autosave.+- Do not ship the editor without lazy-loading (it's large).+- Do not strip vendored license/attribution.++## Acceptance+- [ ] GLB import→edit→export→re-import round-trips faithfully on real models.+- [ ] Editor wrapped in native three.ws chrome/theme; consistent controls.+- [ ] Save/load to account with gallery, autosave, and designed states.+- [ ] Editor bundle lazy-loaded; large scenes don't lock the UI.+- [ ] Import from forge/avatars + export to viewer/profile/share wired.+- [ ] Shareable/embeddable scene pages; attribution preserved; round-trip tests green.diff --git a/prompts/production-ready/21-avatar-creator-character-studio.md b/prompts/production-ready/21-avatar-creator-character-studio.mdnew file mode 100644index 000000000..1378b7463--- /dev/null+++ b/prompts/production-ready/21-avatar-creator-character-studio.md@@ -0,0 +1,58 @@+# 21 — Avatar creator / Character Studio++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `character-studio/`, `avatar-sdk/` (viewer + React creator), `pages/avatar-*.html`, `pages/create*.html`, animation pipeline (`public/animations/`, `src/glb-canonicalize.js`, `src/animation-retarget.js`).+**Depends on:** `10`, `12`, `13`. Pairs with `15`, `17`, `19`.++## Why this matters for $1B+The avatar is the atomic unit of the platform — every agent, every wallet, every+launch starts with one. Creating an avatar must be fast, joyful, and produce a rigged,+animated, usable model that flows into the rest of the product.++## Map+- Full creator app: `character-studio/` (fork of M3-org/CharacterStudio, MIT — keep+ attribution in `character-studio/LICENSE`). Viewer + React creator: `avatar-sdk/`+ (`@three-ws/avatar`, `<agent-3d>` web component, `/react` `/creator` subpaths).+- Pages: `avatar-edit/page/embed/studio`, `create*`, `create-selfie`, `creating`.+- Animation universality: `/CLAUDE.md` "Avatar animation is universal — no rig+ allowlist"; mappings in `src/glb-canonicalize.js` (cover new skeletons in+ `tests/glb-canonicalize.test.js`), retarget in `src/animation-retarget.js`.++## Do this+1. **Creation paths:** every entry (build from parts, from a selfie, from forge,+ upload your own GLB) works end-to-end and yields a rigged, animated avatar.+ Reconcile the many `create*` pages — remove dead/duplicate flows, keep the canonical+ ones reachable (prompt `02`).+2. **Rig universality:** any humanoid upload drives the canonical clip library (idle/+ walk, legs included) via bone-name canonicalization; new skeleton conventions get a+ mapping + test case — never a curated allowlist, never a bind-pose T-pose. Verify+ with avatars from several sources (Mixamo, Avaturn, VRM, Ready-Player-like).+3. **Editor UX:** native three.ws chrome/theme (prompt `13`); real-time preview;+ accessible controls; mobile-aware (prompt `11`). Character-studio fork wrapped so+ it feels first-party.+4. **Save & ownership:** saving creates an owned agent + custodial wallet (per the+ ownership model); editing someone else's forks correctly (fresh wallet, lineage).+ Designed empty/loading/error states (prompt `12`).+5. **Output & cross-wiring:** finished avatar flows to: agent profile, walk/tour guide,+ marketplace listing, embed (`<agent-3d>`), and launch. Wire each connection.+6. **Performance:** lazy-load the heavy creator; compress exported GLBs; smooth on+ mid-tier devices (prompt `10`).+7. **SDK quality:** `avatar-sdk` builds, documented, with working web-component ++ React examples (`examples/`); publish-ready (prompt `24`).+8. Tests: extend `tests/glb-canonicalize.test.js` for any new rig; save→own→fork+ invariants; viewer render.++## Must-not+- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` + add a test case.+- Do not let any humanoid fall back to a T-pose.+- Do not copy wallet secrets on fork; do not strip the CharacterStudio MIT attribution.++## Acceptance+- [ ] Every creation path produces a rigged, animated, owned avatar; dead create-flows removed.+- [ ] Humanoids from multiple rig sources animate (legs included); new skeletons covered by tests.+- [ ] Creator feels first-party (theme/chrome), accessible, mobile-aware.+- [ ] Save creates owned agent + wallet; fork mints fresh wallet + lineage.+- [ ] Avatar flows into profile/tour/marketplace/embed/launch.+- [ ] avatar-sdk builds + documented + examples; canonicalize/ownership tests green.diff --git a/prompts/production-ready/22-pumpfun-and-three-token.md b/prompts/production-ready/22-pumpfun-and-three-token.mdnew file mode 100644index 000000000..27c8f2851--- /dev/null+++ b/prompts/production-ready/22-pumpfun-and-three-token.md@@ -0,0 +1,61 @@+# 22 — Pump.fun launch & $THREE surfaces++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `api/pump/*`, `pump-fun-skills/`, `packages/pumpfun-mcp/`, `packages/three-token-mcp/`, `pages/bulk-launch.html`, launch feeds, $THREE surfaces, sniper/oracle workers (`workers/`).+**Depends on:** `06`, `07`, `08`, `18`. Pairs with `16`, `17`.++## Why this matters for $1B+The launch + token economy is a major engagement and revenue surface, and $THREE is+the platform's only coin and a core narrative. These surfaces must be rock-solid,+honest, and strictly compliant with the one-coin rule.++## Map+- Launch backend: `api/pump/*`, `pump-fun-skills/`. Bulk: `pages/bulk-launch.html`.+ Launch feed: `/launches`, `/api/pump/launches` over `pump_agent_mints`. MCP:+ `packages/pumpfun-mcp/`, `packages/three-token-mcp/`. Snapshot: `pump_snapshot` tool.+- Workers: `worker:oracle`, `worker:sniper` (`workers/`), deploy via `deploy:sniper`;+ `npm run pump:smoke`, `pump:refresh-idls`.+- **$THREE only.** CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Two+ runtime-data exceptions only: (1) generic launcher accepting a user-supplied mint at+ runtime; (2) platform launch directories rendering user-launched mints from our own+ records. Never hardcode/market/recommend any non-$THREE mint anywhere.++## Do this+1. **Coin-rule audit FIRST:** grep the whole surface (code, copy, tests, fixtures,+ metadata) for any coin reference that isn't $THREE or a clearly-synthetic+ placeholder. Remove every one — treat like a leaked secret. Confirm the two+ runtime exceptions are the *only* places non-$THREE mints appear, and only from+ live records / user input.+2. **Launch flow:** create/launch end-to-end with real pump.fun integration and real+ payment (prompt `18`); honest progress and confirmation; idempotent so a retry+ never double-launches. Designed states (prompt `12`).+3. **Bulk launch:** `bulk-launch.html` handles batches with per-item status, partial+ failure recovery, and clear accounting — no silent drops.+4. **Launch feed:** `/launches` + agent-profile launch history render real records+ from `pump_agent_mints`; link to agent profiles (prompt `17`); designed empty state.+5. **$THREE surfaces:** any $THREE price/holders/snapshot data is real (via+ `pump_snapshot`/RPC), resilient (prompt `06`), and never fabricated. Token-gating+ (if used) checks real balances.+6. **Workers:** oracle + sniper run reliably with the resilience patterns (timeouts,+ retries, circuit-breakers via `api/_lib/resilience.js`), proper logging/alerting+ (prompt `25`), and safe shutdown. Never blind-retry trades (idempotency, prompt+ `07`). `pump:smoke` passes.+7. **MCP tools:** `pumpfun-mcp` + `three-token-mcp` build, are documented, return+ correct structured output, and are smoke-tested (`smoke:mcp`).+8. Tests: launch idempotency, feed rendering, coin-rule grep as a CI guard.++## Must-not+- Do not reference, hardcode, market, or recommend any coin other than $THREE+ anywhere outside the two runtime-data exceptions.+- Do not paste any real third-party mint/creator/holder address in tests/fixtures.+- Do not double-launch or blind-retry trades.++## Acceptance+- [ ] Coin-rule grep clean; non-$THREE mints appear only in the two runtime exceptions; CI guard added.+- [ ] Launch + bulk-launch end-to-end, idempotent, with honest states and partial-failure recovery.+- [ ] Launch feed renders real records and links to profiles; designed empty state.+- [ ] $THREE data real + resilient; token-gating checks real balances.+- [ ] Oracle + sniper workers resilient, logged/alerted, idempotent; `pump:smoke` passes.+- [ ] pumpfun-mcp + three-token-mcp build + documented + smoke-tested; tests green.diff --git a/prompts/production-ready/23-mcp-servers-production.md b/prompts/production-ready/23-mcp-servers-production.mdnew file mode 100644index 000000000..1d3102bec--- /dev/null+++ b/prompts/production-ready/23-mcp-servers-production.md@@ -0,0 +1,61 @@+# 23 — MCP servers, production-ready++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** `mcp-server/`, `mcp-bridge/`, `packages/*-mcp/` (avatar-agent, pumpfun, ibm-watsonx, ibm-x402, three-token, threews-avatar), the 3d-agent MCP tool surface (`api/_lib/mcp-dispatch.js`, `mcp-error-sanitize.js`).+**Depends on:** `06`, `07`, `08`, `18`. Pairs with `24`.++## Why this matters for $1B+MCP is how every AI agent in the world plugs into three.ws. A clean, paid, discoverable+MCP surface makes the platform infrastructure other products build on — the highest-+multiple position to occupy. The free `forge_free` lane is the wedge.++## Map+- Servers: `mcp-server/` (`@three-ws/mcp-server`), `mcp-bridge/`, and the+ `packages/*-mcp/` set. Dispatch/error libs: `api/_lib/mcp-dispatch.js`,+ `mcp-error-sanitize.js`. Tooling: `npm run audit:mcp`, `smoke:mcp`, `test:mcp`,+ `publish:mcp`(`:dry`).+- Tool surface (3d-agent-local): `forge_free` (free), `text_to_avatar`, `mesh_forge`,+ `rig_mesh`, `forge_avatar`, `ens_sns_resolve`, `agent_delegate_action`,+ `sentiment_pulse`, `get_pose_seed`, `pump_snapshot`, `agent_reputation`,+ `vanity_grinder`, `aixbt_intel`, `aixbt_projects`, AgenC reads. Paid tools quote USDC+ and require an x402 payment payload in `_meta` (v2 transport); missing payment →+ `PaymentRequired` structuredContent.++## Do this+1. **Spec conformance:** every server speaks current MCP transport correctly; each+ tool has accurate name, description (incl. USDC price for paid), and a strict input+ schema with validation. Errors return proper MCP error shapes via+ `mcp-error-sanitize.js`, never crashes.+2. **Free vs paid:** `forge_free` works with no wallet/key and returns a GLB URL ++ viewer link. Paid tools return correct `PaymentRequired` structuredContent without+ payment and fulfill correctly with a valid x402 payload (prompt `18`). Server-side+ price authority (prompt `07`).+3. **Resilience & limits:** every tool wraps its upstreams with timeouts/retries+ (prompt `06`) and is rate-limited/abuse-guarded (prompt `08`). No tool can hang a+ client.+4. **Discoverability:** tools/servers are discoverable (bazaar/x402 indexing, memory+ `x402-discovery-indexing`); a public catalog page lists them with prices and+ examples.+5. **Docs & examples:** each server has a README with install + config (Claude Desktop/+ Code config snippet), env requirements, and a runnable example per tool. Keep+ `STRUCTURE.md` + `PUBLISHING.md` accurate.+6. **Audit/smoke/tests:** `npm run audit:mcp`, `smoke:mcp`, `test:mcp` all pass and+ run in CI. Add coverage for the payment-required path and schema validation.+7. **Publish-readiness:** `publish:mcp:dry` clean; versions, `files`, and metadata+ correct for every published `@three-ws/*-mcp` (coordinate with prompt `24`).++## Must-not+- Do not let a missing payment return a fake success — return `PaymentRequired`.+- Do not trust client-sent prices; server is the price authority.+- Do not ship a tool whose upstream can hang the client without a timeout.+- Do not reference any coin other than $THREE in tool copy/output (runtime user mints excepted).++## Acceptance+- [ ] Every server spec-conformant; every tool validated input + proper error shapes.+- [ ] forge_free works keyless; paid tools enforce x402 with correct PaymentRequired + fulfillment.+- [ ] All tools have timeouts/retries + rate limiting; none can hang a client.+- [ ] Public MCP catalog page + per-server README/examples; discovery indexing verified.+- [ ] `audit:mcp` + `smoke:mcp` + `test:mcp` green in CI, incl. payment-required coverage.+- [ ] `publish:mcp:dry` clean for all published MCP packages.diff --git a/prompts/road-to-1b/08-rate-limiting-and-abuse.md b/prompts/road-to-1b/08-rate-limiting-and-abuse.mdnew file mode 100644index 000000000..7cf1d4d2f--- /dev/null+++ b/prompts/road-to-1b/08-rate-limiting-and-abuse.md@@ -0,0 +1,58 @@+# 08 — Rate limiting & abuse prevention++> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Correctness & hardening+**Owns:** `api/`, `workers/`, the shared limiter in `api/_lib/rate-limit.js` + `api/_lib/http.js`, Upstash Redis usage (`api/_lib/redis.js`).+**Depends on:** `07` (security hardening) · **Parallel-safe with:** `09`++## Why this matters for $1B+Every expensive call — text-to-3D, image gen, LLM proxy, Solana RPC, mint/launch —+spends real GPU, model, and chain budget. Unmetered, one abuser (or a distributed+flood) drains the spend cap, trips fail-closed lanes, and takes the platform down for+everyone. Abuse = downtime = lost users and burned margin. Metering is what lets a free+tier exist without bankrupting the business.++## Mission+Put per-identity and per-IP rate limits, per-tier quotas, and abuse defenses on every+expensive or money-moving endpoint, standardized on the existing shared limiter.++## Map+- Shared limiter: `api/_lib/rate-limit.js` (Upstash `Ratelimit`, sliding-window,+ in-memory dev fallback, `FORGE_PAID_GLOBAL_HOURLY` platform ceiling, cost limiters+ that fail closed when Redis is unconfigured). Helpers `rateLimited` ++ `setRateLimitHeaders` (with `Retry-After`, RFC 9110 §10.2.3) live in `api/_lib/http.js`.+- Health signal: `api/_lib/forge-health.js` already probes the rate-limiter store+ ("paid generation lanes fail closed" when it is down) — keep this accurate.+- Cost-bearing endpoints: text-to-3D `api/forge.js` (already lane-aware via `rl` /+ `rateLimited`), image gen `api/_mcp3d/text-to-image.js` + `api/_mcp3d/vertex-imagen.js`,+ LLM proxy `api/llm/anthropic.js`, RPC `api/solana-rpc.js`, mint/launch under+ `api/pump/`, the x402 family via `api/_lib/x402-paid-endpoint.js` and `api/x402/`.++## Do this+1. Inventory every cost-bearing / money-moving handler in `api/` and `workers/`. For+ each, record who pays (GPU, model tokens, RPC credits, chain fees) and whether it+ already routes through `rateLimited` from `api/_lib/http.js`.+2. Standardize on `api/_lib/rate-limit.js` — do not hand-roll new limiters. Add+ sliding-window limits keyed by authenticated identity first, then by IP. Never key+ off client-supplied identity (verify the session as `07` requires).+3. Add per-tier quotas: a free tier and a higher-ceiling $THREE-holder tier. Keep the+ platform-wide circuit breaker (`FORGE_PAID_GLOBAL_HOURLY` and the x402 facilitator+ backstop) intact and env-tunable.+4. Protect upload endpoints (size, MIME type, count) before any expensive processing.+5. Add lightweight bot/abuse heuristics (burst detection, repeated-junk-payload+ rejection) and surface a clear `429` with `Retry-After` via `rateLimited`.+6. Add tests under `tests/` simulating burst traffic against the limited endpoints,+ asserting `429` + `Retry-After` once the window is exhausted.++## Must-not+- Do not trust client-supplied identity for keying limits.+- Do not silently drop requests — always return `429` with a reason and `Retry-After`.+- Do not weaken the fail-closed behavior of the cost/money limiters when Redis is down.++## Acceptance+- [ ] Every expensive endpoint has a documented limit + per-tier quota, all routed+ through `api/_lib/rate-limit.js`.+- [ ] `429` responses are designed (reason + `Retry-After`); upload guards in place.+- [ ] Burst tests pass; `npm test` green; `npm run lint` + `npm run typecheck` clean.+- [ ] Changelog `improvement`/`security` entry if user-visible; `npm test` green.diff --git a/prompts/road-to-1b/09-test-suite-green-and-ci-gate.md b/prompts/road-to-1b/09-test-suite-green-and-ci-gate.mdnew file mode 100644index 000000000..3c70d5ac2--- /dev/null+++ b/prompts/road-to-1b/09-test-suite-green-and-ci-gate.md@@ -0,0 +1,56 @@+# 09 — Test suite green & CI gate++> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 1 — Correctness & hardening+**Owns:** `tests/`, `vitest.config.js`, `playwright.config.js`, `.github/workflows/ci.yml`, the `test*`/`lint`/`typecheck` scripts in `package.json`.+**Depends on:** `02` (no stubs) · **Parallel-safe with:** `08`++## Why this matters for $1B+Green, meaningful tests plus a blocking CI gate are table stakes for fundability and+for shipping safely at scale. Real money rides on `api/` and the chain paths — a red+suite or a CI that waves failures through is how a money bug reaches production. The+repo already has ~456 test files and a `.github/workflows/ci.yml` merge gate; this+prompt makes it trustworthy.++## Mission+Get the full suite green, cover the highest-risk money/3D/auth paths, and make CI block+merges on red.++## Map+- Suites/scripts (`package.json`): `npm test` = `vitest run && playwright test`;+ `test:core` (single-worker vitest), `test:gate` (`scripts/test-gate.mjs`), `test:e2e`+ (`playwright test`), `test:pages` (`scripts/test-pages.mjs`).+- Config: `vitest.config.js`, `playwright.config.js` (`testDir: 'tests/e2e'`).+- Quality gates: `npm run lint` (`eslint .`), `npm run typecheck` (`tsc -p jsconfig.json`).+- CI: `.github/workflows/ci.yml` jobs — `lint`, `test` (`vitest run`), `guards`+ (`check-api-not-bundled.mjs`, `check:images`, `build:pages`), `typecheck` (currently+ `continue-on-error: true`, advisory).+- Risk-path example: `tests/glb-canonicalize.test.js` is the per-skeleton convention+ test required by `/CLAUDE.md`.++## Do this+1. Run `npm test`, `npm run test:e2e`, `npm run test:pages`, and `npm run test:gate`.+ Fix every failure, or quarantine it behind a tracked issue — no permanent skips.+2. Add tests for the highest-risk paths surfaced by prompt `01`: wallet/withdraw authz,+ x402 payment, the forge generation fallback chain (`api/forge.js` lanes), and+ `glb-canonicalize` per the `tests/glb-canonicalize.test.js` convention.+3. Make `npm run lint` and `npm run typecheck` pass for touched code; clear typecheck+ errors so `.github/workflows/ci.yml` can flip `typecheck` from advisory to blocking.+4. Verify the CI workflow runs lint + tests + guards and blocks on failure on PRs and+ pushes to `main`; tighten the typecheck job to a hard gate once it is clean.+5. Identify flaky tests (re-run suspect specs), de-flake them at the source, and record+ any that remain quarantined with their tracking issue.++## Must-not+- Do not `.skip`/`.only` a test to go green without a tracked issue.+- Do not weaken assertions, shrink fixtures, or delete cases to force a pass.+- Do not mock real APIs to dodge a failure — fix the code or the test setup.++## Acceptance+- [ ] `npm test`, `npm run test:e2e`, `npm run test:pages`, `npm run lint`, and+ `npm run typecheck` all green locally and in `.github/workflows/ci.yml`.+- [ ] CI blocks merges on red (typecheck moved off `continue-on-error` once clean).+- [ ] New tests cover the top risk paths (wallet/withdraw, x402, forge fallback, glb).+- [ ] Flaky tests de-flaked or quarantined with a tracked issue; `npm test` green.+- [ ] Changelog entry only if a user-visible behavior changed (usually internal).diff --git a/prompts/road-to-1b/13-accessibility.md b/prompts/road-to-1b/13-accessibility.mdnew file mode 100644index 000000000..884d15b9a--- /dev/null+++ b/prompts/road-to-1b/13-accessibility.md@@ -0,0 +1,53 @@+# 13 — Accessibility (WCAG 2.2 AA)++> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Experience quality+**Owns:** `pages/`, `src/` components, design tokens/CSS variables, the 3D viewer controls.+**Depends on:** none (run after Phase 0/1) · **Parallel-safe with:** `12`, `14`, `15`, `16`, `17`++## Why this matters for $1B+`/CLAUDE.md` makes accessibility non-optional. It widens the market, is a legal+requirement in many jurisdictions, and signals the craft a $1B platform is held to. An+interface only mouse-and-sighted users can operate caps growth and invites risk.++## Mission+Bring every interactive surface to WCAG 2.2 AA — semantic HTML, keyboard nav, ARIA,+contrast, focus, and reduced-motion.++## Map+- Top surfaces: `pages/home.html` (home), `pages/forge.html`, `pages/marketplace.html`,+ `pages/trending.html`, `pages/agent-detail.html`, and an editor such as Animation+ Studio (`pages/animations.html`) or Scene Studio (`pages/scene.html` / `src/scene-studio/`).+- Shared UI + tokens: components and CSS variables under `src/`; the 3D canvas/orbit+ controls used by the viewer and editors.+- Existing gates to lean on: `npm run audit:web` (`scripts/page-audit.mjs`) and the+ page suite `npm run test:pages` (`scripts/test-pages.mjs`).++## Do this+1. Audit the top surfaces with axe and Lighthouse accessibility; record per-surface+ scores and every serious violation as the baseline.+2. Fix semantic structure: landmarks (`header`/`nav`/`main`/`footer`), one logical+ heading order, labelled controls, lists where appropriate.+3. Make everything keyboard-operable, including the 3D canvas controls and every modal:+ focus trap while open, `Esc` to close, focus returned to the trigger on close, no+ keyboard traps elsewhere.+4. Add ARIA only where native semantics cannot express the role/state — never to+ paper over a non-semantic element that should be a `button`/`a`.+5. Verify color contrast against the design tokens (4.5:1 text, 3:1 large text/UI);+ fix token values rather than one-off overrides.+6. Honor `prefers-reduced-motion` for the heavy transitions and 3D motion; ensure+ visible focus rings everywhere, meaningful `alt` text on informative images, and+ form errors that are announced (`aria-live` / `aria-describedby`).++## Must-not+- Do not add ARIA that lies about state (e.g. static `aria-expanded`).+- Do not remove focus outlines without a clearly-visible replacement.+- Do not hide content from assistive tech to "clean up" the a11y report.++## Acceptance+- [ ] axe/Lighthouse accessibility >= 95 on the top surfaces, no serious violations.+- [ ] Full keyboard walkthrough documented (tab order, modals, 3D controls, `Esc`).+- [ ] Contrast meets AA against design tokens; `prefers-reduced-motion` respected.+- [ ] `npm test` green; `npm run lint` + `npm run typecheck` clean for touched code.+- [ ] Changelog `improvement` entry (e.g. "Keyboard + screen-reader support").diff --git a/prompts/road-to-1b/14-responsive-and-mobile.md b/prompts/road-to-1b/14-responsive-and-mobile.mdnew file mode 100644index 000000000..55a847a34--- /dev/null+++ b/prompts/road-to-1b/14-responsive-and-mobile.md@@ -0,0 +1,53 @@+# 14 — Responsive & mobile++> Part of **Road to $1B** (`prompts/road-to-1b/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Experience quality+**Owns:** `pages/`, `src/` CSS/layout, viewport meta, 3D canvas sizing, `solana-mobile/` touchpoints.+**Depends on:** none · **Parallel-safe with:** `12`, `13`, `15`, `16`, `17`++## Why this matters for $1B+Most crypto and consumer traffic is mobile. A janky phone experience caps growth hard —+the wallet connect, the launch, and the trade all happen on a 360px screen. `/CLAUDE.md`+mandates 320 / 768 / 1440 and proper touch targets; this prompt makes that real.++## Mission+Make every surface fully usable and polished at 320px, 768px, and 1440px, with proper+touch targets and acceptable mobile 3D performance.++## Map+- Top surfaces: `pages/home.html`, `pages/forge.html`, `pages/marketplace.html`,+ `pages/trending.html`, `pages/agent-detail.html`, `pages/agent-trade.html`,+ `pages/agent-wallet.html`, and the editors `pages/forge.html` / `pages/avatar-studio.html`+ / `pages/animations.html` (Animation Studio).+- Layout/CSS + 3D canvas sizing live under `src/`; mobile-specific surfaces under+ `solana-mobile/` (PWA/TWA wrappers, `solana-mobile/pwa/`, `solana-mobile/twa/`).+- Wallet / x402 flows: `pages/agent-wallet.html`, `api/x402/` (exercise on mobile).+- Existing gate: `npm run audit:web` (`scripts/page-audit.mjs`).++## Do this+1. Walk the top surfaces at 320 / 768 / 1440 (and a real device or DevTools emulation);+ log every overflow, fixed width, cut-off modal, and broken nav/menu.+2. Fix horizontal scroll and fixed widths (relative units, flex/grid, `max-width:100%`,+ `min-width:0` on flex children); enlarge touch targets to >= 44px.+3. Make the 3D viewer and editors (Forge, Avatar/Animation Studio) usable on touch —+ orbit/zoom/IK via touch gestures — or degrade gracefully where touch can't drive a+ control. Size the canvas to the viewport without overflow.+4. Handle the on-screen keyboard and safe-area insets for forms and chat+ (`env(safe-area-inset-*)`, `viewport-fit=cover`); inputs must not be obscured.+5. Reflow data-dense lists/tables (trading, marketplace) into stacked/scrollable cards+ on narrow screens — no clipped columns.+6. Exercise the wallet connect and x402 payment flows on mobile, including the+ `solana-mobile/` PWA/TWA path; fix any tap/redirect breakage.++## Must-not+- Do not hide core features on mobile to "fix" a layout — reflow them instead.+- Do not ship horizontal scroll on any top surface.+- Do not shrink touch targets below 44px to fit a dense layout.++## Acceptance+- [ ] No layout breakage or horizontal scroll at 320 / 768 / 1440 on the top surfaces.+- [ ] Touch targets >= 44px; safe-area insets and on-screen keyboard handled.+- [ ] 3D viewer/editors usable on touch or gracefully degraded; canvas never overflows.+- [ ] Wallet + x402 flows verified on mobile (incl. `solana-mobile/`).+- [ ] `npm test` green; `npm run lint` clean; changelog `improvement` entry.diff --git a/prompts/samples/16-marketplace.md b/prompts/samples/16-marketplace.mdindex 87b5bee46..1c94f3196 100644--- a/prompts/samples/16-marketplace.md+++ b/prompts/samples/16-marketplace.md@@ -52,11 +52,11 @@ with real USDC settlement and zero dead paths.[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/marketplace-platform-fee.test.js](../../tests/marketplace-platform-fee.test.js).-- **Tests** — [tests/marketplace-agent-detail-prices.test.js](../../tests/marketplace-agent-detail-prices.test.js),- [tests/marketplace-agent-detail-subscriptions.test.js](../../tests/marketplace-agent-detail-subscriptions.test.js),- [tests/marketplace-animations.test.js](../../tests/marketplace-animations.test.js),- [tests/marketplace-platform-fee.test.js](../../tests/marketplace-platform-fee.test.js).+ [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@@ -97,7 +97,7 @@ with real USDC settlement and zero dead paths.8. **Accessibility + microinteractions:** category sidebar is keyboard-navigable, everycard/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/marketplace-*.test.js`.+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 runbuild:pages` (it validates the entry).@@ -127,5 +127,5 @@ with real USDC settlement and zero dead paths.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/marketplace-*.test.js` passes.+- [ ] `npx vitest run tests/api/marketplace-*.test.js` passes.- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/src/forge-gameready.js b/src/forge-gameready.jsindex ae1c345f4..43dc63278 100644--- a/src/forge-gameready.js+++ b/src/forge-gameready.js@@ -12,6 +12,15 @@// The panel proves its value the way game devs screenshot it: the before→after// poly delta and a live wireframe of the retopologized mesh. Nothing fakes// progress — it polls the job; the wireframe is the real returned GLB.+//+// Charging: the export runs the remesh GPU worker (real cost), so it's a $THREE+// holder perk with a one-time pay-per-export path — the same hold-or-pay model as+// High-tier generation. A verified holder exports free; a non-holder is offered the+// designed $THREE pay modal and the export retries with the settled proof. The+// price is whatever the server gate quotes — never hardcoded here.++import { payForConsumption } from './forge-pay.js';+import { threeHeaders } from './three-tier-pass.js';const resultPanel = document.getElementById('state-result');const viewer = document.getElementById('viewer');@@ -87,6 +96,10 @@ if (resultPanel && viewer && triggerBtn) {.gr-status { font-size: var(--text-xs); font-family: var(--font-mono); color: var(--ink-dim); }.gr-status[data-kind='error'] { color: var(--danger); }.gr-status[data-kind='done'] { color: var(--success); }+ .gr-pay-note { font-size: var(--text-xs); color: var(--ink-dim); line-height: 1.4; margin: 0; }+ .gr-pay-note a { color: var(--accent); text-decoration: none; }+ .gr-pay-note a:hover { text-decoration: underline; }+ .gr-pay-note a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px; }.gr-skeleton { display: none; height: 4px; border-radius: 2px; overflow: hidden; background: var(--surface-1); position: relative; }.gameready[data-busy='true'] .gr-skeleton { display: block; }.gr-skeleton::after { content: ''; position: absolute; inset: 0; width: 40%; border-radius: 2px; background: linear-gradient(90deg, transparent, var(--accent), transparent); animation: gr-sweep 1.1s ease-in-out infinite; }@@ -165,6 +178,7 @@ if (resultPanel && viewer && triggerBtn) {<button class="btn btn-ghost gr-wire-toggle" type="button" aria-pressed="false" hidden title="Show the retopologized wireframe">Wireframe</button><span class="gr-status" role="status" aria-live="polite"></span></div>+ <p class="gr-pay-note">$THREE holders export free — others pay once per export in $THREE. <a href="/three-token">Hold $THREE →</a></p><div class="gr-skeleton" aria-hidden="true"></div><div class="gr-delta" aria-live="polite"></div><div class="gr-downloads"></div>@@ -372,10 +386,14 @@ if (resultPanel && viewer && triggerBtn) {return new Promise((r) => setTimeout(r, ms));}- async function startExport(formats) {+ async function startExport(formats, payment) {+ // Carry the holder's $THREE tier pass so an eligible holder clears the gate+ // (no payment); harmless / empty for everyone else. A non-holder attaches the+ // settled pay-per-export proof instead.+ const threeHdrs = await threeHeaders();const res = await fetch('/api/forge-gameready', {method: 'POST',- headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS, ...threeHdrs },body: JSON.stringify({mesh_url: state.glbUrl,topology: state.topology,@@ -383,12 +401,35 @@ if (resultPanel && viewer && triggerBtn) {texture_size: Number(texsizeSel.value),formats,preserve_rig: rigCheck.checked && formats.includes('fbx'),+ ...(payment?.paymentId && payment?.refId+ ? { payment_id: payment.paymentId, ref_id: payment.refId }+ : {}),}),});const data = await res.json().catch(() => ({}));if (res.status === 503 || data.error === 'unconfigured') {throw new Error('Game-Ready export is not configured on this deployment yet.');}+ // $THREE hold-or-pay gate, or a pay-per-export proof that didn't verify — both+ // recoverable by paying once. Tag it so run() can open the pay modal and retry.+ if (+ res.status === 402 &&+ (data.error === 'three_hold_required' ||+ data.error === 'payment_invalid' ||+ data.error === 'payment_expired')+ ) {+ const e = new Error(data.message || 'Game-Ready export is a $THREE holder perk — or pay per export.');+ e.kind = 'pay_required';+ e.gate = data;+ throw e;+ }+ // Proof already spent — clear it and re-offer Pay so a retry never replays it.+ if (res.status === 409 && data.error === 'payment_already_used') {+ const e = new Error(data.message || 'That payment was already used. Pay again to export.');+ e.kind = 'pay_required';+ e.gate = data;+ throw e;+ }if (res.status === 429 || data.error === 'rate_limited') {const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;throw new Error(`The exporter is busy. Try again in about ${secs}s.`);@@ -399,6 +440,35 @@ if (resultPanel && viewer && triggerBtn) {return data.job_id;}+ // Start the export, transparently handling the $THREE hold-or-pay gate: a holder+ // passes straight through; a non-holder is offered the one-time pay modal, then+ // the export retries with the settled proof. Returns the job id, or null when the+ // user dismissed the payment. The price comes from the server gate — never+ // hardcoded — so it stays correct if the catalog price changes.+ async function startWithGate(formats) {+ try {+ return await startExport(formats);+ } catch (err) {+ if (err.kind !== 'pay_required') throw err;+ const usd = Number(err.gate?.pay_per_use?.usd) || 0;+ if (!(usd > 0)) throw err; // hold-only with no pay path — surface the gate copy+ setStatus('Waiting for payment…');+ const paid = await payForConsumption({+ usd,+ unit: 'one Game-Ready export',+ confirm: 'One engine-ready export (retopology + PBR re-bake), paid in $THREE.',+ footnote: '$THREE is the only coin on three.ws. Draft & Standard generation stay free.',+ successText: 'Payment confirmed — starting your export…',+ refPrefix: 'forge-gameready',+ });+ if (!paid?.ok) {+ setStatus('Export cancelled — no $THREE was spent.');+ return null;+ }+ return await startExport(formats, { paymentId: paid.paymentId, refId: paid.refId });+ }+ }+async function pollExport(jobId) {const deadline = performance.now() + MAX_MS;while (!state.pollAbort && performance.now() < deadline) {@@ -447,7 +517,8 @@ if (resultPanel && viewer && triggerBtn) {deltaEl.classList.remove('is-shown');downloadsEl.classList.remove('is-shown');try {- const jobId = await startExport(formats);+ const jobId = await startWithGate(formats);+ if (!jobId) return; // user dismissed the $THREE payment — already messagedconst done = await pollExport(jobId);if (!done) return; // superseded by a newer model / cancelledapplyResult(done);diff --git a/src/forge-pay.js b/src/forge-pay.jsindex 858ff7704..5a97ba815 100644--- a/src/forge-pay.js+++ b/src/forge-pay.js@@ -32,13 +32,14 @@ function escapeHtml(s) {}// A fresh client nonce per payment — recorded as token_payments.ref_id at quote-// time and presented again (with the payment_id) when the generation redeems it,-// so possession of the payment_id alone can't unlock a generation.-function clientNonce() {+// time and presented again (with the payment_id) when the action redeems it, so+// possession of the payment_id alone can't unlock a dispatch. The prefix names the+// action (e.g. `forge-high`, `forge-gameready`) for readable ledger/audit rows.+function clientNonce(prefix = 'forge') {const id =(typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID()) ||`${Date.now()}-${Math.random().toString(16).slice(2)}`;- return `forge-high-${id}`;+ return `${prefix}-${id}`;}function usdLabel(usd) {@@ -116,19 +117,35 @@ function classifyError(err) {}/**- * Run the pay-per-use flow for one Forge High generation.- * @param {{ usd: number }} params+ * Run the pay-per-use flow for one Forge consumption action (High generation,+ * Game-Ready export, …). Drives the same server-authoritative quote → sign →+ * settle rail behind the designed status modal, then hands back the settled+ * { paymentId, refId } so the caller can retry the action with the proof attached.+ * @param {object} params+ * @param {number} params.usd price in USD (settled in $THREE)+ * @param {string} [params.unit] short unit shown under the price ("one export")+ * @param {string} [params.confirm] one-line confirm-step description+ * @param {string} [params.footnote] trusted footnote markup under the actions+ * @param {string} [params.successText] copy shown on a verified payment+ * @param {string} [params.refPrefix] client-nonce prefix (action name)* @returns {Promise<{ ok: true, paymentId: string, refId: string } | { ok: false, cancelled?: boolean }>}*/-export function payForHighGeneration({ usd }) {+export function payForConsumption({+ usd,+ unit = 'one generation',+ confirm = 'One generation, paid in $THREE.',+ footnote = '$THREE is the only coin on three.ws.',+ successText = 'Payment confirmed — continuing…',+ refPrefix = 'forge',+} = {}) {injectStyles();return new Promise((resolve) => {- const refId = clientNonce();+ const refId = clientNonce(refPrefix);let settled = false;const overlay = document.createElement('div');overlay.className = 'fpay-overlay';- overlay.innerHTML = renderShell(usd);+ overlay.innerHTML = renderShell(usd, { unit, footnote });document.body.appendChild(overlay);const modal = overlay.querySelector('.fpay-modal');@@ -159,7 +176,7 @@ export function payForHighGeneration({ usd }) {}function showConfirm() {- showStatus('One High-quality generation (200k poly + PBR), paid in $THREE.');+ showStatus(confirm);actionsEl.innerHTML =`<button type="button" class="fpay-btn fpay-btn--primary" data-fpay-pay>Pay ${usdLabel(usd)}</button>` +`<button type="button" class="fpay-btn fpay-btn--ghost" data-fpay-cancel>Cancel</button>`;@@ -213,7 +230,7 @@ export function payForHighGeneration({ usd }) {}settled = true;statusEl.className = 'fpay-status fpay-status--ok';- statusEl.innerHTML = `<span class="fpay-check" aria-hidden="true">✓</span> Payment confirmed — starting your generation…`;+ statusEl.innerHTML = `<span class="fpay-check" aria-hidden="true">✓</span> ${escapeHtml(successText)}`;actionsEl.innerHTML = '';setTimeout(() => finish({ ok: true, paymentId: result.payment_id, refId }), 850);} catch (err) {@@ -240,16 +257,33 @@ export function payForHighGeneration({ usd }) {});}-function renderShell(usd) {+/**+ * Pay-per-use for one Forge High generation — the original entry point, preserved+ * exactly. A thin wrapper over payForConsumption with the High copy/nonce.+ * @param {{ usd: number }} params+ * @returns {Promise<{ ok: true, paymentId: string, refId: string } | { ok: false, cancelled?: boolean }>}+ */+export function payForHighGeneration({ usd }) {+ return payForConsumption({+ usd,+ unit: 'one High generation',+ confirm: 'One High-quality generation (200k poly + PBR), paid in $THREE.',+ footnote: '$THREE is the only coin on three.ws. Draft & Standard generation stay free.',+ successText: 'Payment confirmed — starting your generation…',+ refPrefix: 'forge-high',+ });+}++function renderShell(usd, { unit = 'one generation', footnote = '$THREE is the only coin on three.ws.' } = {}) {return (`<div class="fpay-modal" role="dialog" aria-modal="true" aria-labelledby="fpay-title">` +`<button class="fpay-x" data-fpay-x type="button" aria-label="Close">✕</button>` +`<div class="fpay-badge" aria-hidden="true">◆</div>` +`<h2 class="fpay-title" id="fpay-title">Pay ${usdLabel(usd)} in $THREE</h2>` +- `<div class="fpay-price"><span class="fpay-price-amt">${usdLabel(usd)}</span><span class="fpay-price-unit">in $THREE · one High generation</span></div>` ++ `<div class="fpay-price"><span class="fpay-price-amt">${usdLabel(usd)}</span><span class="fpay-price-unit">in $THREE · ${escapeHtml(unit)}</span></div>` +`<div class="fpay-status" role="status" aria-live="polite"></div>` +`<div class="fpay-actions"></div>` +- `<p class="fpay-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free.</p>` ++ `<p class="fpay-foot">${footnote}</p>` +`</div>`);}diff --git a/tests/api/forge-gameready.test.js b/tests/api/forge-gameready.test.jsindex 8fa515fbc..ae7489bb9 100644--- a/tests/api/forge-gameready.test.js+++ b/tests/api/forge-gameready.test.js@@ -11,6 +11,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { Readable } from 'node:stream';+import { signTierPass } from '../../api/_lib/three-tier.js';// Stub the GCP provider — each submit returns a distinct upstream task id so the// composite job id packs both formats; status() returns a done remesh result.@@ -83,6 +84,15 @@ beforeEach(() => {}));});+// The export is $THREE hold-or-pay gated (Token Utility — consumption lever). A+// signed Bronze tier pass clears the gate so the worker-logic tests below exercise+// the real fan-out, not the 402. Dev secret → sign/verify symmetry; without a pass+// the export 402s (covered in the gate describe block).+process.env.NODE_ENV = 'development';+delete process.env.HOLDER_PASS_SECRET;+const WALLET = 'THREEsynthetic1111111111111111111111111111';+const BRONZE_PASS = signTierPass({ wallet: WALLET, level: 1, tierId: 'bronze', usd: 30 });+const { default: handler } = await import('../../api/forge-gameready.js');function makeRes() {@@ -99,12 +109,20 @@ function makeRes() {};}-function makeReq({ method = 'POST', url = '/api/forge-gameready', headers = {}, body = null } = {}) {+// `pass` defaults to a Bronze tier pass so POSTs clear the $THREE gate; pass `null`+// to submit as a non-holder (gate tests). GET polls are ungated — the header is+// harmless there.+function makeReq({ method = 'POST', url = '/api/forge-gameready', headers = {}, body = null, pass = BRONZE_PASS } = {}) {const payload = body == null ? '' : typeof body === 'string' ? body : JSON.stringify(body);const stream = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);stream.method = method;stream.url = url;- stream.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers };+ stream.headers = {+ 'content-type': 'application/json',+ 'x-forwarded-for': '203.0.113.9',+ ...(pass ? { 'x-three-tier-pass': pass } : {}),+ ...headers,+ };return stream;}@@ -196,6 +214,46 @@ describe('POST /api/forge-gameready', () => {});});+describe('POST /api/forge-gameready — $THREE hold-or-pay gate', () => {+ it('blocks a non-holder with a 402 three_hold_required + the pay-per-export price', async () => {+ const res = makeRes();+ // No pass, no payment → anonymous caller below the Bronze threshold.+ await handler(makeReq({ body: { mesh_url: MESH }, pass: null }), res);+ expect(res.statusCode).toBe(402);+ const b = JSON.parse(res.body);+ expect(b.error).toBe('three_hold_required');+ expect(b.feature).toBe('forge.gameready');+ expect(b.required).toMatchObject({ level: 1, id: 'bronze' });+ // Pay-per-export price comes straight from the catalog ($0.10 = OUTPUTS.gameready).+ expect(b.pay_per_use).toMatchObject({ action: 'forge.gameready', usd: 0.1 });+ // The gate is hermetic — it fired before any worker/DNS call.+ expect(submit).not.toHaveBeenCalled();+ });++ it('does not dispatch to the worker when the gate blocks', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { mesh_url: MESH, formats: ['glb', 'fbx'] }, pass: null }), res);+ expect(res.statusCode).toBe(402);+ expect(submit).not.toHaveBeenCalled();+ });++ it('lets a verified Bronze holder export (gate falls through to the worker)', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { mesh_url: MESH, formats: ['glb'] } }), res); // default Bronze pass+ expect(res.statusCode).toBe(202);+ expect(JSON.parse(res.body).error).toBeUndefined();+ expect(submit).toHaveBeenCalled();+ });++ it('gates a tampered / invalid pass as a non-holder', async () => {+ const res = makeRes();+ await handler(makeReq({ body: { mesh_url: MESH }, pass: 'not.a.valid.pass' }), res);+ expect(res.statusCode).toBe(402);+ expect(JSON.parse(res.body).error).toBe('three_hold_required');+ expect(submit).not.toHaveBeenCalled();+ });+});+describe('GET /api/forge-gameready?job=', () => {async function submitJob(body) {const res = makeRes();diff --git a/tests/forge-consumption-payment.test.js b/tests/forge-consumption-payment.test.jsnew file mode 100644index 000000000..904563081--- /dev/null+++ b/tests/forge-consumption-payment.test.js@@ -0,0 +1,175 @@+// Unit tests for the generic Forge consumption pay-per-use proof+// (api/_lib/forge-consumption-payment.js).+//+// The consumption lever, generalized beyond High: a settled $THREE `consumption`+// payment, bound to ref_type:'forge' + the client nonce + the action's price,+// stands in for holding $THREE on one dispatch of a priced Forge action+// (Game-Ready export today). These prove the validation contract (action/purpose/+// ref/price/recency/single-use), the atomic single-use claim, the release path,+// and — crucially — that a payment for one Forge action can't satisfy a+// differently-priced one.+//+// The DB is mocked: a tagged-template `sql` that returns whatever the test queues.+// priceForAction is the real pure catalog ($0.10 for forge.gameready, $0.50 for+// forge.high), so a silent price change fails here.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const queue = [];+vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async () => (queue.length ? queue.shift() : []));+ return { sql };+});++import {+ assertForgePurchase,+ redeemForgePurchase,+ releaseForgePurchase,+} from '../api/_lib/forge-consumption-payment.js';+import { sql } from '../api/_lib/db.js';+import { priceForAction } from '../api/_lib/pricing/catalog.js';++const ACTION = 'forge.gameready';+const GR_USD = Number(priceForAction(ACTION).usd); // 0.10 from the catalog+const HIGH_USD = Number(priceForAction('forge.high').usd); // 0.50+const REF_ID = 'forge-gameready-abc123';++function paymentRow(over = {}) {+ return {+ id: 'pay-1',+ purpose: 'consumption',+ usd: GR_USD.toFixed(6),+ ref_type: 'forge',+ ref_id: REF_ID,+ confirmed_at: new Date().toISOString(),+ created_at: new Date().toISOString(),+ ...over,+ };+}++// Queue the two reads assertForgePurchase makes: the payment lookup, then the+// redemption-existence check.+function queueAssert({ payment = paymentRow(), redeemed = false } = {}) {+ queue.push(payment ? [payment] : []); // lookupPayment+ queue.push(redeemed ? [{ payment_id: 'pay-1' }] : []); // isRedeemed+}++beforeEach(() => {+ queue.length = 0;+ vi.clearAllMocks();+});++describe('assertForgePurchase', () => {+ it('accepts a settled, ref-bound, correctly-priced, recent, unredeemed payment', async () => {+ queueAssert();+ const r = await assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID });+ expect(r.ok).toBe(true);+ expect(r.payment).toMatchObject({ id: 'pay-1', usd: GR_USD });+ expect(r.payment.settledAt).toBeTruthy();+ });++ it('requires action, payment_id and ref_id', async () => {+ await expect(assertForgePurchase({ action: '', paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ status: 400,+ code: 'bad_request',+ });+ await expect(assertForgePurchase({ action: ACTION, paymentId: '', refId: REF_ID })).rejects.toMatchObject({+ status: 400,+ code: 'bad_request',+ });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: '' })).rejects.toMatchObject({+ status: 400,+ code: 'bad_request',+ });+ });++ it('rejects an unknown payment as payment_invalid (402)', async () => {+ queue.push([]); // lookupPayment → none+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'nope', refId: REF_ID })).rejects.toMatchObject({+ status: 402,+ code: 'payment_invalid',+ });+ });++ it('rejects a non-consumption / non-forge payment', async () => {+ queueAssert({ payment: paymentRow({ purpose: 'spin' }) });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });++ queueAssert({ payment: paymentRow({ ref_type: 'voice' }) });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });++ it('rejects a payment bound to a different ref_id', async () => {+ queueAssert({ payment: paymentRow({ ref_id: 'someone-elses-nonce' }) });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });++ it('rejects a payment priced for a DIFFERENT forge action (High $0.50 ≠ Game-Ready $0.10)', async () => {+ // A $0.50 High payment must not unlock a $0.10 Game-Ready export — the price+ // check is what keeps same-ref_type Forge actions apart.+ expect(HIGH_USD).not.toBe(GR_USD);+ queueAssert({ payment: paymentRow({ usd: HIGH_USD.toFixed(6) }) });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });++ it('rejects a payment older than the redemption window (payment_expired)', async () => {+ const old = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();+ queueAssert({ payment: paymentRow({ confirmed_at: old, created_at: old }) });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ status: 402,+ code: 'payment_expired',+ });+ });++ it('rejects an already-redeemed payment (409 payment_already_used)', async () => {+ queueAssert({ redeemed: true });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ status: 409,+ code: 'payment_already_used',+ });+ });++ it('applies the holder discount to the expected price when a discount rides along', async () => {+ const discounted = Number(priceForAction(ACTION, { discountBps: 500 }).usd); // 5% off+ queueAssert({ payment: paymentRow({ usd: discounted.toFixed(6) }) });+ const r = await assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID, discountBps: 500 });+ expect(r.ok).toBe(true);+ // The same discounted payment fails at full price (no discount presented).+ queueAssert({ payment: paymentRow({ usd: discounted.toFixed(6) }) });+ await expect(assertForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });+});++describe('redeemForgePurchase', () => {+ it('claims a payment when the insert wins (returns a row)', async () => {+ queue.push([{ payment_id: 'pay-1' }]);+ const r = await redeemForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID });+ expect(r.redeemed).toBe(true);+ expect(sql).toHaveBeenCalledOnce();+ });++ it('does not claim when the row already exists (ON CONFLICT DO NOTHING → no row)', async () => {+ queue.push([]); // conflict → nothing returned+ const r = await redeemForgePurchase({ action: ACTION, paymentId: 'pay-1', refId: REF_ID });+ expect(r.redeemed).toBe(false);+ });+});++describe('releaseForgePurchase', () => {+ it('deletes the claim so the payment is reusable on retry', async () => {+ queue.push([]);+ await releaseForgePurchase({ paymentId: 'pay-1' });+ expect(sql).toHaveBeenCalledOnce();+ expect(sql.mock.calls[0].slice(1).map(String)).toContain('pay-1');+ });+});