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
Add prepaid credits rail, new tutorials, and production-readiness prompt sets
nirholas36579d0e76e4
diff --git a/.env.example b/.env.exampleindex ad1f165cf..92fe12ce2 100644--- a/.env.example+++ b/.env.example@@ -320,6 +320,10 @@ SDP_API_BASE=https://api.solana.com# Per-network payTo wallets that receive USDC for paid MCP calls.X402_PAY_TO_SOLANA=BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSNX402_PAY_TO_BASE=0x4022de2d36c334e73c7a108805cea11c0564f402+# Prepaid credits (POST /api/credits/deposit): the Solana wallet users send SOL or+# $THREE to when topping up their balance. Defaults to X402_PAY_TO_SOLANA, then the+# $THREE treasury, if unset — set it to route deposits to a dedicated wallet.+CREDITS_DEPOSIT_WALLET_SOLANA=# USDC asset addresses (mainnet).X402_ASSET_MINT_SOLANA=EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1vX402_ASSET_ADDRESS_BASE=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e749be484..d403a67d3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -70,12 +70,12 @@ jobs:- run: npm run build:pagestypecheck:- name: Typecheck (advisory)+ name: Typecheckruns-on: ubuntu-latest- # Advisory until the JSDoc type backlog is cleared — surfaces type signal on- # every PR without blocking merge. Flip `continue-on-error` to false to make- # it a hard gate once `npm run typecheck` is clean.- continue-on-error: true+ # `npm run typecheck` (tsc over jsconfig.json) is clean as of 2026-06-21, so+ # this is now a hard merge gate: a new type error blocks the PR. The JSDoc+ # backlog it used to wait on has been burned down — keep it clean by fixing+ # the types, not by restoring continue-on-error.steps:- uses: actions/checkout@v4- uses: actions/setup-node@v4@@ -84,3 +84,47 @@ jobs:cache: npm- run: npm ci- run: npm run typecheck++ pages:+ name: Page health+ runs-on: ubuntu-latest+ # scripts/test-pages.mjs spawns its own vite server and drives Chromium over+ # every public route, failing on thrown errors, real console errors, dead+ # requests, or broken hero images before they ship (npm run test:pages).+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 24+ cache: npm+ - run: npm ci+ - name: Cache Playwright browsers+ uses: actions/cache@v4+ with:+ path: ~/.cache/ms-playwright+ key: playwright-${{ runner.os }}-${{ hashFiles('package-lock.json') }}+ restore-keys: playwright-${{ runner.os }}-+ - run: npx playwright install --with-deps chromium+ - run: npm run test:pages++ e2e:+ name: E2E (Playwright)+ runs-on: ubuntu-latest+ # The browser-driven specs (playwright.config.js boots `npm run dev` as its+ # webServer). retries:1 in the config absorbs a single transient blip; a+ # spec that fails twice is a real regression and blocks the PR.+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-node@v4+ with:+ node-version: 24+ cache: npm+ - run: npm ci+ - name: Cache Playwright browsers+ uses: actions/cache@v4+ with:+ path: ~/.cache/ms-playwright+ key: playwright-${{ runner.os }}-${{ hashFiles('package-lock.json') }}+ restore-keys: playwright-${{ runner.os }}-+ - run: npx playwright install --with-deps chromium+ - run: npx playwright testdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2e9c423c..2e6f70bfd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-21- **Arm your agent — automate Oracle conviction** (`/oracle/arm`) — Configure your 3D agent to trade Oracle conviction automatically: set the minimum score, position size, daily and open-position caps, narrative filters and Telegram alerts, then arm it in simulate or live mode. Every action is graded against the outcome.+- **Credits** (`/credits`) — Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.- **Docs · Walk Avatar** (`/docs/walk`) — Developer and user documentation for the three.ws walking-avatar system: the /walk page, iframe embeds, the JavaScript SDK, the postMessage event contract, companion mode, analytics, and the Chrome extension.- **Feed** (`/feed`) — Recent activity from the people and agents you follow on three.ws.- **Walk** (`/walk`) — Your 3D avatar walks anywhere on the web. Live demos across six environments, a Chrome extension, one-tag embeds, and a global distance leaderboard.@@ -15,6 +16,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **"Made with Forge" showcase on the homepage spins again** — The homepage's community strip — fresh text-to-3D models the moment they're forged — had stopped showing the spinning models, leaving only empty placeholder tiles. The viewer that renders each model was waiting on a script that never loaded because of a too-broad name match, so the meshes never appeared. The strip now loads its viewer correctly: real community creations rotate live again, with a click-through to forge your own. (`/forge`) `[fix]`- **$THREE buyback commitment is now public and verifiable on the token page** — The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed. (`/three-token`) `[feature]`- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`+- **13 new step-by-step tutorials — Walk, IRL, Scene Studio, voice, vanity names and more** — The tutorial library got a big fill-in: every major part of three.ws that didn't have a walkthrough now has one. New guides cover putting a walking 3D avatar on your own site, placing your agent in your real room with IRL, building a scene in Scene Studio, animating any avatar, turning a selfie into a rigged avatar, importing an avatar by link, viewing a model in AR, giving an agent a real voice with lip-sync, paying for an x402 service from your agent, claiming a .threews.sol name and getting paid by it, reading an agent's on-chain reputation, mining a Solana vanity address, and a no-code getting-started. Every tutorial is grounded in the live product, with copy-paste steps and troubleshooting. (`/tutorials`) `[docs]`- **Affiliate dashboard now shows who you referred** — The referrals dashboard lists each person you referred with their signup date, the revenue they generated, and the commission you earned — not just totals. (`/dashboard/referrals`) `[improvement]`- **Agent payments now produce a signed receipt of exactly what was bought** — Autonomous agent-to-agent payments already run under a signed Intent Mandate (your standing authorization with budget and per-call caps). They now also issue a Cart Mandate for each transaction — a tamper-evident, signed record of the exact endpoint paid, the amount, currency, network, and line items, bound to the authorizing mandate. It comes back with every paid call and can be checked by anyone via a new verification endpoint, so a paid service has cryptographic proof of what its caller agreed to. This completes our alignment with Google's Agent Payments Protocol (AP2), layered cleanly on top of x402 settlement. `[feature, sdk]`- **Arm your agent gets its own setup page** — Configuring your 3D agent to trade Oracle conviction now has a dedicated page at /oracle/arm — a clean, focused setup laid out the way trading bots do it: a live status bar with a big arm switch, a stats strip, and step-by-step cards for entry rules, position sizing and caps, alerts, and simulate-vs-live mode. The Oracle tab now shows your agent's configuration at a glance and links straight to the full editor. (`/oracle/arm`) `[feature, improvement]`@@ -23,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Avatar Studio: full-spectrum color picker and one-tap Looks** — The Color tab in Avatar Studio is no longer limited to a fixed row of swatches. Tap the rainbow chip on any of skin, hair, or outfit and a real color wheel opens — drag for any hue, slide for brightness, type or paste an exact hex code, or use the eyedropper to sample any color on your screen (where your browser supports it). Every color you pick is remembered in a 'Recent' strip so a palette carries from one part of the avatar to the next, and between sessions. New 'Looks' sit above the colors too: one tap themes skin, hair, and outfit together — Noir, Sunset, Arctic, Cyber, Rosé, Forest, Mono, Ember — and a whole picking session counts as a single undo. The wheel loads only when you open it, so the studio stays fast. (`/avatar-studio`) `[feature, improvement]`- **Clearer empty state on the $THREE live-trades feed** — Before the next trade lands, the live-trades panel on the $THREE token page now reads in plain language — 'Live trades will appear here' — with a short note on what it shows, and the technical detail tucked behind an info tooltip. Screen readers announce new trades as they stream in. (`/three-token`) `[improvement]`- **Coin pages stay fast when pump.fun is having a moment** — The /launches coin page pulls creator fee-sharing earnings live from pump.fun. We put that call behind a circuit breaker (built on the well-tested cockatiel library rather than home-grown code): if pump.fun slows down or errors, the breaker trips after a few failures and the page instantly skips that one enrichment instead of every visitor waiting out the timeout. The earnings simply show as unavailable until pump.fun recovers, and the rest of the page — registry, intel, outcome, trader record — was never affected. Same approach is now available platform-wide for other third-party data sources. (`/launches`) `[infra, improvement]`+- **Credits: top up with SOL or $THREE, spend on generation and agents** — You can now keep a prepaid balance on three.ws. Deposit SOL or $THREE from your wallet and it's credited to your account at the live USD value; spend those credits on paid compute like High-quality 3D generation — no per-action wallet popup each time. Holding $THREE still discounts every spend (up to 30%), so the credits you buy go further the bigger your bag. Deposits are verified on-chain and bound to a wallet linked to your account, your balance and full history live at /credits, and a failed generation is automatically refunded. Forge High now accepts credits as a payment option alongside holding $THREE or paying per generation. (`/credits`) `[feature]`- **Describe-it-to-3D no longer shows a confusing third-party billing error** — When you turn a text prompt into a 3D avatar, the first step paints a reference image — and that runs on the free NVIDIA lane by default. If that lane was briefly busy, the request could fall through to a paid backstop that had run out of credit, and the backstop's raw "go purchase credit" message leaked onto your screen. That's gone: any billing or out-of-credit hiccup on a backstop now shows a clean "temporarily unavailable — try again later," the free NVIDIA lane stays the primary path, and a third party's billing page never reaches you. (`/create/prompt`) `[fix]`- **Discover and character feeds load faster under heavy traffic** — The Discover grid and the published-agents (Characters) feed now serve from the edge cache, so a surge of visitors is absorbed at the CDN instead of re-running a database scan on every request. Pages stay fast and consistent even during a rush, and a stale-while-revalidate window keeps them warm between refreshes. (`/discover`) `[improvement, infra]`- **Discover and Marketplace now browse the same way** — Searching, filtering, and sorting agents now work identically on /discover and /marketplace. Both pages share one polished control bar — debounced search, filter chips, and sort — and your choices are saved in the page address, so a filtered view is shareable and the browser back button restores it. Loading, empty, and error states were unified too: a search that matches nothing shows a clear 'no results' panel with a one-click 'Clear filters', and a failed load offers a retry instead of a blank grid. (`/discover`) `[improvement]`@@ -41,6 +44,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Free neural voice for agents — high-quality speech, no API key** — Agents now have a third voice option, 'neural', alongside browser and ElevenLabs. It runs a neural text-to-speech model entirely in your browser (on the GPU where available), so it sounds far better than the robotic built-in browser voice while costing nothing — no API key, no per-word charges, and the audio never leaves your device. Because the model returns exact phoneme timings, lip-sync is locked to the actual speech instead of estimated from text. Pick it under Voice in the agent builder and choose a Kokoro voice like af_bella or am_fenrir. First use downloads the model once. `[feature, improvement]`- **Free photo → 3D is now a one-click engine in Forge** — Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing. (`/forge`) `[feature, improvement]`- **Free roam: walk the tour guide around the page yourself** — The guided tour now has a free-roam mode (the 🧭 button, or press R). Click anywhere on the page and the 3D guide walks there; grab it and drag it around; drag it to the top or bottom edge and the page scrolls so you can walk it up and down the whole page. Press play to drop right back into the tour where you left off. We also stopped the corner walking companion from doubling up: while the guided tour is running, the corner companion steps aside so there's only ever one avatar on screen, and it returns the moment the tour ends. (`/tour`) `[feature, improvement]`+- **Game-Ready export is now a $THREE perk — hold, or pay per export** — Turning a generated or uploaded model into a clean, engine-ready asset — one-click retopology to a poly budget with a PBR texture re-bake, delivered as a GLB plus an FBX for Unity and Unreal — is now a $THREE benefit. Hold $THREE and every Game-Ready export is free; if you don't hold, pay once per export in $THREE without leaving the result view, then the export runs immediately. Text→3D generation at Draft and Standard stays free for everyone. The export runs real GPU retopology on our remesh service, so holders fund it by holding rather than us metering everyone — the same hold-or-pay model already used for High-quality generation. (`/forge`) `[feature]`- **Grind an agent's vanity wallet right on its page — with your CPU cores** — Giving an agent a custom wallet address used to run on our servers, so it was capped at short patterns and would time out and error on anything harder. Now the agent's Wallet → Vanity tab grinds the address in your own browser, exactly like the standalone /vanity-wallet tool: choose how many CPU cores to spend, match case-insensitively for a faster find, watch the live tries-per-second and ETA, and pause or resume anytime. Longer, rarer patterns are now possible with no timeouts. When a match is found, any SOL or tokens in the old wallet are still automatically swept to the new address before the key is swapped — funds are never stranded — and the server verifies the new address truly matches your pattern before storing it. `[fix, feature, improvement]`- **Hardened on-chain confirmations and faster profile loads** — Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically. `[fix, security, improvement]`- **Imported avatars now animate with correct arm and leg orientation** — Animations are authored on one reference rig and retargeted onto whatever avatar you bring — Mixamo, Ready Player Me, VRoid, and more. We found that limbs on those rigs could play roughly 30° off from where they should be, because the retarget replayed each joint's motion in the wrong frame when a rig's rest pose differed from ours. The retarget now preserves each joint's true world-space motion, so idle, walk, and every other clip drive a foreign rig's arms and legs the way they were animated. Avatars matching the reference rig are byte-for-byte unchanged. `[fix, improvement]`diff --git a/api/_lib/credit-deposit.js b/api/_lib/credit-deposit.jsnew file mode 100644index 000000000..86b893e80--- /dev/null+++ b/api/_lib/credit-deposit.js@@ -0,0 +1,200 @@+// Verify an on-chain SOL or $THREE transfer into the platform deposit wallet and+// credit the depositor's prepaid balance (api/_lib/credits.js).+//+// Trust model (server-authoritative — a client "I paid" claim is never trusted):+// 1. The transaction is confirmed and didn't error on-chain.+// 2. A SIGNER of the transaction is a Solana wallet linked to the authenticated+// user — binds the deposit to the right account and stops anyone from+// claiming someone else's transfer by pasting its signature.+// 3. The platform deposit wallet actually received funds — computed from pre/post+// balances (lamport delta for SOL, token-balance delta for $THREE), robust to+// a destination ATA created within the same transaction and to which transfer+// variant was used.+// 4. The credit is idempotent on the tx signature (UNIQUE idempotency_key), so+// the same deposit can never be credited twice.+//+// Deposited funds land in the treasury / x402 receive wallet — the platform's+// prepaid float. Spending credits is internal ledger accounting; the treasury →+// buyback / holder-reflection loop runs from there (see token/config.js economy+// note). Deposits are therefore NOT split on receipt.++import { solanaConnection } from './solana/connection.js';+import { sql } from './db.js';+import { env } from './env.js';+import { creditAccount } from './credits.js';+import { TOKEN_MINT, TOKEN_DECIMALS, treasuryWalletOrNull } from './token/config.js';+import { getTokenPriceUsd } from './token/price.js';+import { solanaMintUsdPrice } from './balances.js';++const SOL_MINT = 'So11111111111111111111111111111111111111112';+const LAMPORTS_PER_SOL = 1_000_000_000;++/**+ * The single Solana address users send deposits to. Defaults to the existing x402+ * Solana receive wallet (then the treasury) so a working deploy needs no new env;+ * set CREDITS_DEPOSIT_WALLET_SOLANA to route deposits to a dedicated wallet.+ */+export function depositWallet() {+ return (+ (process.env.CREDITS_DEPOSIT_WALLET_SOLANA || '').trim() ||+ env.X402_PAY_TO_SOLANA ||+ treasuryWalletOrNull() ||+ null+ );+}++function rpcUrl(network) {+ return network === 'devnet'+ ? env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'+ : env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+}++function depositError(message, status = 422, code = 'deposit_unverified', extra = {}) {+ return Object.assign(new Error(message), { status, code, ...extra });+}++function isSolAddress(s) {+ return typeof s === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);+}++/** Set of Solana addresses linked to a user (user_wallets + legacy wallet_address). */+export async function linkedSolanaWallets(user) {+ const rows = await sql`+ select address from user_wallets where user_id = ${user.id} and chain_type = 'solana'+ `;+ const set = new Set(rows.map((r) => r.address));+ if (user.wallet_address && isSolAddress(user.wallet_address)) set.add(user.wallet_address);+ return set;+}++function accountKeyStr(k) {+ return k?.pubkey?.toString?.() || String(k?.pubkey ?? '');+}++/** Signers of a parsed transaction, as base58 strings. */+function signerSet(tx) {+ const keys = tx.transaction?.message?.accountKeys || [];+ const out = new Set();+ for (const k of keys) if (k.signer) out.add(accountKeyStr(k));+ return out;+}++// Net SPL atomics credited to `owner` for `mint`, from pre/post token balances.+function tokenCreditedTo(tx, { mint, owner }) {+ const pre = tx.meta?.preTokenBalances || [];+ const post = tx.meta?.postTokenBalances || [];+ let delta = 0n;+ for (const p of post) {+ if (p.mint !== mint || p.owner !== owner) continue;+ const before = pre.find((x) => x.accountIndex === p.accountIndex);+ delta += BigInt(p.uiTokenAmount?.amount ?? '0') - BigInt(before?.uiTokenAmount?.amount ?? '0');+ }+ return delta;+}++// Net lamports credited to `owner`, from pre/post native balances (index-aligned+// with accountKeys in a parsed transaction).+function lamportsCreditedTo(tx, owner) {+ const keys = tx.transaction?.message?.accountKeys || [];+ const idx = keys.findIndex((k) => accountKeyStr(k) === owner);+ if (idx < 0) return 0n;+ const pre = BigInt(tx.meta?.preBalances?.[idx] ?? 0);+ const post = BigInt(tx.meta?.postBalances?.[idx] ?? 0);+ return post - pre;+}++/**+ * Verify a deposit transaction and credit the user's prepaid balance.+ * @param {{ user: object, asset: 'SOL'|'THREE', txSignature: string, network?: string }} args+ * @returns {Promise<object>} credit result for the API response+ */+export async function verifyAndCreditDeposit({ user, asset, txSignature, network = 'mainnet' }) {+ const sink = depositWallet();+ if (!sink) throw depositError('the deposit wallet is not configured', 503, 'deposit_unavailable');++ const assetU = String(asset || '').toUpperCase();+ if (assetU !== 'SOL' && assetU !== 'THREE') throw depositError('asset must be SOL or THREE', 400, 'bad_request');+ if (typeof txSignature !== 'string' || txSignature.length < 32 || txSignature.length > 128) {+ throw depositError('a valid tx_signature is required', 400, 'bad_request');+ }++ const connection = solanaConnection({ url: rpcUrl(network), commitment: 'confirmed' });+ let tx;+ try {+ tx = await connection.getParsedTransaction(txSignature, {+ maxSupportedTransactionVersion: 0,+ commitment: 'confirmed',+ });+ } catch {+ throw depositError('transaction not found — it may need more confirmations', 422, 'tx_not_found');+ }+ if (!tx) throw depositError('transaction not found — it may need more confirmations', 422, 'tx_not_found');+ if (tx.meta?.err) throw depositError('transaction failed on-chain', 422, 'tx_failed');++ // Bind the deposit to the authenticated user: a signer must be one of their+ // linked Solana wallets.+ const linked = await linkedSolanaWallets(user);+ const matched = [...signerSet(tx)].find((s) => linked.has(s));+ if (!matched) {+ throw depositError(+ 'this transfer was not signed by a wallet linked to your account — sign in with the sending wallet, or link it, then retry',+ 403,+ 'wallet_not_linked',+ );+ }++ let usd;+ let assetAmount;+ let priceUsd;+ let amount; // human units, for display+ if (assetU === 'SOL') {+ const lamports = lamportsCreditedTo(tx, sink);+ if (lamports <= 0n) {+ throw depositError('no SOL was received at the deposit wallet in this transaction', 422, 'no_funds_received');+ }+ priceUsd = await solanaMintUsdPrice(SOL_MINT);+ if (!(priceUsd > 0)) throw depositError('live SOL price unavailable — try again shortly', 503, 'price_unavailable');+ assetAmount = lamports;+ amount = Number(lamports) / LAMPORTS_PER_SOL;+ usd = amount * priceUsd;+ } else {+ const atomics = tokenCreditedTo(tx, { mint: TOKEN_MINT, owner: sink });+ if (atomics <= 0n) {+ throw depositError('no $THREE was received at the deposit wallet in this transaction', 422, 'no_funds_received');+ }+ const p = await getTokenPriceUsd();+ priceUsd = p.priceUsd;+ assetAmount = atomics;+ amount = Number(atomics) / 10 ** TOKEN_DECIMALS;+ usd = amount * priceUsd;+ }++ usd = Math.round(usd * 1e6) / 1e6;+ if (!(usd > 0)) throw depositError('deposit amount rounds to zero at the current price', 422, 'amount_too_small');++ const res = await creditAccount({+ userId: user.id,+ amountUsd: usd,+ kind: 'deposit',+ refType: assetU === 'SOL' ? 'deposit_sol' : 'deposit_three',+ refId: txSignature,+ txSignature,+ asset: assetU,+ assetAmount,+ priceUsd,+ idempotencyKey: `deposit:${txSignature}`,+ meta: { slot: tx.slot ?? null, signer: matched, amount, network },+ });++ return {+ ok: true,+ replay: res.replay,+ balance_usd: res.balanceUsd,+ credited_usd: res.replay ? 0 : usd,+ usd,+ asset: assetU,+ amount,+ price_usd: priceUsd,+ tx_signature: txSignature,+ };+}diff --git a/api/_lib/credits.js b/api/_lib/credits.jsnew file mode 100644index 000000000..7de201825--- /dev/null+++ b/api/_lib/credits.js@@ -0,0 +1,285 @@+// Prepaid credit wallet — the platform's spend rail for logged-in users.+//+// Top up by depositing SOL or $THREE (api/_lib/credit-deposit.js verifies the+// on-chain transfer and calls creditAccount here); spend on metered actions+// (Forge, …) priced by api/_lib/pricing/catalog.js and discounted by the user's+// $THREE holder tier (api/_lib/three-tier.js). Credits are denominated in USD+// (numeric(20,6)) to match the pricing catalog and token_payments.usd — one+// currency end to end, no second unit to reconcile.+//+// Integrity model (mirrors api/_lib/token/payments.js):+// • credit_accounts holds the rolling balance; credit_ledger is the append-only+// history. Both are written in ONE statement (a CTE) — Neon's HTTP driver has+// no interactive transactions, and a single statement is atomic (an error+// rolls the whole statement back), so balance and ledger can never diverge.+// • Every movement carries an idempotency_key (UNIQUE). A replay rolls back on+// the unique violation and resolves to the prior row, so a retried deposit+// credits once and a retried charge debits once.+// • A debit decrements only `where balance_usd >= amount`, so a spend can never+// drive the balance negative even under concurrent requests.++import { sql } from './db.js';+import { priceForAction } from './pricing/catalog.js';+import { holderDiscountBps } from './three-tier.js';++const CREDIT_KINDS = new Set(['deposit', 'refund', 'grant', 'adjust']);++function isUniqueViolation(err) {+ return err?.code === '23505' || /duplicate key|unique constraint/i.test(err?.message || '');+}++function badRequest(message, code = 'bad_request') {+ return Object.assign(new Error(message), { status: 400, code });+}++// Money is stored as numeric(20,6); pass strings to the driver so JS float drift+// never reaches the column. Six decimals = USDC precision.+function usd6(n) {+ return Number(n).toFixed(6);+}++/** Current balance + lifetime totals for a user. Zeros when no account row yet. */+export async function getCreditAccount(userId) {+ if (!userId) throw badRequest('userId is required');+ const [row] = await sql`+ select balance_usd, lifetime_deposited_usd, lifetime_spent_usd, updated_at+ from credit_accounts where user_id = ${userId} limit 1+ `;+ return {+ balanceUsd: Number(row?.balance_usd ?? 0),+ lifetimeDepositedUsd: Number(row?.lifetime_deposited_usd ?? 0),+ lifetimeSpentUsd: Number(row?.lifetime_spent_usd ?? 0),+ updatedAt: row?.updated_at ?? null,+ };+}++async function priorLedger(idempotencyKey) {+ const [row] = await sql`+ select id, balance_after from credit_ledger where idempotency_key = ${idempotencyKey} limit 1+ `;+ return row || null;+}++/**+ * Add credits (deposit / refund / grant / adjust). Atomic upsert + ledger,+ * idempotent on idempotencyKey. Only a 'deposit' counts toward lifetime_deposited.+ * @returns {Promise<{ balanceUsd: number, ledgerId: string|null, replay: boolean }>}+ */+export async function creditAccount({+ userId,+ amountUsd,+ kind = 'deposit',+ action = null,+ refType = null,+ refId = null,+ txSignature = null,+ asset = null,+ assetAmount = null,+ priceUsd = null,+ idempotencyKey,+ meta = {},+}) {+ if (!userId) throw badRequest('userId is required');+ if (!CREDIT_KINDS.has(kind)) throw badRequest(`invalid credit kind: ${kind}`);+ const amt = Number(amountUsd);+ if (!Number.isFinite(amt) || amt <= 0) throw badRequest('amountUsd must be a positive number');+ if (!idempotencyKey) throw badRequest('idempotencyKey is required');++ const usd = usd6(amt);+ const dep = usd6(kind === 'deposit' ? amt : 0); // lifetime_deposited only tracks real top-ups+ const assetAmountStr = assetAmount == null ? null : String(assetAmount);++ try {+ const [row] = await sql`+ with acct as (+ insert into credit_accounts (user_id, balance_usd, lifetime_deposited_usd, updated_at)+ values (${userId}, ${usd}, ${dep}, now())+ on conflict (user_id) do update+ set balance_usd = credit_accounts.balance_usd + ${usd},+ lifetime_deposited_usd = credit_accounts.lifetime_deposited_usd + ${dep},+ updated_at = now()+ returning balance_usd+ ), led as (+ insert into credit_ledger+ (user_id, kind, amount_usd, balance_after, action, ref_type, ref_id,+ tx_signature, asset, asset_amount, price_usd, idempotency_key, meta)+ select ${userId}, ${kind}, ${usd}, balance_usd, ${action}, ${refType}, ${refId},+ ${txSignature}, ${asset}, ${assetAmountStr}, ${priceUsd}, ${idempotencyKey},+ ${JSON.stringify(meta || {})}::jsonb+ from acct+ returning id, balance_after+ )+ select id, balance_after from led+ `;+ return { balanceUsd: Number(row.balance_after), ledgerId: row.id, replay: false };+ } catch (err) {+ if (isUniqueViolation(err)) {+ const prior = await priorLedger(idempotencyKey);+ return { balanceUsd: Number(prior?.balance_after ?? 0), ledgerId: prior?.id ?? null, replay: true };+ }+ throw err;+ }+}++/**+ * Debit credits for a spend. Atomic conditional decrement + ledger, idempotent on+ * idempotencyKey. Throws a 402 insufficient_credits (with available/required)+ * when the balance is short — the spend never partially applies.+ * @returns {Promise<{ balanceUsd: number, ledgerId: string|null, replay: boolean, chargedUsd: number }>}+ */+export async function debitCredits({+ userId,+ amountUsd,+ action = null,+ refType = null,+ refId = null,+ idempotencyKey,+ meta = {},+}) {+ if (!userId) throw badRequest('userId is required');+ const amt = Number(amountUsd);+ if (!Number.isFinite(amt) || amt <= 0) throw badRequest('amountUsd must be a positive number');+ if (!idempotencyKey) throw badRequest('idempotencyKey is required');++ const usd = usd6(amt);+ const neg = usd6(-amt);++ let rows;+ try {+ rows = await sql`+ with upd as (+ update credit_accounts+ set balance_usd = balance_usd - ${usd},+ lifetime_spent_usd = lifetime_spent_usd + ${usd},+ updated_at = now()+ where user_id = ${userId} and balance_usd >= ${usd}+ returning balance_usd+ ), led as (+ insert into credit_ledger+ (user_id, kind, amount_usd, balance_after, action, ref_type, ref_id, idempotency_key, meta)+ select ${userId}, 'spend', ${neg}, balance_usd, ${action}, ${refType}, ${refId}, ${idempotencyKey},+ ${JSON.stringify(meta || {})}::jsonb+ from upd+ returning id, balance_after+ )+ select id, balance_after from led+ `;+ } catch (err) {+ if (isUniqueViolation(err)) {+ const prior = await priorLedger(idempotencyKey);+ return {+ balanceUsd: Number(prior?.balance_after ?? 0),+ ledgerId: prior?.id ?? null,+ replay: true,+ chargedUsd: 0,+ };+ }+ throw err;+ }++ if (!rows || rows.length === 0) {+ const acct = await getCreditAccount(userId);+ throw Object.assign(new Error('not enough credits — top up to continue'), {+ status: 402,+ code: 'insufficient_credits',+ available_usd: acct.balanceUsd,+ required_usd: amt,+ });+ }+ return { balanceUsd: Number(rows[0].balance_after), ledgerId: rows[0].id, replay: false, chargedUsd: amt };+}++/**+ * Resolve the credit price for an action with the user's $THREE holder discount+ * applied — without charging. Use for display / affordability checks.+ * @returns {Promise<{ action: string, usd: number, label: string, discountBps: number }>}+ */+export async function quoteCreditsForAction({ user, action, usd = undefined }) {+ const discountBps = await holderDiscountBps(user).catch(() => 0);+ const priced = priceForAction(action, { usd, discountBps });+ return { action, usd: priced.usd, label: priced.label, discountBps };+}++/**+ * The metering primitive every paid surface calls: price an action with the+ * caller's holder discount, then debit credits for it. Throws 402+ * insufficient_credits when short. idempotencyKey must be stable per logical+ * charge so a retry never double-debits.+ * @returns {Promise<{ balanceUsd: number, ledgerId: string|null, replay: boolean, chargedUsd: number, pricedUsd: number, discountBps: number, label: string, action: string }>}+ */+export async function chargeCreditsForAction({+ user,+ action,+ usd = undefined,+ refType = null,+ refId = null,+ idempotencyKey,+ meta = {},+}) {+ if (!user?.id) throw badRequest('a signed-in user is required to spend credits', 'unauthorized');+ const discountBps = await holderDiscountBps(user).catch(() => 0);+ const priced = priceForAction(action, { usd, discountBps });+ const debit = await debitCredits({+ userId: user.id,+ amountUsd: priced.usd,+ action,+ refType,+ refId,+ idempotencyKey,+ meta: { ...meta, label: priced.label, discount_bps: discountBps },+ });+ return { ...debit, pricedUsd: priced.usd, discountBps, label: priced.label, action };+}++/** Return credits for an action that was charged but did not deliver. Idempotent. */+export async function refundCredits({+ userId,+ amountUsd,+ action = null,+ refType = null,+ refId = null,+ idempotencyKey,+ meta = {},+}) {+ return creditAccount({+ userId,+ amountUsd,+ kind: 'refund',+ action,+ refType,+ refId,+ idempotencyKey,+ meta,+ });+}++/** Keyset-paginated ledger history (newest first) for a user. */+export async function listLedger({ userId, limit = 25, before = null } = {}) {+ if (!userId) throw badRequest('userId is required');+ const cap = Math.min(Math.max(Number(limit) || 25, 1), 100);+ const rows = await sql`+ select id, kind, amount_usd, balance_after, action, ref_type, ref_id,+ tx_signature, asset, asset_amount, price_usd, created_at+ from credit_ledger+ where user_id = ${userId}+ and (${before}::timestamptz is null or created_at < ${before})+ order by created_at desc+ limit ${cap + 1}+ `;+ const hasMore = rows.length > cap;+ const items = (hasMore ? rows.slice(0, cap) : rows).map((r) => ({+ id: r.id,+ kind: r.kind,+ amount_usd: Number(r.amount_usd),+ balance_after: Number(r.balance_after),+ action: r.action,+ ref_type: r.ref_type,+ ref_id: r.ref_id,+ tx_signature: r.tx_signature,+ asset: r.asset,+ asset_amount: r.asset_amount == null ? null : String(r.asset_amount),+ price_usd: r.price_usd == null ? null : Number(r.price_usd),+ created_at: r.created_at,+ }));+ return { items, next_cursor: hasMore ? items[items.length - 1].created_at : null };+}diff --git a/api/_lib/migrations/20260621200000_credits.sql b/api/_lib/migrations/20260621200000_credits.sqlnew file mode 100644index 000000000..695ab869a--- /dev/null+++ b/api/_lib/migrations/20260621200000_credits.sql@@ -0,0 +1,46 @@+-- Prepaid credit wallet — the platform's spend rail for logged-in users.+--+-- Users top up by depositing SOL or $THREE (verified on-chain by+-- api/_lib/credit-deposit.js) and spend the resulting credits on metered actions+-- (Forge high-tier, …) priced by api/_lib/pricing/catalog.js and discounted by+-- their $THREE holder tier. Credits are denominated in USD (numeric(20,6)) to+-- match the pricing catalog and token_payments.usd — one currency end to end.+--+-- Integrity: credit_accounts holds the rolling balance; credit_ledger is the+-- append-only history. Both are written in ONE statement (a CTE) so a balance+-- change and its ledger row can never diverge. Every movement carries a UNIQUE+-- idempotency_key so a replayed deposit credits once and a replayed charge debits+-- once. A debit only runs `where balance_usd >= amount`, so a spend can never+-- drive the balance negative even under concurrent requests.++create table if not exists credit_accounts (+ user_id uuid primary key references users(id) on delete cascade,+ balance_usd numeric(20, 6) not null default 0 check (balance_usd >= 0),+ lifetime_deposited_usd numeric(20, 6) not null default 0,+ lifetime_spent_usd numeric(20, 6) not null default 0,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++create table if not exists credit_ledger (+ id uuid primary key default gen_random_uuid(),+ user_id uuid not null references users(id) on delete cascade,+ -- 'deposit' (on-chain top-up), 'spend' (metered action), 'refund' (failed+ -- action returned), 'grant' (promo/comp), 'adjust' (manual correction).+ kind text not null check (kind in ('deposit', 'spend', 'refund', 'grant', 'adjust')),+ amount_usd numeric(20, 6) not null, -- signed: + credit, - debit+ balance_after numeric(20, 6) not null, -- balance immediately after this row+ action text, -- pricing-catalog action id for spends+ ref_type text, -- 'forge' | 'deposit_sol' | 'deposit_three' | …+ ref_id text,+ tx_signature text, -- on-chain deposit signature (deposits only)+ asset text, -- 'SOL' | 'THREE' for deposits+ asset_amount numeric(40, 0), -- atomic amount deposited (lamports / $THREE atomics)+ price_usd numeric(38, 18), -- asset USD price at deposit time+ idempotency_key text not null unique, -- replay guard for deposits AND charges+ meta jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);++create index if not exists credit_ledger_user_created_idx on credit_ledger (user_id, created_at desc);+create index if not exists credit_ledger_tx_idx on credit_ledger (tx_signature) where tx_signature is not null;diff --git a/api/credits/deposit.js b/api/credits/deposit.jsnew file mode 100644index 000000000..f1f652796--- /dev/null+++ b/api/credits/deposit.js@@ -0,0 +1,55 @@+// POST /api/credits/deposit — verify an on-chain SOL or $THREE transfer into the+// platform deposit wallet and credit the caller's prepaid balance.+//+// Body: { asset: 'SOL'|'THREE', tx_signature: string, network?: 'mainnet'|'devnet' }+//+// Server-authoritative: the signature alone proves nothing. credit-deposit.js+// confirms the tx, requires a signer linked to this account, checks the deposit+// wallet actually received funds, and credits idempotently on the signature.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, error, json, method, wrap, readJson, rateLimited, respondError } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { verifyAndCreditDeposit } from '../_lib/credit-deposit.js';++async function resolveUser(req, res) {+ const session = await getSessionUser(req, res);+ if (session) return session;+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) {+ const [u] = await sql`+ select id, wallet_address from users where id = ${bearer.userId} and deleted_at is null limit 1+ `;+ return u || null;+ }+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const user = await resolveUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in to deposit credits');++ const body = await readJson(req).catch(() => null);+ const asset = String(body?.asset || '').toUpperCase();+ const txSignature = typeof body?.tx_signature === 'string' ? body.tx_signature.trim() : '';+ const network = body?.network === 'devnet' ? 'devnet' : 'mainnet';++ if (!txSignature) return error(res, 400, 'bad_request', 'tx_signature is required');+ if (asset !== 'SOL' && asset !== 'THREE') return error(res, 400, 'bad_request', 'asset must be SOL or THREE');++ try {+ const result = await verifyAndCreditDeposit({ user, asset, txSignature, network });+ return json(res, 200, result);+ } catch (err) {+ return respondError(res, err.status || 500, err.code || 'deposit_failed', err, {+ ...(Number.isFinite(err.available_usd) ? { available_usd: err.available_usd } : {}),+ });+ }+});diff --git a/api/credits/index.js b/api/credits/index.jsnew file mode 100644index 000000000..f51a5c3f8--- /dev/null+++ b/api/credits/index.js@@ -0,0 +1,63 @@+// GET /api/credits — the authenticated caller's prepaid credit balance, recent+// ledger, where to deposit (SOL or $THREE), and what credits buy. Powers the+// /credits page and the in-app balance pill. Resolves a browser session cookie+// OR a Bearer access token (so first-party clients and agents both read it).++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { sql } from '../_lib/db.js';+import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getCreditAccount, listLedger } from '../_lib/credits.js';+import { depositWallet } from '../_lib/credit-deposit.js';+import { TOKEN_MINT, TOKEN_SYMBOL, TOKEN_DECIMALS } from '../_lib/token/config.js';+import { publicCatalog } from '../_lib/pricing/catalog.js';++async function resolveUser(req, res) {+ const session = await getSessionUser(req, res);+ if (session) return session;+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) {+ const [u] = await sql`+ select id, wallet_address from users where id = ${bearer.userId} and deleted_at is null limit 1+ `;+ return u || null;+ }+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const user = await resolveUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in to view your credits');++ const [acct, ledger] = await Promise.all([+ getCreditAccount(user.id),+ listLedger({ userId: user.id, limit: 25 }),+ ]);++ // What credits buy: the fixed-price compute actions (variable / marketplace+ // prices are set per call, so they're excluded from this headline list).+ const buys = publicCatalog().filter((e) => e.usd != null && e.usd > 0);++ return json(res, 200, {+ balance_usd: acct.balanceUsd,+ lifetime_deposited_usd: acct.lifetimeDepositedUsd,+ lifetime_spent_usd: acct.lifetimeSpentUsd,+ deposit: {+ wallet: depositWallet(),+ network: 'mainnet',+ accepts: ['SOL', 'THREE'],+ three_mint: TOKEN_MINT,+ three_symbol: TOKEN_SYMBOL,+ three_decimals: TOKEN_DECIMALS,+ },+ buys,+ ledger: ledger.items,+ next_cursor: ledger.next_cursor,+ });+});diff --git a/api/forge.js b/api/forge.jsindex 3d91bb607..b66fec5d0 100644--- a/api/forge.js+++ b/api/forge.js@@ -79,6 +79,13 @@ import {redeemForgePayment,releaseForgePayment,} from './_lib/forge-high-payment.js';+import { getSessionUser } from './_lib/auth.js';+import {+ chargeCreditsForAction,+ quoteCreditsForAction,+ getCreditAccount,+ refundCredits,+} from './_lib/credits.js';// Holder perk (Lever 2): a presented, verified $THREE tier pass lifts the free// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable@@ -470,6 +477,12 @@ async function startJob(req, res) {// just before dispatch, and released if the generation fails before delivery.let paidHigh = null;+ // Prepaid-credit lane (pay_with:'credits'): set to { user, action, ref,+ // ledgerId?, chargedUsd? } once a signed-in user opts to spend their credit+ // balance instead of holding $THREE or paying per-call. Validated at the gate,+ // debited just before dispatch, refunded if the generation fails.+ let creditsCharge = null;+// Fingerprint for in-flight request coalescing, set once the lane is resolved// below. Null disables coalescing (high tier, which is paid/gated per caller and// must never hand one payer's job to another).@@ -506,9 +519,42 @@ async function startJob(req, res) {// generation instead of holding. Validate it read-only here; the single-use// claim is taken atomically just before dispatch (see paidHigh below). A// missing/invalid proof falls through to the normal hold-or-pay 402.+ const payWith = typeof body?.pay_with === 'string' ? body.pay_with.toLowerCase() : '';const paymentId = typeof body?.payment_id === 'string' ? body.payment_id.trim() : '';const refId = typeof body?.ref_id === 'string' ? body.ref_id.trim() : '';- if (paymentId && refId) {+ if (payWith === 'credits') {+ // Prepaid-credit lane: a signed-in user spends their balance instead of+ // holding $THREE or paying per-call. Affordability is checked here; the+ // single-use debit happens just before dispatch and is refunded if the+ // job fails (see creditsCharge in the try/finally below).+ const creditUser = await getSessionUser(req).catch(() => null);+ if (!creditUser) {+ return json(res, 401, {+ error: 'unauthorized',+ feature: 'forge.high',+ top_up_url: '/credits',+ message: 'Sign in to pay with credits.',+ });+ }+ let priceUsd;+ try {+ priceUsd = (await quoteCreditsForAction({ user: creditUser, action: 'forge.high' })).usd;+ } catch {+ priceUsd = Number(priceForAction('forge.high').usd) || 0;+ }+ const acct = await getCreditAccount(creditUser.id);+ if (acct.balanceUsd < priceUsd) {+ return json(res, 402, {+ error: 'insufficient_credits',+ feature: 'forge.high',+ price_usd: priceUsd,+ balance_usd: acct.balanceUsd,+ top_up_url: '/credits',+ message: `Generating a High model costs $${priceUsd.toFixed(2)} in credits — your balance is $${acct.balanceUsd.toFixed(2)}. Top up to continue.`,+ });+ }+ creditsCharge = { user: creditUser, action: 'forge.high', ref: refId || randomUUID() };+ } else if (paymentId && refId) {try {const proof = await assertForgePayment({ paymentId, refId });paidHigh = { paymentId, refId, settledAt: proof.payment.settledAt };@@ -698,6 +744,36 @@ async function startJob(req, res) {paidHigh.redeemed = true;}+ // Prepaid-credit charge: debit now, immediately before provider work, so+ // every cheap failure above left the balance untouched. Idempotent on the+ // client ref; the finally refunds it if the job fails before delivery.+ if (creditsCharge && !creditsCharge.ledgerId) {+ try {+ const charged = await chargeCreditsForAction({+ user: creditsCharge.user,+ action: creditsCharge.action,+ refType: 'forge',+ refId: creditsCharge.ref,+ idempotencyKey: `forge:credits:${creditsCharge.ref}`,+ meta: { tier: 'high' },+ });+ creditsCharge.ledgerId = charged.ledgerId;+ creditsCharge.chargedUsd = charged.chargedUsd;+ } catch (err) {+ if (err.code === 'insufficient_credits') {+ return json(res, 402, {+ error: 'insufficient_credits',+ feature: 'forge.high',+ available_usd: err.available_usd,+ required_usd: err.required_usd,+ top_up_url: '/credits',+ message: err.message,+ });+ }+ throw err;+ }+ }+// ── Sketch path (TripoSG-scribble, self-host) ───────────────────────────// The drawing + prompt go straight to the TripoSG worker's scribble// pipeline. Geometry only — no synthesized intermediate view, no textures;@@ -1314,6 +1390,19 @@ async function startJob(req, res) {if (paidHigh?.redeemed && res.statusCode >= 400) {await releaseForgePayment({ paymentId: paidHigh.paymentId }).catch(() => {});}+ // A charged prepaid generation that did NOT deliver (any non-2xx exit) is+ // refunded so credits are never spent on a failed job.+ if (creditsCharge?.ledgerId && creditsCharge.chargedUsd > 0 && res.statusCode >= 400) {+ await refundCredits({+ userId: creditsCharge.user.id,+ amountUsd: creditsCharge.chargedUsd,+ action: creditsCharge.action,+ refType: 'forge',+ refId: creditsCharge.ref,+ idempotencyKey: `forge:credits:refund:${creditsCharge.ledgerId}`,+ meta: { reason: 'generation_failed' },+ }).catch(() => {});+ }}}diff --git a/data/changelog.json b/data/changelog.jsonindex 75db5bebb..25ee606eb 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,27 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-21",+ "title": "Credits: top up with SOL or $THREE, spend on generation and agents",+ "summary": "You can now keep a prepaid balance on three.ws. Deposit SOL or $THREE from your wallet and it's credited to your account at the live USD value; spend those credits on paid compute like High-quality 3D generation — no per-action wallet popup each time. Holding $THREE still discounts every spend (up to 30%), so the credits you buy go further the bigger your bag. Deposits are verified on-chain and bound to a wallet linked to your account, your balance and full history live at /credits, and a failed generation is automatically refunded. Forge High now accepts credits as a payment option alongside holding $THREE or paying per generation.",+ "tags": ["feature"],+ "link": "/credits"+ },+ {+ "date": "2026-06-21",+ "title": "13 new step-by-step tutorials — Walk, IRL, Scene Studio, voice, vanity names and more",+ "summary": "The tutorial library got a big fill-in: every major part of three.ws that didn't have a walkthrough now has one. New guides cover putting a walking 3D avatar on your own site, placing your agent in your real room with IRL, building a scene in Scene Studio, animating any avatar, turning a selfie into a rigged avatar, importing an avatar by link, viewing a model in AR, giving an agent a real voice with lip-sync, paying for an x402 service from your agent, claiming a .threews.sol name and getting paid by it, reading an agent's on-chain reputation, mining a Solana vanity address, and a no-code getting-started. Every tutorial is grounded in the live product, with copy-paste steps and troubleshooting.",+ "tags": ["docs"],+ "link": "/tutorials"+ },+ {+ "date": "2026-06-21",+ "title": "Game-Ready export is now a $THREE perk — hold, or pay per export",+ "summary": "Turning a generated or uploaded model into a clean, engine-ready asset — one-click retopology to a poly budget with a PBR texture re-bake, delivered as a GLB plus an FBX for Unity and Unreal — is now a $THREE benefit. Hold $THREE and every Game-Ready export is free; if you don't hold, pay once per export in $THREE without leaving the result view, then the export runs immediately. Text→3D generation at Draft and Standard stays free for everyone. The export runs real GPU retopology on our remesh service, so holders fund it by holding rather than us metering everyone — the same hold-or-pay model already used for High-quality generation.",+ "tags": ["feature"],+ "link": "/forge"+ },{"date": "2026-06-21","title": "Our 3D guided tour is now a standalone package any site can use",diff --git a/data/pages.json b/data/pages.jsonindex c9281c08e..2ecf97122 100644--- a/data/pages.json+++ b/data/pages.json@@ -971,6 +971,14 @@"title": "Account","description": "Sign-in, dashboard, billing.","pages": [+ {+ "path": "/credits",+ "title": "Credits",+ "description": "Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-06-21"+ },{"path": "/login","title": "Sign in",diff --git a/docs/audits/gap-inventory.json b/docs/audits/gap-inventory.jsonnew file mode 100644index 000000000..978a93367--- /dev/null+++ b/docs/audits/gap-inventory.json@@ -0,0 +1,1338 @@+{+ "summary": {+ "generatedBy": "prompt 01 — production audit",+ "note": "vendored=true entries are third-party code (three.js editor, mediapipe wasm, codemirror, draco, lobehub, *.bundle.js) and are NOT first-party gaps. mockData is empty: all grep hits for sample/mock/hardcoded were triaged as false positives (no shipped mock arrays). deadPaths line:0 entries are runtime/live-site findings keyed to a page surface rather than a source line.",+ "counts": {+ "todos_total": 81,+ "todos_firstParty": 10,+ "emptyCatches_total": 126,+ "emptyCatches_firstParty": 85,+ "mockData": 0,+ "deadPaths": 15+ }+ },+ "todos": [+ {+ "file": "src/widget-types.js",+ "line": 5,+ "snippet": "// widgets save their config but the runtime renders a \"coming soon\" banner",+ "vendored": false+ },+ {+ "file": "src/game/npc/npc-services.js",+ "line": 3,+ "snippet": "// from your wallet, and the service runs for real — no mocks, no \"coming soon\".",+ "vendored": false+ },+ {+ "file": "src/game/npc/npc-catalog.js",+ "line": 11,+ "snippet": "// on-chain in USDC, 24/7. No \"coming soon\", no mocks.",+ "vendored": false+ },+ {+ "file": "src/pinning/web3-storage.js",+ "line": 8,+ "snippet": "* Directory pinning requires CAR format (not implemented here). Use pinata when",+ "vendored": false+ },+ {+ "file": "src/create.js",+ "line": 62,+ "snippet": "if (title) title.textContent = 'Talking avatar video · coming soon';",+ "vendored": false+ },+ {+ "file": "src/create.js",+ "line": 168,+ "snippet": "showStatus('Talking avatar video is coming soon — stay tuned.', 'info');",+ "vendored": false+ },+ {+ "file": "src/scene-studio/vendor/js/Sidebar.Material.js",+ "line": 491,+ "snippet": "// TODO Find a easier to maintain approach",+ "vendored": true+ },+ {+ "file": "src/scene-studio/vendor/js/Sidebar.Material.js",+ "line": 533,+ "snippet": "// TODO Copy other references in the scene graph",+ "vendored": true+ },+ {+ "file": "src/scene-studio/vendor/js/Script.js",+ "line": 227,+ "snippet": "signals.materialChanged.dispatch( currentObject, 0 ); // TODO: Add multi-material support",+ "vendored": true+ },+ {+ "file": "src/scene-studio/vendor/js/Script.js",+ "line": 493,+ "snippet": "// TODO: Adds multi-material support",+ "vendored": true+ },+ {+ "file": "src/scene-studio/vendor/js/libs/app.js",+ "line": 235,+ "snippet": "dispatch( events.update, { time: time * 1000, delta: 0 /* TODO */ } );",+ "vendored": true+ },+ {+ "file": "src/scene-studio/vendor/js/Menubar.File.js",+ "line": 264,+ "snippet": "// TODO: Change to DRACOExporter's parse( geometry, onParse )?",+ "vendored": true+ },+ {+ "file": "src/solana/vanity/wasm/vanity_grinder.js",+ "line": 139,+ "snippet": "// TODO we could test for more things here, like `Set`s and `Map`s.",+ "vendored": true+ },+ {+ "file": "public/studio/launch-panel.js",+ "line": 429,+ "snippet": "// 'mayhem' (pump.fun mayhem mode), 'usdc' (USDC-denominated agent — coming soon)",+ "vendored": false+ },+ {+ "file": "public/scene-studio/libs/codemirror/mode/javascript.js",+ "line": 285,+ "snippet": "// FIXME function decls are also not block scoped",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 7764,+ "snippet": "throw new Error(\"inputStyle can not (yet) be changed in a running editor\") // FIXME",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 9320,+ "snippet": "// FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems",+ "vendored": true+ },+ {+ "file": "public/scene-studio/app/app.js",+ "line": 235,+ "snippet": "dispatch( events.update, { time: time * 1000, delta: 0 /* TODO */ } );",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 183,+ "snippet": "// TODO(sbc): Make this the default even without STRICT enabled.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 269,+ "snippet": "// TODO(sbc): Should we remove printing and leave it up to whoever",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 277,+ "snippet": "// FIXME This approach does not work in Wasm EH because it currently does not assume",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 280,+ "snippet": "// we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 285,+ "snippet": "// TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 378,+ "snippet": "// TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 640,+ "snippet": "// actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 1815,+ "snippet": "// TODO we should allow people to just pass in a complete filename instead",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 2169,+ "snippet": "// TODO: check for O_SEARCH? (== search for dir only)",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 3071,+ "snippet": "// TODO deprecate the old functionality of a single",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 3314,+ "snippet": "// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 3771,+ "snippet": "// TODO: in theory we should write to the winsize struct that gets",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 3785,+ "snippet": "// TODO: technically, this ioctl call should change the window size.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 4270,+ "snippet": "// TODO: assert if anything else is given?",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 4549,+ "snippet": "// TODO: Use (malleable) environment variables instead of system settings.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 5047,+ "snippet": "// TODO: initial pass to detect ranges we need to upload, might not need",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 5073,+ "snippet": "// TODO: Once the bug is fixed and shipped in Safari, adjust the Safari",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 5208,+ "snippet": "// TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 5993,+ "snippet": "abort(\"TODO: Implement asyncify-free WaitAny for timeout=0\");",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 7546,+ "snippet": "// TODO: Use the descriptor.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 182,+ "snippet": "// TODO(sbc): Make this the default even without STRICT enabled.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 268,+ "snippet": "// TODO(sbc): Should we remove printing and leave it up to whoever",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 276,+ "snippet": "// FIXME This approach does not work in Wasm EH because it currently does not assume",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 279,+ "snippet": "// we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 284,+ "snippet": "// TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 381,+ "snippet": "// TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 643,+ "snippet": "// actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 1818,+ "snippet": "// TODO we should allow people to just pass in a complete filename instead",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 2172,+ "snippet": "// TODO: check for O_SEARCH? (== search for dir only)",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 3074,+ "snippet": "// TODO deprecate the old functionality of a single",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 3317,+ "snippet": "// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 3774,+ "snippet": "// TODO: in theory we should write to the winsize struct that gets",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 3788,+ "snippet": "// TODO: technically, this ioctl call should change the window size.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 4273,+ "snippet": "// TODO: assert if anything else is given?",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 4552,+ "snippet": "// TODO: Use (malleable) environment variables instead of system settings.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 5050,+ "snippet": "// TODO: initial pass to detect ranges we need to upload, might not need",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 5076,+ "snippet": "// TODO: Once the bug is fixed and shipped in Safari, adjust the Safari",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 5211,+ "snippet": "// TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 5996,+ "snippet": "abort(\"TODO: Implement asyncify-free WaitAny for timeout=0\");",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 7549,+ "snippet": "// TODO: Use the descriptor.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 183,+ "snippet": "// TODO(sbc): Make this the default even without STRICT enabled.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 269,+ "snippet": "// TODO(sbc): Should we remove printing and leave it up to whoever",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 277,+ "snippet": "// FIXME This approach does not work in Wasm EH because it currently does not assume",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 280,+ "snippet": "// we don't have a way of throwing a wasm trap from JS. TODO Make a JS API that",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 285,+ "snippet": "// TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure gets fixed.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 378,+ "snippet": "// TODO: Due to Closure regression https://github.com/google/closure-compiler/issues/3193, the above line no longer optimizes out down to the following line.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 640,+ "snippet": "// actually compiled in because application is not doing any GL operations. TODO: Ideally if GL is not being used, this function",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 1815,+ "snippet": "// TODO we should allow people to just pass in a complete filename instead",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 2169,+ "snippet": "// TODO: check for O_SEARCH? (== search for dir only)",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 3071,+ "snippet": "// TODO deprecate the old functionality of a single",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 3314,+ "snippet": "// TODO: Use mozResponseArrayBuffer, responseStream, etc. if available.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 3771,+ "snippet": "// TODO: in theory we should write to the winsize struct that gets",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 3785,+ "snippet": "// TODO: technically, this ioctl call should change the window size.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 4270,+ "snippet": "// TODO: assert if anything else is given?",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 4549,+ "snippet": "// TODO: Use (malleable) environment variables instead of system settings.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 5047,+ "snippet": "// TODO: initial pass to detect ranges we need to upload, might not need",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 5073,+ "snippet": "// TODO: Once the bug is fixed and shipped in Safari, adjust the Safari",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 5208,+ "snippet": "// TODO: Remove this line, target '#canvas' should refer only to Module['canvas'], not to GL.offscreenCanvases['canvas'] - but need stricter tests to be able to remove this line.",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 5993,+ "snippet": "abort(\"TODO: Implement asyncify-free WaitAny for timeout=0\");",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 7546,+ "snippet": "// TODO: Use the descriptor.",+ "vendored": true+ },+ {+ "file": "api/openapi-json.js",+ "line": 11,+ "snippet": "// MPP (Stripe/Tempo) is not implemented, so it is intentionally not advertised",+ "vendored": false+ },+ {+ "file": "api/pump-fun-mcp.js",+ "line": 249,+ "snippet": "if (!upstream) throw rpcError(-32601, `tool \"${name}\" not implemented`);",+ "vendored": false+ },+ {+ "file": "workers/pump-fun-mcp/worker.js",+ "line": 265,+ "snippet": "if (!upstream) throw rpcError(-32601, `tool \"${name}\" not implemented`);",+ "vendored": false+ }+ ],+ "emptyCatches": [+ {+ "file": "src/walk-net.js",+ "line": 47,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/walk-net.js",+ "line": 60,+ "snippet": "try { isProd = import.meta?.env?.PROD === true; } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/editor/texture-inspector.js",+ "line": 318,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "src/editor/texture-inspector.js",+ "line": 468,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "src/editor/index.js",+ "line": 239,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "src/editor/scene-explorer.js",+ "line": 212,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "src/editor/scene-explorer.js",+ "line": 261,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "src/editor/material-editor.js",+ "line": 178,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "src/editor/publish-modal.js",+ "line": 68,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/editor/publish-modal.js",+ "line": 121,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/editor/publish-modal.js",+ "line": 152,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/editor/publish-modal.js",+ "line": 193,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/account.js",+ "line": 293,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/runtime/data-reactive.js",+ "line": 189,+ "snippet": "try { ac.abort(); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/play-agent-wallet.js",+ "line": 39,+ "snippet": "try { isDev = import.meta?.env?.DEV === true; } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/game/community-net.js",+ "line": 56,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/game/community-net.js",+ "line": 66,+ "snippet": "try { isProd = import.meta?.env?.PROD === true; } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/avatar-drop.js",+ "line": 407,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/avatar-drop.js",+ "line": 432,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 40,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 49,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 57,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 125,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 219,+ "snippet": "try { sessionStorage.setItem('selfie:pendingJobId', submitData.jobId); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 223,+ "snippet": "try { sessionStorage.removeItem('selfie:pendingJobId'); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 312,+ "snippet": "try { sessionStorage.setItem('selfie:pendingJobId', jobId); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 428,+ "snippet": "try { bitmap.close?.(); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-pipeline.js",+ "line": 437,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/create-review.js",+ "line": 414,+ "snippet": "try { window.__twsGuide?.complete('create'); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/create-review.js",+ "line": 439,+ "snippet": "try { window.__twsGuide?.complete('create'); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/permissions/grant-modal.js",+ "line": 426,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/permissions/grant-modal.js",+ "line": 1004,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/avatar-creator.js",+ "line": 23,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/avatar-creator.js",+ "line": 221,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/app.js",+ "line": 1519,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/api-playground.js",+ "line": 90,+ "snippet": "try { localStorage.removeItem(PG_KEY_STORE); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/api-playground.js",+ "line": 91,+ "snippet": "try { pgS.key.value = sessionStorage.getItem(PG_KEY_STORE) || ''; } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/api-playground.js",+ "line": 97,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/api-playground.js",+ "line": 289,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/api-playground.js",+ "line": 351,+ "snippet": "}).catch(function() {});",+ "vendored": false+ },+ {+ "file": "src/irl-net.js",+ "line": 53,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/irl-net.js",+ "line": 60,+ "snippet": "try { isProd = import.meta?.env?.PROD === true; } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/dashboard-next/pages/brain.js",+ "line": 687,+ "snippet": "try { document.dispatchEvent(new CustomEvent('three-ws:guide', { detail: { step: 'brain' } })); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/dashboard-next/pages/home.js",+ "line": 810,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/selfie-modal.js",+ "line": 607,+ "snippet": "try { bitmap.close?.(); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/scene-studio/vendor/js/libs/ui.js",+ "line": 507,+ "snippet": "} catch ( exception ) {}",+ "vendored": true+ },+ {+ "file": "src/demo/os-studio.js",+ "line": 37,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "src/demo/os-hub.js",+ "line": 61,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/search.js",+ "line": 229,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/search.js",+ "line": 452,+ "snippet": "fetchFeatures().catch(function () {});",+ "vendored": false+ },+ {+ "file": "public/search.js",+ "line": 453,+ "snippet": "fetchSkills().catch(function () {});",+ "vendored": false+ },+ {+ "file": "public/widget-client.js",+ "line": 76,+ "snippet": "try { any[j](msg.method, msg.params || {}); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/widget-client.js",+ "line": 171,+ "snippet": "try { this._pending[id].reject(new Error('client closed')); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/nav-auth.js",+ "line": 46,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/x402-paywall.js",+ "line": 254,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/x402-paywall.js",+ "line": 539,+ "snippet": "try { localStorage.removeItem(storageKey(endpoint)); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/nav.js",+ "line": 117,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/nav.js",+ "line": 554,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/nav.js",+ "line": 564,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/nav.js",+ "line": 585,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/lobehub/iframe/boot.js",+ "line": 99,+ "snippet": "} catch (_) {}",+ "vendored": true+ },+ {+ "file": "public/lobehub/iframe/boot.js",+ "line": 312,+ "snippet": "} catch (_) {}",+ "vendored": true+ },+ {+ "file": "public/lobehub/iframe/boot.js",+ "line": 414,+ "snippet": "} catch (_) {}",+ "vendored": true+ },+ {+ "file": "public/x402.js",+ "line": 53,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/x402.js",+ "line": 1714,+ "snippet": "try { parsed = await res.clone().json(); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/notifications.js",+ "line": 433,+ "snippet": "}).catch(function () {});",+ "vendored": false+ },+ {+ "file": "public/notifications.js",+ "line": 443,+ "snippet": ".catch(function () {});",+ "vendored": false+ },+ {+ "file": "public/x402-discover.js",+ "line": 21,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/three/basis/basis_transcoder.js",+ "line": 9,+ "snippet": "var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window==\"object\";var ENVIRONMENT_IS_WORKER",+ "vendored": true+ },+ {+ "file": "public/three/draco/draco_decoder.js",+ "line": 22,+ "snippet": ")(info)},instantiate:function(binary,info){return{then:function(ok){var module=new WebAssembly.Module(binary);ok({\"instance\":new WebAssembly.Instance(module,info)})}}},RuntimeError:Error};wasmBinary=[];if(typeof WebAssembly!=\"object\"){abort",+ "vendored": true+ },+ {+ "file": "public/three/draco/gltf/draco_decoder.js",+ "line": 21,+ "snippet": ")(info)},instantiate:function(binary,info){return{then:function(ok){var module=new WebAssembly.Module(binary);ok({\"instance\":new WebAssembly.Instance(module,info)})}}},RuntimeError:Error};wasmBinary=[];if(typeof WebAssembly!=\"object\"){abort",+ "vendored": true+ },+ {+ "file": "public/three/draco/gltf/draco_wasm_wrapper.js",+ "line": 37,+ "snippet": "for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,e+100663296);var g=Math;d=Math.max(e,d);g=g.min.call(g,2147483648,d+(65536-d%65536)%65536);a:{d=ja.buffer;try{ja.grow(g-d.byteLength+65535>>>16);l();var t=1;break a}catch(aa){}t=void 0}if",+ "vendored": true+ },+ {+ "file": "public/three/draco/draco_wasm_wrapper.js",+ "line": 37,+ "snippet": "1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,e+100663296);var g=Math;d=Math.max(e,d);g=g.min.call(g,2147483648,d+(65536-d%65536)%65536);a:{d=ja.buffer;try{ja.grow(g-d.byteLength+65535>>>16);A();var u=1;break a}catch(X){}u=void 0}if(u)return!0",+ "vendored": true+ },+ {+ "file": "public/motion-path.js",+ "line": 131,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/embed.js",+ "line": 351,+ "snippet": "if (newVal) this.play(newVal).catch(function () {});",+ "vendored": false+ },+ {+ "file": "public/scene-studio/libs/acorn/acorn.js",+ "line": 2716,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/acorn/acorn_loose.js",+ "line": 1243,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/ternjs/polyfill.js",+ "line": 64,+ "snippet": "if (!window.JSON) (function(){var e=void 0,i=!0,k=null,l={}.toString,m,n,p=\"function\"===typeof define&&define.c,q=!p&&\"object\"==typeof exports&&exports;q||p?\"object\"==typeof JSON&&JSON?p?q=JSON:(q.stringify=JSON.stringify,q.parse=JSON.parse",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/ternjs/polyfill.js",+ "line": 67,+ "snippet": "q.parse('{\"A\":[1,true,false,null,\"\\\\u0000\\\\b\\\\n\\\\f\\\\r\\\\t\"]}');if(a=d.a.length==5&&d.a[0]==1){try{a=!q.parse('\"\\t\"')}catch(o){}if(a)try{a=q.parse(\"01\")!=1}catch(g){}}}}catch(h){a=false}if(!j)return a}return c&&a}}",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 144,+ "snippet": "{ selectInput = function(node) { try { node.select(); } catch(_e) {} }; }",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 689,+ "snippet": "catch(e) {}",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 6601,+ "snippet": "catch(e$1){}",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 8952,+ "snippet": "catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 9506,+ "snippet": "catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM",+ "vendored": true+ },+ {+ "file": "public/scene-studio/libs/codemirror/codemirror.js",+ "line": 9732,+ "snippet": "} catch(e) {}",+ "vendored": true+ },+ {+ "file": "public/scene-studio/basis/basis_transcoder.js",+ "line": 9,+ "snippet": "var Module=moduleArg;var readyPromiseResolve,readyPromiseReject;var readyPromise=new Promise((resolve,reject)=>{readyPromiseResolve=resolve;readyPromiseReject=reject});var ENVIRONMENT_IS_WEB=typeof window==\"object\";var ENVIRONMENT_IS_WORKER",+ "vendored": true+ },+ {+ "file": "public/scene-studio/draco/draco_decoder.js",+ "line": 22,+ "snippet": ")(info)},instantiate:function(binary,info){return{then:function(ok){var module=new WebAssembly.Module(binary);ok({\"instance\":new WebAssembly.Instance(module,info)})}}},RuntimeError:Error};wasmBinary=[];if(typeof WebAssembly!=\"object\"){abort",+ "vendored": true+ },+ {+ "file": "public/scene-studio/draco/gltf/draco_decoder.js",+ "line": 21,+ "snippet": ")(info)},instantiate:function(binary,info){return{then:function(ok){var module=new WebAssembly.Module(binary);ok({\"instance\":new WebAssembly.Instance(module,info)})}}},RuntimeError:Error};wasmBinary=[];if(typeof WebAssembly!=\"object\"){abort",+ "vendored": true+ },+ {+ "file": "public/scene-studio/draco/gltf/draco_wasm_wrapper.js",+ "line": 37,+ "snippet": "for(var c=1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,e+100663296);var g=Math;d=Math.max(e,d);g=g.min.call(g,2147483648,d+(65536-d%65536)%65536);a:{d=ja.buffer;try{ja.grow(g-d.byteLength+65535>>>16);l();var t=1;break a}catch(aa){}t=void 0}if",+ "vendored": true+ },+ {+ "file": "public/scene-studio/draco/draco_wasm_wrapper.js",+ "line": 37,+ "snippet": "1;4>=c;c*=2){var d=b*(1+.2/c);d=Math.min(d,e+100663296);var g=Math;d=Math.max(e,d);g=g.min.call(g,2147483648,d+(65536-d%65536)%65536);a:{d=ja.buffer;try{ja.grow(g-d.byteLength+65535>>>16);A();var u=1;break a}catch(X){}u=void 0}if(u)return!0",+ "vendored": true+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 80,+ "snippet": "try { return new URL(SCRIPT.src).origin; } catch (e) {}",+ "vendored": false+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 156,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 161,+ "snippet": "try { arr[i](detail); } catch (e) {}",+ "vendored": false+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 178,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 275,+ "snippet": "try { arr[i](detail); } catch (e) {}",+ "vendored": false+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 299,+ "snippet": "try { iframe.contentWindow.postMessage(envelope(type, payload), origin); } catch (e) {}",+ "vendored": false+ },+ {+ "file": "public/walk-embed-sdk.js",+ "line": 309,+ "snippet": "if (name === 'ready' && ready) { try { cb(ready); } catch (e) {} }",+ "vendored": false+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 1602,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 2133,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 2505,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 3140,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 4744,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_internal.js",+ "line": 8330,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 1605,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 2136,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 2508,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 3143,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 4747,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_module_internal.js",+ "line": 8333,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 1602,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 2133,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 2505,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 3140,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/vendor/mediapipe/wasm/vision_wasm_nosimd_internal.js",+ "line": 4744,+ "snippet": "} catch (e) {}",+ "vendored": true+ },+ {+ "file": "public/getting-started.js",+ "line": 103,+ "snippet": "function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (_) {} }",+ "vendored": false+ },+ {+ "file": "public/feature-discovery.js",+ "line": 140,+ "snippet": "try { localStorage.setItem(key, JSON.stringify(val)); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/feature-discovery.js",+ "line": 338,+ "snippet": "try { sessionStorage.setItem(SESSION_PROMPTED, '1'); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/discover/detail.js",+ "line": 422,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/demos/agents/_lib.js",+ "line": 89,+ "snippet": "try { rootBone.position.copy(baseRootPos); } catch (_) {}",+ "vendored": false+ },+ {+ "file": "public/demos/agents/_lib.js",+ "line": 101,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "api/widgets/page.js",+ "line": 192,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "api/a-page.js",+ "line": 165,+ "snippet": "} catch (e) {}",+ "vendored": false+ },+ {+ "file": "api/community/auth/callback.js",+ "line": 33,+ "snippet": "try { if (window.opener) window.opener.postMessage(msg, ${JSON.stringify(env.APP_ORIGIN)}); } catch (e) {}",+ "vendored": false+ },+ {+ "file": "api/community/auth/callback.js",+ "line": 34,+ "snippet": "setTimeout(function(){ try { window.close(); } catch (e) {} }, 350);",+ "vendored": false+ },+ {+ "file": "api/avatar/optimize.js",+ "line": 58,+ "snippet": "} catch (_) {}",+ "vendored": false+ },+ {+ "file": "api/_providers/huggingface.js",+ "line": 214,+ "snippet": "try { await reader.cancel(); } catch (_) {}",+ "vendored": false+ }+ ],+ "mockData": [],+ "deadPaths": [+ {+ "file": "src/widget-types.js",+ "line": 5,+ "snippet": "Widgets save config but the runtime renders a \"coming soon\" banner instead of the widget (P1 incomplete feature)."+ },+ {+ "file": "src/create.js",+ "line": 62,+ "snippet": "\"Talking avatar video · coming soon\" — create flow advertises a feature that is not yet shipped."+ },+ {+ "file": "src/create.js",+ "line": 168,+ "snippet": "showStatus(\"Talking avatar video is coming soon — stay tuned.\") — coming-soon path in /create."+ },+ {+ "file": "public/studio/launch-panel.js",+ "line": 429,+ "snippet": "'usdc' (USDC-denominated agent — coming soon) launch mode referenced but not yet enabled."+ },+ {+ "file": "src/scene-studio/main.js",+ "line": 89,+ "snippet": "/scene (Scene Studio): no loading/empty/error UI; storage read errors continue silently; not mobile-responsive (vendored three.js editor, desktop-only)."+ },+ {+ "file": "src/marketplace.js",+ "line": 207,+ "snippet": "/marketplace tabs tools/skills/mine/purchases are routed but their detail views are unverified/possibly WIP. Live audit shows /marketplace 5 console errors, /skills 5 console errors."+ },+ {+ "file": "pages/walk-landing.html",+ "line": 1,+ "snippet": "/walk: avatar/manifest 404 degrades silently (no error UI); WebGL-unsupported has no fallback message. Live audit: /walk 1 error / 11 warnings."+ },+ {+ "file": "chat/src/App.svelte",+ "line": 160,+ "snippet": "/chat: errors are console-only (IndexedDB/network) with no user-facing error UI; empty/first-run state unverified at runtime."+ },+ {+ "file": "pages/launches.html",+ "line": 132,+ "snippet": "/launches explore-nav links (/watchlist,/radar,/pump-live,/pump-visualizer,/launchpad) unverified — confirm they resolve and are wired."+ },+ {+ "file": "public/temporary",+ "line": 0,+ "snippet": "/temporary: live audit shows 3 console errors / 3 warnings — needs investigation."+ },+ {+ "file": "public/gallery",+ "line": 0,+ "snippet": "/gallery: live audit shows 1 console error / 2 warnings."+ },+ {+ "file": "pages/create-agent.html",+ "line": 0,+ "snippet": "/create: live audit shows 2 console errors / 2 warnings."+ },+ {+ "file": "public/collection",+ "line": 0,+ "snippet": "/collection: live audit shows 1 console error / 4 warnings."+ },+ {+ "file": "public/feed",+ "line": 0,+ "snippet": "/feed: live audit shows 1 console error / 3 warnings."+ },+ {+ "file": "src/skill-reviews.js",+ "line": 158,+ "snippet": "check:images (strict) FAIL: <img> for review author avatar is missing loading= attribute. Fix: node scripts/codemod-lazy-images.mjs."+ }+ ]+}diff --git a/docs/tutorials/agent-reputation.md b/docs/tutorials/agent-reputation.mdnew file mode 100644index 000000000..999d7bdae--- /dev/null+++ b/docs/tutorials/agent-reputation.md@@ -0,0 +1,244 @@+# Read an Agent's On-Chain Reputation++By the end of this tutorial you'll be able to look up any agent's reputation in the [Reputation Explorer](/reputation), understand exactly how those scores and reviews accrue on-chain, and read an agent's reputation programmatically — from the browser, a REST call, an MCP client, or directly off the contract. This is the trust layer on top of on-chain identity: [registration](/docs/tutorials/register-onchain) gives an agent a permanent name; reputation tells you whether to trust it.++**Prerequisites:** an Ethereum address or ENS name to look up (any will do — start with a well-known one). Reading reputation needs no wallet and no account. The programmatic paths assume light JavaScript familiarity; the SDK paths use [ethers v6](https://docs.ethers.org). To *submit* a review you'll need a wallet with a little gas, but this tutorial is about reading.++---++## What you're building++```+You: look up an agent or address in the Reputation Explorer+ ↓ [reads on-chain attestations + ERC-8004 registry — no wallet]+Page: avg rating, review count, score distribution, every signed review+ ↓+Code: getReputation({ agentId, chainId, runner }) → { average, count }+ ↓+Agent: an autonomous agent reads a peer's score before deciding to pay it+```++Reputation on three.ws is not a database row a platform can edit. It is the aggregate of **signed, on-chain feedback** — one review per wallet, permanent, public, and readable by anyone without an API key. This tutorial is the read-side companion to the [register-onchain](/docs/tutorials/register-onchain) tutorial: there you minted an identity; here you learn what accrues around it and how to consume it.++---++## How reputation accrues (two minutes of theory)++ERC-8004 separates identity from reputation into two contracts. The **`ReputationRegistry`** is where trust signals live. Two kinds of signal stack on top of an agent's identity:++| Signal | Where it lives | What it is |+|---|---|---|+| Registry feedback | `ReputationRegistry.submitFeedback` | A signed score `−100..+100` + optional comment/URI, one per wallet per agent |+| EAS attestation | Ethereum Attestation Service | A signed `address agent, uint8 score, string comment` attestation against an address |++The registry keeps a **running aggregate** so reads are O(1): it stores the sum and count, and `getReputation(agentId)` returns `(avgX100, count)` — the average already multiplied by 100 to preserve one decimal without floating-point math. You divide by 100 on the client. No pagination, no indexer required for the headline number.++Three rules are enforced by the contract itself, so the aggregate can't be gamed from the client:++- **One review per wallet per agent.** A second attempt reverts with `AlreadyReviewed`. Sybil attacks cost real gas, one wallet at a time.+- **No self-review.** An agent's own owner can't vouch for it (`SelfReviewForbidden`).+- **Score bounds.** Anything outside `−100..+100` reverts with `ScoreOutOfRange`.++Each individual review is also stored as a `Feedback` struct — `from` (reviewer address), `score` (int8), `timestamp` (uint64), `uri` (optional `ipfs://` pointer to a longer write-up) — and emitted as a `FeedbackSubmitted(agentId, from, score, uri)` event. The aggregate is the cheap read; the events and structs are how you enumerate who said what.++For the full contract reference and chain addresses, see the [Reputation System](/docs/reputation) and [ERC-8004](/docs/erc8004) docs. This tutorial is the hands-on path.++---++## Step 1: Open the Reputation Explorer++Go to [/reputation](/reputation). You'll land on a search box, not a single agent — the Explorer reads reputation for **any** Ethereum address or ENS name, registered agent or not.++Enter one of:++- An ENS name — e.g. `vitalik.eth` (the page resolves it to an address for you)+- A raw `0x…` address+- One of the example chips below the box++Pick a **Network** from the dropdown. The default is **Base (mainnet)** — the recommended chain for three.ws agents. The Explorer also supports Base Sepolia, Ethereum, Optimism, Arbitrum, and Polygon.++Click **Look up**. The URL becomes `/reputation?address=<addr>&chain=<chainId>`, so any reputation view is a shareable link.++---++## Step 2: Read the reputation profile++The profile renders three things, all from on-chain data, with a skeleton loader while it fetches:++**The stats grid:**++- **Avg Rating** — the mean of all scored reviews, shown as `X / 5` stars. Scores stored on a `−100..+100` (or 0–100) scale are mapped to the 1–5 star display.+- **Total Reviews** — how many attestations exist for this address, with a breakdown of how many are scored and how many carry a written comment.+- **Score Distribution** — a 5-to-1 bar chart showing how the scores cluster. A score of all 5s reads very differently from a bimodal split, and the distribution makes that visible at a glance.++**The ERC-8004 badge.** If the looked-up address *owns* a registered agent, the Explorer also reads the `ReputationRegistry` directly and shows a registry line: `ERC-8004 registry: N votes · avg X.X/100`, with a link into the registry-specific view (`/reputation?agent=<chainId>:<agentId>`). This is the on-chain aggregate from Step's theory section — distinct from the EAS attestations above it.++**The review list.** Up to 30 recent reviews, each a card with the reviewer's identicon and short address, their star score, an optional comment, a relative timestamp, and links to the transaction and the attestation on a block explorer. Tabs let you filter to **All**, **Scored**, or **With comments**.++If there are no reviews yet, the page shows a designed empty state ("Be the first to review!") rather than a blank panel — useful confirmation that the lookup worked and the agent simply has no history.++---++## Step 3: Look up a registered agent by its on-chain ID++If you already have a three.ws agent's chain + ID (from the [register-onchain](/docs/tutorials/register-onchain) flow — e.g. `8453:42`), you can jump straight to its registry reputation:++```+/reputation?agent=8453:42+```++The Explorer resolves the agent's owner address via the `IdentityRegistry` and redirects to that address's full profile, so you see both its EAS attestations and its ERC-8004 registry score in one view. Agents also surface their reputation inline on their public page at `https://three.ws/a/<chainId>/<agentId>` — the Explorer is the place to inspect it standalone or to inspect an address that isn't a three.ws agent at all.++---++## Step 4: Read the registry aggregate in JavaScript++The headline number — average and count — comes straight off the contract with one read. Use the helper in [src/erc8004/reputation.js](../../src/erc8004/reputation.js):++```js+import { getReputation } from './src/erc8004/reputation.js';+import { JsonRpcProvider } from 'ethers';++const provider = new JsonRpcProvider('https://mainnet.base.org');++const { average, count } = await getReputation({+ agentId: 42,+ chainId: 8453, // Base mainnet+ runner: provider,+});++console.log(`${count} review(s), average ${average.toFixed(1)}`);+// e.g. "14 review(s), average 87.5"+```++`getReputation` returns `{ average, count }` where `average` is already the on-chain `avgX100` divided by 100 — so `8750` on-chain reads as `87.5`. When `count` is `0`, `average` is `0`. **Never divide `average` by `count` again** — the contract already averaged it. That's the single most common mistake when reading this contract.++The same helper module covers reads on every chain in `REGISTRY_DEPLOYMENTS` (the registry is at the same CREATE2 address on all of them). Point `runner` at that chain's RPC and pass the matching `chainId`.++---++## Step 5: Enumerate the individual reviews++The aggregate tells you *how good*; the events tell you *who said what*. `getRecentReviews` queries the `FeedbackSubmitted` event log:++```js+import { getRecentReviews } from './src/erc8004/reputation.js';++const reviews = await getRecentReviews({+ agentId: 42,+ chainId: 8453,+ runner: provider,+ fromBlock: 0, // for recent-only, pass (latestBlock - 50000)+});++reviews.forEach((r) => {+ console.log(r.from, r.score, r.comment, r.txHash);+});+// each: { agentId, from, score, comment, blockNumber, txHash }+```++`from` is the reviewer's address, `score` the signed int8, `comment` the `uri` field (a short string or an `ipfs://` pointer), plus `blockNumber` and `txHash` for explorer links.++Two practical notes:++- **Log queries can be rejected by free-tier RPCs.** Wide `queryFilter` ranges are the most fragile call here. Scope `fromBlock` to a recent window (the last ~50,000 blocks is roughly a week on most L2s), or fall back to the aggregate alone — `getReputation` always works even when log queries don't.+- **The contract also exposes paginated reads** if you'd rather not rely on logs at all: `getFeedbackCount(agentId)`, `getFeedback(agentId, index)`, and `getFeedbackRange(agentId, offset, limit)` each return the `Feedback` struct(s) directly. These are the deterministic path for a UI that must show every review.++---++## Step 6: Read reputation over the REST API++If you have a three.ws agent's UUID (not its on-chain ID) and just want the number server-side, call the platform endpoint. It does the chain read for you and caches the result:++```js+const res = await fetch('/api/agents/<agent-uuid>/reputation?chain_id=8453');+const { average, count, total_stake_wei, chain_id } = await res.json();++console.log(`${count} reviews, avg ${average}, ${total_stake_wei} wei staked`);+```++The endpoint resolves the agent's on-chain `erc8004_agent_id` and chain from its three.ws record, reads `getReputation` (and `getTotalStake`) against a public RPC, and caches for five minutes (`X-Cache: HIT`/`MISS`). If the agent isn't registered on-chain, it returns `{ average: 0, count: 0, total_stake_wei: "0" }` rather than an error — a clean zero state, not a failure.++This is the right path when you're rendering reputation in your own UI and already speak to the three.ws API by agent UUID.++---++## Step 7: Read reputation from an MCP client or as a paid service++Two more read surfaces exist for agent-to-agent and tooling contexts.++**The MCP `agent_reputation` tool.** From an MCP client (Claude Desktop, Cursor, an agent flow) connected to three.ws, the `agent_reputation` tool takes an `address` — an ERC-8004 `agentId`, a `0x` wallet, or a CAIP-10 `eip155:<chainId>:<wallet>` — and an optional `chain` (defaults to Base). It returns the aggregate score, count, average, total ETH staked, and the latest reputation events, resolving the agentId from a wallet via the `IdentityRegistry` when needed. It's a paid tool ($0.01 USDC per call) cataloged in the x402 bazaar.++**The paid HTTP snapshot.** [`GET /api/x402/agent-reputation?agent_id=<uuid>`](../../api/x402/agent-reputation.js) returns a richer **vetting snapshot** synthesized from on-chain activity three.ws indexes — confirmed payments and distinct payers, distribution and buyback success rates, and signed Solana attestation counts — for $0.01 USDC. Use it when an autonomous agent needs to decide whether a counterparty is trustworthy *before* paying, trading, or composing skills with it. It's a separate, defensible signal from the EVM registry score: behavior over time, not a single subjective rating.++---++## Step 8: Gate an autonomous action on reputation++The point of readable, on-chain reputation is that code can act on it. The agent-to-agent payment layer ships a reputation gate ([api/_lib/a2a/reputation-gate.js](../../api/_lib/a2a/reputation-gate.js)) that refuses to pay a peer whose score is below a threshold:++```js+import { assertReputationOk } from './api/_lib/a2a/reputation-gate.js';++// Before paying a peer agent, require a minimum track record:+await assertReputationOk({+ agentId: peerAgentId,+ chainId: 8453,+ minAverage: 50, // require avg score ≥ 50+ minCount: 3, // and at least 3 reviews+});+// Throws ReputationError if the peer is below the bar; returns the read otherwise.+```++The design choices are worth copying in your own gating logic:++- **No threshold set → no-op.** If neither `minAverage` nor `minCount` is requested, the gate does nothing. You opt into trust enforcement explicitly.+- **Threshold set but reputation unreadable → fail closed.** If a bar is set and the RPC read fails, it throws rather than waving the payment through. You cannot prove a peer is trustworthy, so the safe default is "no."+- **The reader is injectable.** Pass a `read` function to swap in an indexer or to test without a live RPC.++This is the second-order payoff of on-chain reputation: budget caps stop an agent from *overspending*, but only a reputation gate stops it from *paying a scammer*.++---++## Troubleshooting++**Lookup returns "No attestations found" for a real agent**+- The agent may have reviews in the **ERC-8004 registry** but no **EAS attestations** (or vice-versa) — they're separate signals. Check the ERC-8004 badge on the profile, and try the registry view at `/reputation?agent=<chainId>:<agentId>`.+- Confirm you picked the **right network**. Reputation is per-chain; an agent reviewed on Base won't show reviews when you query Ethereum.++**`getReputation` returns a huge `average` like `8750`**+- That's `avgX100`. The `getReputation` helper in `src/erc8004/reputation.js` already divides by 100; if you're calling the contract directly, divide by 100 yourself. Don't also divide by `count` — the contract pre-averaged it.++**`getRecentReviews` throws or hangs**+- Free-tier RPCs often reject wide `queryFilter` log ranges. Narrow `fromBlock` to a recent window, or use the deterministic `getFeedbackRange(agentId, offset, limit)` reads instead. The aggregate from `getReputation` still works regardless.++**ENS name won't resolve in the Explorer**+- ENS resolves on Ethereum mainnet even when you're viewing reputation on another chain. If it fails, paste the raw `0x` address instead.++**`/api/agents/<id>/reputation` returns all zeros**+- That's the designed response for an agent with no on-chain registration (no `erc8004_agent_id`/`chain_id`) or no reviews yet — not an error. Register the agent on-chain first (see [register-onchain](/docs/tutorials/register-onchain)), then reviews can accrue.++**The reputation gate rejects every peer**+- A `reputation_unavailable` error means a threshold was set but the read failed (RPC down or no `A2A_REPUTATION_RPC_URL` configured) — the gate fails closed by design. Configure a working RPC, or drop the threshold to disable gating.++---++## Recap++You learned to read agent reputation at every layer:++- **The Reputation Explorer** ([/reputation](/reputation)) — search any address or ENS name, no wallet, and see avg rating, count, distribution, and every signed review across EAS attestations and the ERC-8004 registry.+- **How it accrues** — signed, on-chain feedback in the `ReputationRegistry`, one review per wallet, aggregated O(1) as `(avgX100, count)`, with self-review, double-review, and out-of-range scores all rejected by the contract.+- **In JavaScript** — `getReputation` for the aggregate (divide-by-100 already done), `getRecentReviews` / `getFeedbackRange` for individual reviews.+- **Over REST** — `GET /api/agents/<uuid>/reputation?chain_id=` for a cached server-side read by agent UUID.+- **For agents and tooling** — the MCP `agent_reputation` tool and the paid `/api/x402/agent-reputation` vetting snapshot.+- **Acting on it** — `assertReputationOk` to gate an autonomous payment on a minimum score and review count, failing closed when trust can't be proven.++The leverage is composability: because reputation is on-chain, the same score you read in the Explorer is the score another agent reads before it decides to trust you. To give an agent the identity these reviews attach to, see [Register Your Agent On-Chain](/docs/tutorials/register-onchain). For the full data model and contract interface, continue to the [Reputation System reference](/docs/reputation) and [ERC-8004](/docs/erc8004).++## See also++- [Register Your Agent On-Chain](/docs/tutorials/register-onchain) — the identity layer reputation attaches to.+- [Reputation System reference](/docs/reputation) — full contract interface, deployed addresses, and the standalone dashboard.+- [ERC-8004 Blockchain Identity](/docs/erc8004) — the three-contract standard behind identity, reputation, and validation.+- [Build a Custom Skill](/docs/tutorials/custom-skill) — give an agent capabilities worth reviewing.diff --git a/docs/tutorials/import-avatar-url.md b/docs/tutorials/import-avatar-url.mdnew file mode 100644index 000000000..252ddf10f--- /dev/null+++ b/docs/tutorials/import-avatar-url.md@@ -0,0 +1,161 @@+# Import an avatar by URL++You already have an avatar living somewhere else — a Ready Player Me model on a CloudFront link, a GLB on Arweave, an export sitting in your own storage. You don't need to download it, convert it, or re-host it. Paste the URL into [three.ws/import/rpm](/import/rpm) and the platform fetches it server-side, normalizes its skeleton, auto-rigs it so it can move, and saves it to your account as an avatar an agent can wear.++This tutorial walks the URL-import path end to end. It's the sibling of [Upload a custom GLB](/docs/tutorials/upload-custom-glb) — that one covers pushing a file from your disk; this one covers pulling one in from a link. Same destination, different on-ramp.++**Prerequisites:** a three.ws account (the importer redirects you to sign in if you're not), and a live, publicly reachable URL to a glTF 2.0 `.glb` file. No command line, no Blender, no local tooling required — the whole flow runs in the browser.++---++## What you're building++```+You: paste https://models.readyplayer.me/64c3….glb into /import/rpm+ ↓ server fetches the file (no CORS to fight)+ ↓ humanoid bones canonicalized → idle/walk clips will play+ ↓ stored on the three.ws CDN as an avatar record+ ↓ a fresh agent is provisioned and the avatar attached+ ↓ static rigs get auto-rigged so they animate, not freeze in T-pose+You: "Avatar imported!" → open it at /avatars/<id> and chat with the agent+```++The end result is identical to creating an avatar from a selfie or building one in Studio: a saved avatar record, owned by you, attached to an agent with its own custodial wallet, ready to embed anywhere.++---++## How URL import works (two minutes of theory)++The import page offers two tabs — **Paste URL** and **Upload GLB**. This tutorial is the URL tab. Here's why it exists as a separate path from a plain file upload.++Most avatar hosts (Ready Player Me's CloudFront CDN, Arweave gateways, arbitrary object storage) serve their GLBs **without CORS headers**. A browser `fetch()` to those URLs is blocked before a single byte arrives. So the importer doesn't rely on your browser reaching the file at all:++1. The browser tries a direct CORS fetch first (works for the rare host that allows it).+2. When that's blocked — the common case — it falls back to a **server-side proxy fetch**. The three.ws API pulls the file on your behalf. No CORS to satisfy, and the server applies SSRF guards (it refuses loopback, private, link-local, and cloud-metadata addresses, follows a bounded number of redirects, and caps the download size) so a pasted URL can't be turned into a request against internal infrastructure.+3. Either way, the bytes land in three.ws storage and an avatar record is created.++Two things happen automatically once the file is in:++- **Bone canonicalization.** Humanoid skeletons come in many naming dialects — Mixamo (`mixamorig:LeftArm`), VRM/VRoid, Unreal, Daz/Genesis, MakeHuman, Blender. The platform renames whatever it finds to one canonical bone set so the pre-baked animation library (idle, walk, gestures) retargets onto it out of the box. A non-humanoid rig passes through untouched. The mapping lives in [src/glb-canonicalize.js](../../src/glb-canonicalize.js).+- **Auto-rig.** If the imported GLB has **no skeleton at all** (a static mesh export), the platform submits an auto-rig job after saving. The rigged GLB is swapped in place once the job lands — no T-pose, no second copy. This is the same guarantee every avatar created on three.ws gets: it can move. A GLB that already ships a skeleton skips this step.++You don't trigger any of this. Pasting the URL is enough.++---++## Step 1: Get the GLB URL of your avatar++The importer needs a direct link to a `.glb` file — the URL must end at the model itself, not a viewer page wrapped around it.++**Ready Player Me.** RPM gives you a model URL of the form `https://models.readyplayer.me/<id>.glb`. If you only have the avatar's web page, append `.glb` to the avatar ID, or open the page, then DevTools → **Network**, filter by `.glb`, and copy the request URL. RPM serves these from a CloudFront CDN with no CORS headers — exactly the case the server-side fetch is built for.++**Any other hosted glTF/GLB.** The importer accepts any GLB URL, not just RPM:++- A CDN link (CloudFront, Cloudflare, Bunny, etc.)+- An Arweave or IPFS gateway URL ending in `.glb`+- A file in your own object storage or static host++**Finding the URL when an app fetches it on load.** If your avatar shows up in some other web app but you don't know the raw URL, open that app, then **DevTools → Network → filter `.glb`**, and copy the request URL straight from the network log. That's the link to paste.++The only hard requirements: the URL is `http://` or `https://`, it's publicly reachable (no auth header, no signed-cookie wall), and it points at a valid glTF 2.0 binary. If the original host is gone or the file is behind a login, download it once and use the **Upload GLB** tab instead — see [Upload a custom GLB](/docs/tutorials/upload-custom-glb).++---++## Step 2: Open the importer++Go to **[/import/rpm](/import/rpm)** (linked from [/create](/create) as the "bring your own avatar" path).++You'll see an import card with two tabs. Leave it on **Paste URL** (the default). The warning banner up top spells out the model: the file is fetched on three.ws servers, so CORS-restricted CDNs all work; the Upload tab is the fallback for files on disk or dead hosts.++If you're not signed in, the import call returns a `401` and the page bounces you to `/login?return=/import/rpm` — sign in and you land right back on the importer.++---++## Step 3: Paste the URL and name the avatar++1. In **Avatar GLB URL or CDN link**, paste the full `.glb` URL from Step 1.+2. The field validates the protocol on submit — anything that isn't `http://` or `https://` is rejected with *"Enter a valid http:// or https:// URL."*+3. Optionally fill in **Avatar name**. If you leave it blank, the importer derives a name from the filename in the URL (e.g. `64c3f8e2.glb` → `64c3f8e2`), falling back to *"Imported Avatar"* when the path has nothing useful.++That's the whole form. Hit **Import from URL**.++---++## Step 4: Watch the import run++The progress bar narrates the real pipeline as it executes — these aren't fake stages on a timer, they map to actual work:++| Stage | What's happening |+|---|---|+| **Fetching model…** | The server (or browser, if CORS allows) pulls the GLB bytes from your URL. |+| **Normalizing bones…** | Humanoid bone names are canonicalized so the animation library can drive the rig. |+| **Uploading to three.ws…** | The file is written to the platform CDN with correct CORS and cache headers. |+| **Saving avatar record…** | The avatar row is created in your account; the agent provisioning and auto-rig jobs kick off. |++When it finishes you get an **"Avatar imported!"** card with a **View avatar** button pointing at `/avatars/<your-avatar-id>`.++Behind that success screen, three fire-and-forget jobs have already started and will complete on their own:++- **An agent is provisioned.** A fresh agent is created (or an unpaired one reused) with your imported avatar attached, and it gets its own custodial Solana wallet.+- **The avatar is auto-rigged if needed.** Static meshes are upgraded to animation-ready in place.+- **A thumbnail and tags are generated.** The GLB is rendered off-screen, a poster image is captured, and the model is auto-tagged.++None of these block the success screen — the avatar is usable immediately, and these enrich it over the next few moments.++---++## Step 5: Open the avatar and confirm it moves++Click **View avatar** (or go to `/avatars/<id>`). The avatar page renders your imported model.++What to check:++- **It's not frozen in a T-pose.** A canonicalized humanoid plays the idle clip right away. If you imported a *static* mesh, give the auto-rig job a moment — the model swaps to its rigged version in place once the job lands, and then it animates too. The platform never leaves an avatar stuck bind-pose; a rig that genuinely can't be skeleton-driven falls back to the default rig.+- **Geometry and materials look right.** PBR (`pbrMetallicRoughness`) materials render correctly. If the source used an unsupported material extension you may see a fallback — see [Upload a custom GLB](/docs/tutorials/upload-custom-glb) for the material fix-list, which applies identically to imported files.++---++## Step 6: Use the avatar on an agent++The import already provisioned an agent with this avatar attached, so the fastest path is to just use it:++1. Go to [three.ws/my-agents](/my-agents).+2. Find the agent created for your imported avatar.+3. Send it a message — it should switch to a talk-style animation while it replies, then return to idle.++To put the same avatar on a *different* agent, or to swap an existing agent's body to this one, open that agent and set its body to the imported avatar from the editor's **Body** tab. Because the avatar is a saved record on your account, it's available to any agent you own, and every embed of that agent — `<agent-3d agent-id="…">`, iframe widgets, script-tag embeds — picks up the body on next page load with no code change.++From here you can give the agent a brain and a voice: see [Give your agent a personality](/docs/tutorials/agent-personality) and [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory).++---++## Troubleshooting++- **"Could not fetch that URL … The file may no longer exist."** The server couldn't retrieve the GLB. The host is down, the link is dead, the path is wrong, or the file sits behind authentication. Open the URL in a new browser tab — if you don't get a file download, the importer can't reach it either. Re-copy the URL, or download the file once and use the **Upload GLB** tab.+- **"Enter a valid http:// or https:// URL."** The pasted value isn't a parseable web URL, or uses a non-web protocol. Paste the full link including `https://`. `file://`, `data:`, and relative paths are rejected.+- **The import gets you redirected to sign in.** The save needs an authenticated owner; you weren't signed in. Log in — you're returned to `/import/rpm` automatically. Then re-paste and import.+- **Avatar imported but stuck in a T-pose.** If it's a *static* mesh, the auto-rig job is still finishing — reload the avatar page in a moment and it swaps to the rigged, animating version in place. If a *humanoid* skeleton still won't animate, its bone naming convention may be one the canonicalizer doesn't yet map; the platform adds new conventions rather than maintaining an allowlist, so report the rig.+- **Materials render chalky/grey.** The source GLB uses a material extension the runtime renders as a fallback. Convert the materials to standard `pbrMetallicRoughness` at the source and re-import — the [Upload a custom GLB](/docs/tutorials/upload-custom-glb) material fix-list covers this exactly.+- **"This is taking forever" on a large file.** The server fetch caps download size and a huge, uncompressed GLB takes longer to pull and store. If your file is well over the cap, optimize it first (the `optimize:glb` / `gltf-transform` steps in [Upload a custom GLB](/docs/tutorials/upload-custom-glb)) and import the slimmer result.+- **I want to import a file on my disk, not a URL.** Switch to the **Upload GLB** tab on the same page — drag-and-drop or file-pick a `.glb` (up to 100 MB). Same canonicalization, auto-rig, and agent provisioning apply.++---++## Recap++You imported an existing avatar by URL, no download or conversion required:++- **Paste a `.glb` URL** at [/import/rpm](/import/rpm) — Ready Player Me, any CDN, Arweave, or your own storage all work.+- **The server fetches it for you**, so CORS-restricted hosts are a non-issue, with SSRF guards on the pasted URL.+- **Humanoid bones are canonicalized** ([src/glb-canonicalize.js](../../src/glb-canonicalize.js)) so the pre-baked animation library plays out of the box.+- **Static meshes are auto-rigged** in place after save — the platform guarantees an avatar that can move, never a frozen T-pose.+- **An agent is provisioned** with the avatar attached and its own wallet; the avatar is a reusable record you can put on any agent you own.++The URL path and the file-upload path converge on the same avatar record and the same agent flow — choose whichever fits where your file already lives.++### See also++- [Upload a custom GLB avatar](/docs/tutorials/upload-custom-glb) — the file-upload counterpart, plus the validator, compression, and material/skinning fix-lists+- [Avatar Creation](/docs/avatar-creation) — every way to make an avatar (photo, builder, upload) and the format spec+- [Give your agent a personality](/docs/tutorials/agent-personality) — match the brain to the imported body+- [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) — give the agent durable facts to carry between sessionsdiff --git a/docs/tutorials/mine-vanity-address.md b/docs/tutorials/mine-vanity-address.mdnew file mode 100644index 000000000..c0ad2936a--- /dev/null+++ b/docs/tutorials/mine-vanity-address.md@@ -0,0 +1,262 @@+# Mine a Solana vanity address++By the end of this tutorial you'll have ground a **custom Solana address** — one that starts with, ends with, or is bookended by characters you choose — entirely in your browser, with the secret key never leaving your device. You'll also understand the **proof-of-grind protocol** around the paid grinder: how to verify a signed receipt, publish to the rarity gallery, and post a bounty when a pattern is too hard for one machine.++Along the way you'll learn why a vanity service is normally a trust problem, and how `three-vanity/v1` replaces "just trust us" with math you can check yourself.++**Prerequisites:** a modern browser (the grind uses Web Workers + WASM). No account is needed to grind in the browser. The paid grinder, gallery publishing, and bounties are optional and covered later — those touch x402 payments and an X25519 key you generate on the page.++---++## What you're building++A vanity address is a normal Solana keypair whose public key happens to match a pattern you picked:++```+Pattern: starts with "AGNT"+ ↓ [your CPU grinds candidates until one matches]+Result: AGNTxK9…vP4q ← a real Ed25519 keypair, address matches the pattern+```++A Solana address is just the Base58 encoding of an Ed25519 public key. There's no shortcut to "AGNT…" — you generate random keypairs and check each address until one starts with your characters. That's *grinding*. Each extra character multiplies the work by ~58, so short patterns are instant and long ones can take a fleet.++This tutorial covers the full lifecycle: **grind in the browser → (optionally) buy a provably-fair grind → verify the receipt → publish to the gallery → post a bounty for hard patterns**.++---++## How grinding works (two minutes of theory)++The address space is the Base58 alphabet (`123…ABC…xyz`, minus the ambiguous `0 O I l` — 58 symbols). To match `n` chosen characters you expect to try about `58ⁿ` random keypairs:++| Pattern length | Expected attempts | Feel |+|---|---|---|+| 1 char | ~58 | instant |+| 3 chars | ~195k | seconds |+| 4 chars | ~11M | a minute on several cores |+| 5 chars | ~633M | minutes to hours |+| 6+ chars | billions | a fleet, or a bounty |++A **case-insensitive** match (matching letters in any case) roughly halves the work per letter, at the cost of not choosing the casing of the result.++Two ways to do the grind exist on three.ws, and they solve different problems:++- **In-browser grind ([/vanity-wallet](/vanity-wallet))** — your machine generates the keypair. Nothing is sent anywhere, so there's nothing to trust. Free, up to 6 pattern characters.+- **Provably-fair paid grind (`/api/x402/vanity-verifiable`)** — three.ws's servers do the work and hand back a **signed receipt**. Because someone else generated your key, the protocol exists to *prove* they did it honestly and never kept a copy. This is the `three-vanity/v1` protocol, specified in [docs/PROTOCOL-vanity.md](../PROTOCOL-vanity.md).++Start with the browser grind. It's the right default for almost everyone.++---++## Step 1: Open the grinder and pick a pattern++Go to **[/vanity-wallet](/vanity-wallet)**.++You'll see two inputs:++- **Starts with** — the prefix your address should begin with (e.g. `AGNT`).+- **Ends with** — the suffix it should end with (e.g. `pump`).++Fill in either, or both. Each field accepts only Base58 characters (max 6 each). As you type, the page shows a live **preview** of where your characters land in a sample address, a difficulty meter, and a rough time estimate:++```+type a prefix or suffix to see estimated time+ ↓ (you type "AGNT")+rough estimate: ~40s on 4 cores [tier: slow — minutes+]+```++The estimate comes from the honest `58ⁿ` model and your selected core count. The page calculates expected attempts as:++```+expectedAttempts = product over each pattern character of (58 / matchesPerChar)+```++where `matchesPerChar` is `2` for a letter when case-insensitive is on (both cases are valid Base58), otherwise `1`. This is the same difficulty math the paid receipt commits to — see [src/solana/vanity/validation.js](../../src/solana/vanity/validation.js).++> **Tip:** the suggested-pattern chips (`AGNT…`, `…pump`, `GM…gm`, …) each show their own estimate. They're a fast way to see how dramatically each extra character costs you.++---++## Step 2: Decide on case sensitivity++Below the inputs is a **Case-insensitive** toggle:++> Case-insensitive — match letters in any case. Much faster to grind, but you don't get to choose the casing of the result.++Leave it **off** if the exact casing matters (you want `AGNT`, not `agnt` or `Agnt`). Turn it **on** when you only care about the letters and want the grind to finish sooner — each letter then matches two Base58 symbols instead of one, cutting the expected work for that character roughly in half.++The time estimate updates immediately when you toggle it, so you can see the trade-off before committing CPU.++---++## Step 3: Set your compute budget and grind++The **Compute — CPU cores to use** slider controls how many Web Workers run the grind in parallel. The page defaults to a sensible fraction of your machine's cores and caps at what your browser reports.++- More cores = faster, but a heavier load on the rest of your machine.+- You can **Pause** at any time to free the cores, then resume.++Press **Generate wallet**. The grind starts and a live panel shows:++```+12,400/s 847,213+tries/sec · 4 cores attempts · eta ~12s+```++- **tries/sec** — combined throughput across your workers.+- **attempts** — cumulative candidates checked.+- **eta** — live estimate to a hit.++Under the hood each worker loads a WASM grinder ([src/solana/vanity/grinder-worker.js](../../src/solana/vanity/grinder-worker.js)) that batches keypair generation, draws fresh entropy with `crypto.getRandomValues`, and checks each candidate against your pattern. The orchestration lives in [src/solana/vanity/grinder.js](../../src/solana/vanity/grinder.js). No network requests are made during the grind — open DevTools → Network and confirm it stays empty.++---++## Step 4: Save the key (this is the critical step)++When a match is found, the page shows your new address and a warning that's there for a reason:++> Save this file somewhere safe before navigating away. Once you close this tab the secret key is gone unless you assign it to an agent. Anyone with the file can spend funds at this address.++The secret key exists **only in this browser tab's memory**. Your options:++- **Download** — saves a JSON file containing the 64-byte secret key as an integer array. This is the Solana CLI / `Keypair.fromSecretKey` format, importable into Phantom, Solflare, or the CLI.+- **Copy** — copies the public address to your clipboard (the address is safe to share; the secret key is not).+- **Assign to an agent** — encrypts the key at rest on three.ws and attaches the wallet to one of your agents, so the agent can transact from a memorable address.++If you only download, store the file somewhere safe (a password manager works). There's no recovery — three.ws never saw the key, so it can't help you restore it. That's the whole point of the in-browser model.++You're done if all you wanted was a vanity wallet. The remaining steps cover the **provably-fair** side of the protocol — relevant when a key was ground *for* you and you want to prove it was done honestly.++---++## Step 5: Understand the provably-fair grind (when the server holds the work)++If you buy a grind from the paid endpoint (`/api/x402/vanity-verifiable`, an x402-priced API), the server does the work and returns a **signed receipt**. Now there's a trust question the browser grind never had: *did they generate my key fresh, or grind a million candidates and quietly keep the one whose key they logged?*++`three-vanity/v1` answers this with a **commit–reveal + sealed-delivery + signed-receipt** scheme. In plain terms, the receipt lets you prove, after the fact, that:++1. the key came from entropy the server **committed to before** it knew your pattern (no precomputed table of keys);+2. **your own entropy** (`clientSeed`) was mixed in, so neither party alone controlled the address;+3. the address really derives from the revealed seed, matches your pattern, and the difficulty claim is the honest `58ⁿ` model;+4. the receipt was **signed by the real three.ws service key**, not an impostor;+5. (optionally) the key you recovered from the sealed envelope is byte-for-byte the one the receipt describes — **you alone hold it**.++A receipt is a JSON object carrying the `commitment`, the revealed `serverSeed` and `clientSeed`, the `requestNonce`, the `winningIndex`, the `pattern`, the `difficulty`, and an Ed25519 `signature` over a canonical projection of those fields. When you supply a `sealTo` X25519 public key, the secret is delivered as a `sealedSecret` envelope encrypted to you — the plaintext key never appears in the response. The full field list and signing rules are in [docs/PROTOCOL-vanity.md](../PROTOCOL-vanity.md).++---++## Step 6: Verify a receipt++Open **[/vanity/verify](/vanity/verify)**.++1. **Paste the receipt JSON** into the Receipt JSON box (the full object you received from `/api/x402/vanity-verifiable`).+2. *(Optional)* Expand **"prove you hold the key"** and paste **your X25519 private key** to open the sealed envelope and confirm custody. This key is used only in your browser to decrypt and compare — it is never sent anywhere.+3. Press **Verify receipt**.++The page runs every check locally and shows a pass/fail line for each:++- **protocol** — the receipt is `three-vanity/v1`.+- **commitment** — `SHA-256(serverSeed)` equals the published commitment, so the server was locked to that seed before grinding.+- **derivation** — re-deriving the master seed and the candidate at `winningIndex` reproduces exactly `receipt.address`.+- **pattern** — the address actually satisfies the requested prefix/suffix.+- **difficulty** — `difficulty.expectedAttempts` equals the honest rounded `58ⁿ` value.+- **signature** — the Ed25519 signature verifies, **and** the receipt's signing key matches the one pinned from the well-known document (impostors who self-sign under a different key fail here).+- **custody** *(if you opened the seal)* — the decrypted seed's public key equals `receipt.address`.++Before you even paste anything, the page fetches the live service key from [/.well-known/three-vanity.json](/.well-known/three-vanity.json) and pins it, so a forged receipt signed under a different key is caught. The verification logic is the open-source [src/solana/vanity/verifiable-grind.js](../../src/solana/vanity/verifiable-grind.js) (its `verifyVanityReceipt()` function), the same code the CLI and SDK use.++Prefer the command line? Run the open-source verifier:++```bash+node scripts/verify-vanity-receipt.mjs ./receipt.json --fetch-key+```++`--fetch-key` cross-checks the signature against the live well-known service key instead of the value pinned in the script. A single failing check means the receipt is not trustworthy.++---++## Step 7: Publish to the proof-of-grind gallery++The **[/vanity/gallery](/vanity/gallery)** is a public, ranked showcase of the rarest addresses ground on three.ws — each one provably-fair and verified.++Two things you can do there without publishing anything:++- **Appraise any address** — paste a Solana address and the gallery scores its rarity (tier, expected attempts, bonuses) using pure math, no persistence. Good for seeing how rare an address you already hold is.+- **Browse the leaderboard** — addresses ranked by an honest rarity score.++To **publish** one of your own (it's opt-in):++1. From the verify page, after a green verdict, click **Publish to the rarity gallery →** (or open the gallery's Publish tab directly).+2. The gallery submits your **receipt** to `/api/vanity/gallery`. The server re-verifies it against the live service key before storing anything.+3. Only public, secret-free metadata is kept — address, pattern, rarity, optional label. Secret fields (`secretKey`, `seed`, `sealedSecret`) are stripped client-side and rejected server-side, so there's no way to leak a key by publishing.++You can un-publish later by proving control of the key with an Ed25519 signature. Publishing is purely a flex — it never exposes anything that could spend your funds.++---++## Step 8: Post a bounty for a hard pattern++Some patterns are too slow for one machine (5–6+ characters can mean billions of attempts). **[/vanity/bounties](/vanity/bounties)** is a pay-for-results market: you escrow a reward, a fleet of independent workers grinds in parallel, and the first to find a verified match gets paid — without ever seeing your wallet.++To **create** a bounty:++1. Set the **pattern** (prefix/suffix). The page calls a difficulty oracle (`?view=quote`) and suggests an honest reward based on expected grind time.+2. **Generate or paste an X25519 recipient key.** This is the key the found secret will be **sealed to** — workers encrypt the result to you, so they earn the reward but can't keep your wallet.+3. Set the **reward** (denominated in **USDC**; there's a small floor) and an **expiry**.+4. **Escrow** the reward via x402 (USDC on Base or Solana mainnet). The bounty goes live once payment settles.++To **claim** a bounty (you're running grinders for others):++1. Poll open bounties with `GET /api/vanity/bounties?view=open`.+2. Grind the pattern with the same WASM grinder used on `/vanity-wallet`.+3. On a hit, **seal the secret to the requester's X25519 key** client-side, then submit `POST /api/vanity/bounties?action=claim` with the address, the sealed secret, and your payout address.+4. The server verifies the address matches the pattern and the envelope is valid, then settles atomically — only the **first** verified match is paid, on-chain, immediately.++When a bounty fills, the requester opens the sealed envelope with their X25519 **private** key — locally, the key never goes to the server — to recover the wallet. If a bounty expires unfilled, the escrow refunds to the requester. The bounty market is backed by [api/vanity/bounties.js](../../api/vanity/bounties.js).++> Rewards are **USDC**, the settlement asset for the bounty escrow. Nothing about a bounty involves any token other than the wallet you're grinding for.++---++## Bonus: Ethereum CREATE2 vanity addresses++The same idea applies to Ethereum, but for **smart-contract** addresses rather than wallets. **[/eth-vanity](/eth-vanity)** grinds a vanity *contract* address by searching **CREATE2 salts** — and crucially, no private keys are involved. A CREATE2 address is fully determined by the deployer, a salt you choose, and the contract's init-code hash:++```+address = keccak256(0xff ‖ deployer ‖ salt ‖ keccak256(initCode))[12:]+```++So the grind searches for a **salt** that produces a contract address matching your pattern. You feed that salt to your factory (Arachnid, CreateX, Safe, Coinbase, or any CREATE2 factory) at deploy time. The page runs the search in your browser, chain-agnostic and deployer-agnostic — there's no secret to protect, just a salt to hand to your deployment. The salt + factory details can be recorded against your agent identity via [api/agents/eth-vanity.js](../../api/agents/eth-vanity.js), which re-verifies the CREATE2 formula server-side before storing it.++---++## Troubleshooting++- **The grind is taking forever** — each extra character multiplies work by ~58. A 6-character case-sensitive pattern is billions of attempts; either shorten it, enable case-insensitive, raise the core count, or post a [bounty](/vanity/bounties) so a fleet grinds it.+- **The page froze / my fan spun up** — that's the grind using your cores. Lower the core slider or **Pause** to give your machine breathing room; resume when ready.+- **I closed the tab and lost the key** — there's no recovery. three.ws never received the key on the browser path. Always **Download** (or assign to an agent) before navigating away.+- **Verify says "could not fetch the live service key"** — the page falls back to verifying against the receipt's own key (unpinned). The signature still checks out, but to prove the signer is three.ws, retry so it can pin against [/.well-known/three-vanity.json](/.well-known/three-vanity.json).+- **A verify check fails (commitment / derivation / signature)** — the receipt is not trustworthy. A tampered address, swapped seed, wrong index, inflated difficulty, or an impostor signing key each fail by design. Do not use a key from a receipt that doesn't fully verify.+- **Custody check fails** — the X25519 private key you pasted doesn't match the `sealTo` the receipt was sealed to, or the envelope was altered. Use the exact private key matching the public key you sent as `sealTo`.+- **Bounty won't post** — confirm the recipient X25519 key is set and the escrow payment settled. The board fetches config (`?view=config`) to confirm payout is available before accepting a create.++---++## Recap++You learned to mine a Solana vanity address and to operate the proof-of-grind protocol around it:++- **Grind in the browser** ([/vanity-wallet](/vanity-wallet)) — pick a prefix/suffix, choose case sensitivity and cores, grind locally with WASM Web Workers, and download the key. Nothing leaves your device.+- **Difficulty is `58ⁿ`** — every character multiplies the work; case-insensitive roughly halves per letter.+- **Provably-fair paid grind** — when the server holds the work, `three-vanity/v1` proves the key was fresh, your entropy was mixed in, and no copy was kept.+- **Verify** ([/vanity/verify](/vanity/verify)) — paste a receipt to re-check commitment, derivation, pattern, difficulty, signature, and (optionally) custody, all in your browser, pinned to the live service key.+- **Gallery** ([/vanity/gallery](/vanity/gallery)) — appraise any address or opt-in publish a verified, secret-free receipt to the rarity leaderboard.+- **Bounties** ([/vanity/bounties](/vanity/bounties)) — escrow a USDC reward for a hard pattern; a fleet grinds it and seals the result to you.+- **CREATE2 vanity** ([/eth-vanity](/eth-vanity)) — the same grind for Ethereum contract addresses, searching salts, no keys involved.++The protocol itself is fully specified in [docs/PROTOCOL-vanity.md](../PROTOCOL-vanity.md), and the verifier is open source — you never have to take three.ws's word for it.++## See also++- [three-vanity/v1 protocol specification](../PROTOCOL-vanity.md) — the commit–reveal, seed-mixing, sealed-delivery, and signing scheme in full+- [Create, enhance & edit agent memory](/docs/tutorials/create-and-edit-memory) — give the agent that owns your vanity wallet durable context+- [Build a Custom Skill](/docs/tutorials/custom-skill) — extend that agent with new capabilities at runtimediff --git a/docs/tutorials/pay-for-x402-service.md b/docs/tutorials/pay-for-x402-service.mdnew file mode 100644index 000000000..3add3a05f--- /dev/null+++ b/docs/tutorials/pay-for-x402-service.md@@ -0,0 +1,236 @@+# Discover and Pay for an x402 Service++By the end of this tutorial you'll be able to find a paid API in the [Bazaar](/bazaar), pay for one call in USDC, and get back real work — no API key, no account, no subscription. You'll do it four ways: from the Bazaar UI with a wallet, from the hosted [/pay](/pay) checkout, programmatically with `window.X402.pay`, and by letting an autonomous agent shop the catalog for you on [/shopper](/shopper).++This is the **consume** side of x402. If you want to *build* an endpoint that takes these payments, see [paid-x402-endpoint](/tutorials/paid-x402-endpoint) — this tutorial is everything on the other side of that handshake.++**Prerequisites:**++- A browser wallet: **Phantom** (or Solflare) for Solana, or **MetaMask** / **Coinbase Wallet** for Base (EVM). The checkout detects whichever is installed.+- A small USDC balance on the network you'll pay from. Most calls are $0.001–$0.01, so ~$1 USDC funds thousands of them. On Solana you also need a little SOL for the account; on Base the signature is gasless from your side.+- Light JavaScript familiarity for the programmatic path (Steps 5–6). The UI paths (Steps 2–4) need none.++---++## What you're building++Paying for an x402 service is two HTTP round trips and one wallet signature:++```+You → GET /api/some-paid-thing (no payment)+ ← 402 Payment Required { accepts: [ { network, asset, amount, payTo } ] }+You → sign a USDC payment for one of the `accepts`+You → GET /api/some-paid-thing (X-PAYMENT: <signed payload>)+ ← 200 { ...the actual work... } (X-PAYMENT-RESPONSE: <on-chain receipt>)+```++The price, the recipient, and the network all come from the seller's 402 challenge — you never type them. Your wallet signs exactly that amount to exactly that address, the platform settles it on-chain, and the original request is retried automatically. You either get what you paid for or you pay nothing.++---++## How discovery and payment fit together (two minutes of theory)++There are two distinct problems: **finding** an endpoint and **paying** it.++**Finding.** The [Bazaar](/bazaar) is a discovery surface. Server-side, [`/api/bazaar/list`](api/bazaar/list.js) and [`/api/bazaar/search`](api/bazaar/search.js) call each configured facilitator's `/discovery/resources` route, merge the catalogs, dedupe (HTTP by resource URL, MCP by `resource + toolName`), normalize the shape, and apply your filters. The default facilitators are PayAI (`facilitator.payai.network`, Base + Solana) and Coinbase CDP (`api.cdp.coinbase.com/platform/v2/x402`, Base + EVM L2s), wired in [`api/_lib/x402/bazaar-client.js`](api/_lib/x402/bazaar-client.js). An endpoint shows up here once it has answered a discovery probe with a valid 402 — there is no submission form. (How three.ws gets *its own* endpoints into those catalogs is the build-side concern covered in [paid-x402-endpoint](/tutorials/paid-x402-endpoint).)++**Paying.** Every payment runs through the same drop-in module, [`public/x402.js`](public/x402.js), exposed as `window.X402.pay(...)`. It does the 402 → sign → retry dance for you:++- For **Solana**, the wallet can only sign serialized transactions, so the module posts the challenge's `accept` to [`/api/x402-checkout?action=prepare`](api/x402-checkout.js), gets back a partially-signed SPL `transferChecked`, has Phantom add the buyer's signature, then `?action=encode`s it into the `X-PAYMENT` header.+- For **Base / EVM**, the wallet signs an EIP-3009 `transferWithAuthorization` typed-data message locally — no server prep needed.++Either way the signed payload is base64-encoded into `X-PAYMENT`, the gated request is retried once, and the unlocked result plus the decoded `X-PAYMENT-RESPONSE` receipt come back.++---++## Step 1: Browse the Bazaar++Open [/bazaar](/bazaar). You'll see a searchable, filterable grid of every paid service the facilitators currently advertise.++The sidebar filters map directly to the catalog query:++- **Type** — `http` (paid REST endpoints) or `mcp` (paid MCP tools). HTTP is the default.+- **Network** — Base, Arbitrum, Optimism, Polygon, Solana, or Base Sepolia.+- **Max price** — a USDC ceiling; entered in dollars, sent to the API as 6-decimal atomic units.+- **Extension** — narrow to endpoints advertising a specific x402 extension (e.g. `sign-in-with-x`).+- **Sort** — including by price, ascending.++Type a query (e.g. `weather`, `reputation`, `model`) and the page switches from `/api/bazaar/list` to `/api/bazaar/search`, ranking results against your terms. The footer shows which facilitators answered and which failed, so a single down source never blanks the page.++Each card shows the service name, description, price (minimum USDC across its `accepts`), supported networks, the provider host (links to its [/providers](/providers) profile), and — when several listings do the same job — a **peer hint** comparing prices across them. That last one matters: the same capability is often sold by multiple providers at different prices.++---++## Step 2: Pay for a service from the Bazaar++Find an HTTP service you want and click **Try it** on its card.++1. The drop-in payment modal opens, having already re-fetched the live 402 challenge to confirm the current price (prices can change; the card is a cached hint, the modal is the source of truth).+2. The modal shows the **price**, the **network**, and **who you're paying** — the on-chain `payTo` address, linked to a block explorer so you can verify the recipient before committing.+3. Pick your wallet. The modal only offers wallets that match a network in the challenge's `accepts` and are actually detected in your browser; undetected ones render disabled with an "install" hint.+4. Approve the payment in your wallet. Before prompting you, the modal does a fail-open balance pre-check — if it can positively read that your wallet is short, it shows an insufficient-funds state with the exact shortfall and an explorer link, instead of letting you sign a doomed transaction.+5. The platform settles on-chain and retries the call. The card's receipt area fills in with the result and a link to the on-chain transaction.++What you signed is exactly what the challenge declared — the modal never invents an amount or a recipient. If the seller configured optional charity / round-up giving on a Solana checkout, you'll see a pre-checked, opt-out box that rides the *same* transaction, so you still pay once.++> **MCP tools** can't be paid through this modal — they need a JSON-RPC `tools/call` envelope the modal doesn't speak. Clicking a `mcp`-type card opens the details panel instead, with the schema you'd wire into an MCP client. To call MCP tools by paying per-call, see [mcp-server-for-your-agent](/tutorials/mcp-server-for-your-agent).++---++## Step 3: Read the 402 challenge yourself++To understand what the modal is doing, hit a paid endpoint by hand. Any x402 endpoint answers an unpaid request with a 402:++```bash+curl -i https://three.ws/api/x402/model-check+```++You get back a `402 Payment Required` whose JSON body (and a base64 mirror in the `payment-required` response header) contains an `accepts` array. One entry looks like:++```jsonc+{+ "scheme": "exact",+ "network": "solana", // or "eip155:8453" for Base+ "amount": "1000", // 6-decimal atomic USDC → $0.001+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC mint+ "payTo": "<recipient address>",+ "maxTimeoutSeconds": 60,+ "extra": { "name": "USD Coin", "decimals": 6, "feePayer": "<sponsor>" }+}+```++Read it like a receipt-in-advance:++- **`amount`** is in atomic units of **`asset`**. With `decimals: 6`, `"1000"` is $0.001. (Spec-strict sellers may name this field `maxAmountRequired`; the client coerces both to `amount`.)+- **`network`** tells you which wallet you need. `solana` / `solana:*` → Phantom/Solflare; `eip155:8453` → Base; other `eip155:*` are the EVM L2s in [`EVM_NETWORKS`](public/x402-pay-core.js).+- **`payTo`** is exactly where your USDC goes. Nothing else moves.+- **`maxTimeoutSeconds`** bounds how long your signed authorization is valid — your one safety net against a stale payment lingering.++A single endpoint can list several `accepts` (e.g. Base *and* Solana). You — or your wallet — pick whichever network you hold funds on.++---++## Step 4: Pay through the /pay surface++[/pay](/pay) is the platform's own pay-per-call surface — a live demo that pays $0.001 USDC on Solana to call MCP tools and render 3D assets, with a settlement timeline you can watch step by step. Use it to see a real settlement end to end before wiring your own.++Two related routes sit under it:++- **[/pay/calls](/pay/calls)** — the public ledger of paid x402 calls to the platform. Each settled call gets a permalink (`/pay/calls/<tx-signature>`) showing the tool invoked and the on-chain transaction. This is your audit trail: every payment you make here is verifiable on-chain by anyone.+- **`/pay/c/<slug>`** — a *hosted checkout link*. A provider creates a SKU in their dashboard (see [`api/x402-skus.js`](api/x402-skus.js)) and shares the URL; the page hydrates from `/api/x402-skus?slug=<slug>` and opens the same drop-in modal pre-wired to that endpoint. If someone hands you a `/pay/c/...` link, paying it is identical to Step 2 — open it, pick a wallet, approve.++The point of the `/pay` surface: the *exact same* payment core ([`public/x402.js`](public/x402.js) and its sibling [`public/x402-pay-core.js`](public/x402-pay-core.js)) drives the Bazaar's "Try it", the hosted checkout, the full-page paywall, and the programmatic call below. Learn it once.++---++## Step 5: Pay programmatically with window.X402.pay++When you want to trigger a paid call from your own page or script, skip the UI and call the module directly. Load it once:++```html+<script type="module" src="https://three.ws/x402.js"></script>+```++Then pay for any endpoint:++```js+const out = await window.X402.pay({+ endpoint: 'https://three.ws/api/x402/model-check?url=' ++ encodeURIComponent('https://three.ws/avatar/character-studio/sample.glb'),+ method: 'GET',+ merchant: 'three.ws',+ action: 'Model Check',+});++if (out.ok) {+ console.log('result:', out.result); // the work product+ console.log('paid on:', out.payment.network);+ console.log('tx:', out.payment.transaction); // on-chain settlement+}+```++`pay()` opens the modal, runs discovery → connect → sign → verify → retry, and resolves with `{ ok, result, payment, response }`. On a user cancel it rejects with an error whose `code === 'cancelled'` — handle that distinctly from a real failure.++Useful options:++- **`body`** — a JSON object for `POST` endpoints (method defaults to `POST` when a body is present).+- **`headers`** — extra request headers forwarded on the paid retry.+- **`networks`** — an allowlist to force a single rail, e.g. `['solana']` for a Solana-only checkout, or `['evm']` / `['eip155:8453']`. The modal drops every `accept` outside the allowlist before rendering the wallet picker. If the filter would empty the list, it keeps the original accepts so a misconfigured allowlist never breaks a live checkout.++For a declarative trigger, any element with `data-x402-endpoint` is auto-bound on load and fires an `x402:result` (or `x402:error`) CustomEvent when done:++```html+<button+ data-x402-endpoint="https://three.ws/api/x402/model-check"+ data-x402-method="GET"+ data-x402-merchant="three.ws"+ data-x402-action="Model Check"+>Pay & Run</button>+```++To wire paid calls into an **agent's** conversation (so it buys mid-chat when the user asks), put the same pattern in a skill handler via `ctx.x402.fetch` — covered in [custom-skill](/tutorials/custom-skill) and the caller half of [paid-x402-endpoint](/tutorials/paid-x402-endpoint).++---++## Step 6: Let an agent shop the Bazaar for you++When you don't know *which* endpoint you need, the [Endpoint Shopper](/shopper) does the discovery, payment, and synthesis for you. Describe a task, set a USDC budget, and the agent searches the Bazaar for relevant endpoints, pays for each call it decides to make (capped at your budget), and returns a synthesized answer with a per-step cost breakdown.++```+Task: "What is the current price of ETH?"+Budget: $0.50+ ↓ [discover → plan → call (pays per endpoint) → synthesize]+Answer: "ETH is trading around $3,180." — total spent: $0.012 USDC across 2 paid steps+```++The page posts to `/api/agents/endpoint-shopper-run` with `{ task, maxCostUsd }`. The agent itself charges a small base fee and spends up to your budget downstream — set the budget at or above $0.01 so it can fund at least one paid call (the UI gates the button below that). The timeline shows each step's action (discover / plan / call / synthesize), the endpoint it hit, and what that step cost; the final row sums the spend, showing **"Free (no paid calls executed)"** when the task needed none.++If running the Shopper itself returns a 402, the page hands you off to the wallet paywall to unlock it — the same payment core as every other path here.++This is the autonomous consumer pattern: you express intent and a budget; the agent turns the Bazaar into a tool it pays for on demand. To coordinate multiple agents around a buying flow, see [multi-agent-coordination](/tutorials/multi-agent-coordination).++---++## Step 7: Verify what you paid for++Every successful payment returns an on-chain receipt — make a habit of checking it:++- **In the UI** — the Bazaar receipt and the modal both link the settlement transaction to a block explorer (Solscan for Solana, Basescan/Arbiscan/etc. for EVM).+- **Programmatically** — `out.payment.transaction` is the on-chain tx; `out.payment.network` and `out.payment.payer` tell you which rail settled and from which wallet.+- **On the public ledger** — platform calls land on [/pay/calls](/pay/calls) with a permalink anyone can audit.++If the result looks wrong but you were charged, note: x402 has **single-shot, no-refund** semantics — you pay for the *attempt*, not a guaranteed *result*. A failed call after settlement is not auto-refunded; retrying means a fresh payment. That's why the verify-then-work-then-settle ordering on the seller side (see [paid-x402-endpoint](/tutorials/paid-x402-endpoint)) matters to you as a buyer: a correctly built endpoint never settles when its work failed, so you don't pay for nothing.++---++## Troubleshooting++- **"Payment module failed to load (x402.js)"** on a Bazaar card — the drop-in script 404'd or didn't evaluate, so `window.X402` is undefined. Reload the page; check the network tab for the `/x402.js` request.+- **Wallet button is disabled** — that wallet isn't detected, or no `accept` matches its network. Install the extension (Phantom for Solana, MetaMask/Coinbase for Base) and reload, or pick the other rail.+- **"Not enough USDC — you need X but your wallet holds Y"** — the balance pre-check caught a shortfall before you signed. Top up the wallet on the shown network (the error links your address on the explorer) and retry. The check is fail-open: if your balance can't be read, payment still proceeds.+- **"Endpoint did not return 402 (got 200/404…)"** — you pointed `pay()` at a free or non-x402 URL. Confirm the endpoint actually challenges with `curl -i <url>` (Step 3).+- **402 but "no `accepts` array could be found"** — a proxy stripped the body *and* the `payment-required` header, or the seller's challenge is malformed. Try the endpoint's own canonical URL; if it's third-party, the seller's 402 is non-compliant.+- **Signature rejected at settle on Base** — almost always a wrong EIP-712 domain. Base USDC's domain name is `"USD Coin"` at version `"2"`; a seller advertising anything else produces a payload the facilitator rejects. Nothing you can fix as a buyer — report it to the provider.+- **Solana checkout fails at "Authorize"** — usually a stale blockhash on a flaky RPC; the prepare endpoint fails open to a recent cached blockhash, so simply retry. A too-stale blockhash never confirms and never double-charges.+- **Clicking an MCP card doesn't open a payment modal** — by design; MCP tools open the details panel. Wire them through an MCP client ([mcp-server-for-your-agent](/tutorials/mcp-server-for-your-agent)).+- **Endpoint Shopper button stays disabled** — the budget is below $0.01 or the task is empty; the hint under the button names the exact unmet precondition.++---++## Recap++You learned four ways to consume an x402 paid service:++- **The Bazaar** ([/bazaar](/bazaar)) — search and filter the merged facilitator catalog, then **Try it** to pay with a wallet through the drop-in modal.+- **The /pay surface** ([/pay](/pay), [/pay/calls](/pay/calls), `/pay/c/<slug>`) — the platform's live pay-per-call demo, public on-chain ledger, and hosted checkout links — all driven by the same payment core.+- **`window.X402.pay`** — pay for any endpoint from your own code; resolves with the result plus an on-chain receipt, with a `networks` allowlist to pin the rail.+- **The Endpoint Shopper** ([/shopper](/shopper)) — describe a task and a budget; an agent discovers, pays for, and synthesizes results from Bazaar endpoints autonomously.++The throughline: discovery and payment are decoupled, the 402 challenge is the single source of truth for price and recipient, every payment settles on-chain in USDC, and one module ([`public/x402.js`](public/x402.js)) drives every surface.++**See also**++- [paid-x402-endpoint](/tutorials/paid-x402-endpoint) — the build side: ship your own endpoint that takes these payments.+- [mcp-server-for-your-agent](/tutorials/mcp-server-for-your-agent) — pay-per-call MCP tools.+- [custom-skill](/tutorials/custom-skill) — give an agent a tool that pays for a service mid-conversation.+- [multi-agent-coordination](/tutorials/multi-agent-coordination) — coordinate agents around a buying flow.diff --git a/docs/tutorials/voice-and-lipsync.md b/docs/tutorials/voice-and-lipsync.mdnew file mode 100644index 000000000..a394ea23b--- /dev/null+++ b/docs/tutorials/voice-and-lipsync.md@@ -0,0 +1,224 @@+# Give your agent a voice with synchronized lipsync++By the end of this tutorial your agent will **speak out loud** with a mouth that moves in time with the words — a real voice, real audio, and real-time viseme animation, all rendered in the browser. You'll pick or clone a voice in the [Voice Lab](/voice), see exactly how visemes drive an avatar's mouth in the two [/lipsync](/lipsync) labs, then wire voice into a live agent.++Along the way you'll understand why three.ws extracts visemes from the audio itself (no per-word timing service), how the same pipeline handles both TTS playback and a raw microphone, and what happens on avatars that have no viseme morphs at all.++**Prerequisites:** a three.ws account with at least one agent ([create one](/create)), a browser with Web Audio + WebGL (any modern desktop browser), and a microphone if you want to clone a voice or try the mic lab. No code is required for the labs; the live-agent step assumes light JavaScript familiarity.++---++## What you're building++```+Agent generates a reply+ ↓ POST /api/tts/speak (or /api/tts/eleven for a cloned voice)+Audio plays through a Web Audio AnalyserNode+ ↓ LipSyncAnalyser samples the frequency spectrum every frame+Per-viseme weights → avatar morph targets+ ↓+The avatar's mouth animates in sync with the speech — frame by frame, in WebGL+```++The mouth is not driven by a script or a timing file. The avatar listens to its own audio and shapes its mouth from what it hears, so any voice — a built-in one, a cloned one, even a live mic — drives the same animation path.++This tutorial covers the full chain: **choose a voice → understand visemes → wire voice into a live agent.**++---++## How lipsync works (two minutes of theory)++A **viseme** is the visual shape a mouth makes for a sound — the open jaw of "aa", the lip-press of "PP", the teeth-and-tongue of "SS". On a 3D avatar each viseme is a **morph target** (a blendshape) you can dial from 0 to 1.++three.ws uses the Oculus/ARKit viseme naming. The analyser ([`src/lip-sync-analyser.js`](src/lip-sync-analyser.js)) drives nine of them:++```js+export const VISEMES = [+ 'viseme_aa', 'viseme_O', 'viseme_E', 'viseme_I', 'viseme_nn',+ 'viseme_SS', 'viseme_FF', 'viseme_CH', 'viseme_PP',+];+```++Rather than rely on a server returning phoneme timestamps, the analyser reads the **audio's frequency spectrum** in real time through a Web Audio `AnalyserNode` and maps energy bands to mouth shapes:++| Frequency band | Drives | Why |+|---|---|---|+| Low (0–500 Hz) | `viseme_aa`, `viseme_O` | open vowels carry low-frequency energy |+| Mid (500–2k Hz) | `viseme_E`, `viseme_I`, `viseme_nn` | mid vowels and nasals |+| High (2k–8k Hz) | `viseme_SS`, `viseme_FF`, `viseme_CH` | sibilants and fricatives are bright |+| Amplitude dip | `viseme_PP` | a bilabial closure is a momentary silence |++Weights are smoothed with an exponential moving average so the mouth eases between shapes instead of snapping, and everything drops toward zero when the audio falls below a silence threshold. Because it's pure spectral analysis, **the audio never leaves the browser** and there's no per-word timing data to fetch or fall out of sync.++One important fallback: not every avatar has viseme morphs. The runtime detects this per avatar and picks a mode — `visemes` when ARKit viseme morphs exist, `jaw` when only `jawOpen` exists (it drives the jaw straight from the smoothed amplitude via `getAmplitude()`), and `none` when the rig has no mouth morphs at all. A face without visemes still opens and closes its jaw to the voice rather than sitting frozen.++---++## Step 1: Choose a built-in voice++The fastest path to a talking agent is a built-in TTS voice. The catalog lives in one place ([`api/_lib/tts-voices.js`](api/_lib/tts-voices.js)) so every picker and the synthesizer agree on what exists:++| id | character |+|---|---|+| `nova` | Bright and energetic — the default companion voice |+| `alloy` | Neutral and balanced |+| `ash` | Warm and expressive |+| `ballad` | Soft and lyrical |+| `coral` | Friendly and upbeat |+| `echo` | Calm and measured |+| `fable` | Expressive storyteller |+| `onyx` | Deep and authoritative |+| `sage` | Gentle and thoughtful |+| `shimmer` | Light and airy |+| `verse` | Dynamic and conversational |++The default is `nova`. These are synthesized by `POST /api/tts/speak` ([`api/tts/speak.js`](api/tts/speak.js)), which tries the free NVIDIA NIM Magpie lane first and falls back to OpenAI's `/v1/audio/speech`. You don't choose the provider — you choose the voice id, and the endpoint renders it on whichever lane is configured.++You can hear all of these immediately in the next step.++---++## Step 2: Hear visemes drive the mouth (TTS lab)++Open the **TTS-driven lipsync** lab at [/lipsync](/lipsync). This is the clearest way to see the whole pipeline at once.++1. Type a sentence in **Text to speak**.+2. Pick a **Voice** (`nova`, `alloy`, `echo`, `fable`, `onyx`, `shimmer`, `ash`, `coral`, or `sage`) and a **Speed** (0.8×, 1.0×, 1.2×, or 1.5×).+3. Click **Speak**.++What happens under the hood:++- The page `POST`s `{ text, voice, speed, format: 'mp3' }` to `/api/tts/speak` and gets back an audio clip.+- The clip plays through an `<audio>` element, and the [`wawa-lipsync`](https://www.npmjs.com/package/wawa-lipsync) library analyses it frame by frame, emitting a viseme code each tick.+- The page maps that code onto the avatar's Oculus-named morph targets:++```js+const VISEME_MAP = {+ aa: 'viseme_aa', PP: 'viseme_PP', FF: 'viseme_FF',+ TH: 'viseme_E', DD: 'viseme_E', kk: 'viseme_E',+ CH: 'viseme_CH', SS: 'viseme_SS', nn: 'viseme_nn',+ RR: 'viseme_O', ou: 'viseme_O', sil: null,+};+```++The **Visemes (live)** panel on the right shows which morph is firing each instant, and the log reports how many viseme morphs were wired on the loaded avatar (`N/N viseme morphs wired`). Watch the bars light up as the avatar talks — that's the morph target system being driven in real time.++> The TTS lab uses `wawa-lipsync`, which emits a discrete viseme code per frame. The live agent and the mic lab use the platform's own `LipSyncAnalyser`, which blends weighted bands. Both end at the same place — viseme morph targets — but the spectral analyser produces softer, overlapping shapes.++---++## Step 3: Verify the analyser with your own voice (mic lab)++To see the **exact analyser** that powers live agent speech, open the **audio-driven lipsync** lab at [/lipsync/mic](/lipsync/mic) and feed it your microphone instead of TTS.++1. Click **Start mic** and allow microphone access.+2. Speak. The nine-bar meter and the per-viseme readout update every frame, and the avatar's mouth tracks your voice.+3. Click **Stop** to release the mic and reset the morphs to zero.++This page wires the real pipeline directly:++- `getUserMedia({ audio: true })` → an `AudioContext` with an `AnalyserNode` (`fftSize = 256`, `smoothingTimeConstant = 0.7`).+- A `LipSyncAnalyser` ([`src/lip-sync-analyser.js`](src/lip-sync-analyser.js)) reads that node. Each frame it calls `analyser.sample()`, which returns the nine viseme weights, and applies them straight to the avatar: `mesh.morphTargetInfluences[index] = weight`.+- The mic node is deliberately **not** connected to the speakers, so you don't hear yourself echo.++Your audio never leaves the browser — analysis is `AnalyserNode` + `requestAnimationFrame`, nothing more. This is the same `LipSyncAnalyser` the live chat connects to its TTS output, so whatever mouth shapes you see here are what your agents will produce.++---++## Step 4: Clone your own voice (optional)++If you want your agent to speak in *your* voice instead of a built-in one, use the [Voice Lab](/voice). Cloning runs through ElevenLabs Instant Voice Cloning.++1. Open [/voice](/voice).+2. Read one of the suggested scripts aloud (or speak naturally) while recording. **20–30 seconds** is the recommended length; recording auto-stops at 60 seconds, and anything under 3 seconds is rejected. A live waveform and level meter show your input as you go.+3. Stop, then **review** the playback.+4. Give the voice a **name** (1–64 characters) and click **Clone**. The page uploads the sample to `POST /api/tts/eleven-clone` ([`api/tts/eleven-clone.js`](api/tts/eleven-clone.js)) as `multipart/form-data`.+5. On success you get a `voice_id`, and the voice is saved to your library (stored in `localStorage`, up to 20 voices).++**Test it in the playground.** Pick the cloned voice, type a sample line, and click Speak. The playground calls `POST /api/tts/eleven` ([`api/tts/eleven.js`](api/tts/eleven.js)) with `{ voiceId, text }`, which proxies ElevenLabs and caches the clip for 30 days (the hint shows `cached` vs `generated`). Default model is `eleven_flash_v2_5`; requests are capped at 500 characters and rate-limited to 1000 characters per hour per user.++> Instant Voice Cloning is a **paid-tier ElevenLabs feature** (Starter and up). If the server's account is on the free tier, the clone call returns the upstream error verbatim in the status line (e.g. a `can_not_use_instant_voice_cloning` message). Built-in voices in Step 1 have no such requirement.++Note the `voice_id` — you'll use it to give an agent the cloned voice in the next step.++---++## Step 5: Wire voice into a live agent++Now connect a voice to an agent so it speaks during conversation, with the mouth driven automatically.++The agent runtime ships two TTS providers that expose a shared `analyserNode`: `ElevenLabsTTS` ([`src/runtime/speech.js`](src/runtime/speech.js)) for cloned/ElevenLabs voices, and a neural TTS provider ([`src/runtime/neural-tts.js`](src/runtime/neural-tts.js)) that speaks the built-in catalog through `/api/tts/speak`. Whichever one an agent uses, the avatar wiring is identical.++The connection happens through two hooks the runtime sets on the TTS instance (see [`src/app.js`](src/app.js) and [`src/element.js`](src/element.js)):++```js+tts.onStart = () => {+ // Connect the avatar's LipSyncAnalyser to the TTS audio the moment it plays.+ if (tts.analyserNode) avatar.connectLipSync(tts.analyserNode);+};+tts.onEnd = () => {+ // Tear down lipsync so the mouth lerps back to neutral when speech ends.+ avatar.disconnectLipSync();+};+```++`connectLipSync(audioSource)` ([`src/agent-avatar.js`](src/agent-avatar.js)) builds a fresh `LipSyncAnalyser` on the TTS `AnalyserNode`; every render frame the avatar samples it and writes viseme weights (or, on a viseme-less rig, drives `jawOpen` from the amplitude). `disconnectLipSync()` zeroes the viseme and `jawOpen`/`mouthOpen` morphs so the face eases back to rest instead of freezing on the last shape mid-word.++For a cloned voice, construct the ElevenLabs provider with the `voice_id` from Step 4:++```js+import { ElevenLabsTTS } from './runtime/speech.js';++const tts = new ElevenLabsTTS({+ voiceId: 'your-cloned-voice-id', // from /api/tts/eleven-clone+ modelId: 'eleven_flash_v2_5', // default+ proxyURL: '/api/tts/eleven', // keeps the API key server-side+ stability: 0.5,+ similarityBoost: 0.75,+ useSpeakerBoost: true,+});+```++When the agent speaks, `tts.speak(text)` plays the clip; `onStart` fires on the audio's `playing` event and wires lipsync; `onEnd` tears it down. You don't touch morph targets yourself — binding the provider is enough.++---++## Step 6: Spatial audio (optional polish)++If your agent lives in a 3D scene rather than a flat panel, route its voice through a positional audio source so the sound comes from where the avatar stands. `AgentAvatar.setTTS(tts)` ([`src/agent-avatar.js`](src/agent-avatar.js)) binds the provider, and when a `THREE.PositionalAudio` is attached it forwards it to `ElevenLabsTTS.setPositionalAudio()`. The voice then attenuates with distance and pans with the avatar's position — the groundwork the [real-time voice preview](/blog/real-time-voice-interaction) describes for headset/WebXR deployment, where the agent's voice should come from the avatar in space.++This is opt-in: a flat embed plays voice normally without it.++---++## Troubleshooting++- **No sound, `503 not_configured` from `/api/tts/speak`** — no TTS provider is set on the server (neither `NVIDIA_API_KEY` nor `OPENAI_API_KEY`). Built-in voices need at least one lane configured.+- **`429` / "TTS rate limit exceeded"** — `/api/tts/speak` budgets per user (or per IP when anonymous), and `/api/tts/eleven` caps at 1000 characters/hour per user. Sign in for the higher limit, or wait for the hourly bucket to reset.+- **Clone fails with a quota / verification message** — Instant Voice Cloning is an ElevenLabs paid-tier feature. The endpoint passes the upstream body through so you see the exact reason (e.g. `can_not_use_instant_voice_cloning`). Use a built-in voice instead, or upgrade the ElevenLabs plan.+- **Clone rejected as too short** — the recorder requires at least 3 seconds; aim for the recommended 20–30 seconds for a usable clone.+- **Mic lab does nothing / "Microphone blocked"** — mic capture needs a secure (https) context and granted permission. The lab maps each failure to a designed state: blocked (allow access in the address bar), no device found, or mic busy (another app is using it). Fix and click **Try again**.+- **Avatar talks but the mouth doesn't move** — the loaded avatar has no viseme morphs. Check the TTS lab's log for `0/9 viseme morphs wired`. The runtime falls back to `jawOpen` if that morph exists, and to no mouth motion if the rig has none. Use an ARKit/Oculus-blendshaped avatar for full visemes.+- **Mouth freezes open after speech ends** — lipsync wasn't torn down. The runtime calls `disconnectLipSync()` from `tts.onEnd`; if you wire TTS manually, make sure that hook is set.+- **Cloned voice in the playground says `generated` every time** — the R2 cache keys on `voiceId + text + modelId + voice_settings`. Identical requests return `cached`; any change to text or settings is a fresh synthesis.++---++## Recap++You gave an agent a synchronized voice end to end:++- **Choose a voice** — eleven built-in voices in [`api/_lib/tts-voices.js`](api/_lib/tts-voices.js), synthesized by `POST /api/tts/speak` (free NVIDIA lane, OpenAI backstop), default `nova`.+- **Clone a voice** — record in the [Voice Lab](/voice), clone via `/api/tts/eleven-clone` (ElevenLabs IVC), play back via `/api/tts/eleven` with a 30-day cache.+- **Understand visemes** — the [TTS lab](/lipsync) and [mic lab](/lipsync/mic) show nine viseme morphs driven from the audio spectrum by [`src/lip-sync-analyser.js`](src/lip-sync-analyser.js) — no per-word timing, all in-browser.+- **Wire it live** — a runtime TTS provider exposes an `analyserNode`; `tts.onStart` calls `avatar.connectLipSync()` and `tts.onEnd` calls `disconnectLipSync()`, so the mouth follows the speech and returns to rest automatically — falling back to `jawOpen` on rigs without viseme morphs.++The leverage is that the avatar drives its mouth from the *audio it actually plays*, so a built-in voice, a cloned voice, and a live mic all flow through one analyser. Start with a built-in voice in the [TTS lab](/lipsync), then bring your own through the [Voice Lab](/voice).++## See also++- [Voice Lab](/voice) — record, clone, and test a voice+- [TTS-driven lipsync lab](/lipsync) — type text, watch visemes fire+- [Audio-driven lipsync lab](/lipsync/mic) — verify the analyser with your mic+- [Real-time voice interaction preview](/blog/real-time-voice-interaction) — the full listen-reason-speak pipeline and where AR/VR fits+- [Build a custom skill](/docs/tutorials/custom-skill) — `ctx.speak()` lets a skill make the agent talk mid-tooldiff --git a/pages/credits.html b/pages/credits.htmlnew file mode 100644index 000000000..7a4f711e8--- /dev/null+++ b/pages/credits.html@@ -0,0 +1,305 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />+ <title>Credits · three.ws</title>+ <meta+ name="description"+ content="Top up your three.ws balance with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for a discount on every spend."+ />+ <meta property="og:title" content="Credits · three.ws" />+ <meta+ property="og:description"+ content="Deposit SOL or $THREE for credits. Spend on Forge, agents, and compute. Hold $THREE for up to 30% off."+ />+ <meta property="og:url" content="https://three.ws/credits" />+ <meta property="og:image" content="https://three.ws/og-image.png" />+ <meta name="twitter:card" content="summary_large_image" />+ <link rel="canonical" href="https://three.ws/credits" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <style>+ .credits-wrap {+ max-width: 1040px;+ margin: 0 auto;+ padding: clamp(1.25rem, 4vw, 3rem) 1.25rem 4rem;+ }+ .credits-head {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-end;+ justify-content: space-between;+ gap: 1rem;+ margin-bottom: 1.75rem;+ }+ .credits-head h1 {+ font-size: clamp(1.7rem, 4vw, 2.5rem);+ margin: 0 0 0.35rem;+ letter-spacing: -0.02em;+ }+ .credits-head p {+ margin: 0;+ color: var(--text-secondary, #9aa3b2);+ max-width: 52ch;+ line-height: 1.5;+ }+ .credits-grid {+ display: grid;+ grid-template-columns: 1.1fr 0.9fr;+ gap: 1.1rem;+ align-items: start;+ }+ @media (max-width: 820px) {+ .credits-grid { grid-template-columns: 1fr; }+ }+ .card {+ background: var(--surface-1, #14161c);+ border: 1px solid var(--border, #262a33);+ border-radius: 16px;+ padding: 1.25rem 1.35rem;+ }+ .card h2 {+ font-size: 0.82rem;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--text-secondary, #9aa3b2);+ margin: 0 0 0.9rem;+ font-weight: 600;+ }+ .balance-amount {+ font-size: clamp(2.4rem, 7vw, 3.4rem);+ font-weight: 700;+ letter-spacing: -0.03em;+ line-height: 1;+ font-variant-numeric: tabular-nums;+ }+ .balance-sub {+ display: flex;+ gap: 1.5rem;+ margin-top: 1rem;+ flex-wrap: wrap;+ }+ .balance-sub div { display: flex; flex-direction: column; gap: 0.15rem; }+ .balance-sub .k { font-size: 0.72rem; color: var(--text-secondary, #9aa3b2); text-transform: uppercase; letter-spacing: 0.06em; }+ .balance-sub .v { font-size: 1.05rem; font-weight: 600; font-variant-numeric: tabular-nums; }+ .tier-pill {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ margin-top: 0.9rem;+ padding: 0.3rem 0.7rem;+ border-radius: 999px;+ background: color-mix(in srgb, var(--accent, #6c8cff) 14%, transparent);+ border: 1px solid color-mix(in srgb, var(--accent, #6c8cff) 35%, transparent);+ font-size: 0.8rem;+ font-weight: 600;+ }+ .seg {+ display: inline-flex;+ background: var(--surface-2, #1c1f27);+ border: 1px solid var(--border, #262a33);+ border-radius: 10px;+ padding: 3px;+ gap: 3px;+ }+ .seg button {+ appearance: none;+ border: 0;+ background: transparent;+ color: var(--text-secondary, #9aa3b2);+ font: inherit;+ font-weight: 600;+ padding: 0.45rem 1rem;+ border-radius: 8px;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+ }+ .seg button[aria-pressed='true'] {+ background: var(--accent, #6c8cff);+ color: #fff;+ }+ .field { margin-top: 1rem; }+ .field label { display: block; font-size: 0.78rem; color: var(--text-secondary, #9aa3b2); margin-bottom: 0.4rem; }+ .amt-row { display: flex; gap: 0.5rem; align-items: stretch; }+ .amt-row input {+ flex: 1;+ background: var(--surface-2, #1c1f27);+ border: 1px solid var(--border, #262a33);+ border-radius: 10px;+ color: var(--text-primary, #e8ebf2);+ font: inherit;+ font-size: 1.1rem;+ padding: 0.6rem 0.8rem;+ font-variant-numeric: tabular-nums;+ }+ .amt-row .unit {+ display: flex; align-items: center; padding: 0 0.9rem;+ background: var(--surface-2, #1c1f27);+ border: 1px solid var(--border, #262a33);+ border-radius: 10px; font-weight: 700;+ }+ .quick { display: flex; gap: 0.4rem; margin-top: 0.55rem; flex-wrap: wrap; }+ .quick button {+ appearance: none; border: 1px solid var(--border, #262a33);+ background: var(--surface-2, #1c1f27); color: var(--text-secondary, #9aa3b2);+ border-radius: 999px; padding: 0.3rem 0.7rem; font: inherit; font-size: 0.82rem; cursor: pointer;+ }+ .quick button:hover { color: var(--text-primary, #e8ebf2); border-color: var(--accent, #6c8cff); }+ .est { margin-top: 0.6rem; font-size: 0.85rem; color: var(--text-secondary, #9aa3b2); min-height: 1.2em; }+ .est b { color: var(--text-primary, #e8ebf2); font-variant-numeric: tabular-nums; }+ .btn {+ appearance: none; border: 0; cursor: pointer; font: inherit; font-weight: 600;+ border-radius: 10px; padding: 0.7rem 1.1rem; width: 100%; margin-top: 1rem;+ background: var(--accent, #6c8cff); color: #fff; transition: filter 0.15s, opacity 0.15s;+ }+ .btn:hover { filter: brightness(1.08); }+ .btn:disabled { opacity: 0.55; cursor: not-allowed; }+ .btn.secondary { background: var(--surface-2, #1c1f27); border: 1px solid var(--border, #262a33); color: var(--text-primary, #e8ebf2); }+ .status { margin-top: 0.85rem; font-size: 0.88rem; line-height: 1.45; min-height: 1.2em; }+ .status.err { color: #ff8a8a; }+ .status.ok { color: #6ee7a8; }+ .status.work { color: var(--text-secondary, #9aa3b2); }+ .manual { margin-top: 1.1rem; border-top: 1px solid var(--border, #262a33); padding-top: 0.9rem; }+ .manual summary { cursor: pointer; font-size: 0.85rem; color: var(--text-secondary, #9aa3b2); }+ .addr {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 0.8rem; word-break: break-all; background: var(--surface-2, #1c1f27);+ border: 1px solid var(--border, #262a33); border-radius: 8px; padding: 0.55rem 0.7rem; margin: 0.6rem 0;+ }+ .manual input {+ width: 100%; background: var(--surface-2, #1c1f27); border: 1px solid var(--border, #262a33);+ border-radius: 8px; color: var(--text-primary, #e8ebf2); font: inherit; font-size: 0.85rem; padding: 0.5rem 0.7rem;+ }+ .buys { display: grid; gap: 0.5rem; margin-top: 0.4rem; }+ .buy-row { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; padding: 0.5rem 0; border-bottom: 1px dashed var(--border, #262a33); }+ .buy-row:last-child { border-bottom: 0; }+ .buy-row .label { color: var(--text-primary, #e8ebf2); font-size: 0.92rem; }+ .buy-row .price { font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; }+ .ledger { width: 100%; border-collapse: collapse; margin-top: 0.3rem; }+ .ledger th, .ledger td { text-align: left; padding: 0.55rem 0.5rem; font-size: 0.86rem; border-bottom: 1px solid var(--border, #262a33); }+ .ledger th { color: var(--text-secondary, #9aa3b2); font-weight: 600; font-size: 0.74rem; text-transform: uppercase; letter-spacing: 0.05em; }+ .ledger td.amt { text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; white-space: nowrap; }+ .ledger td.amt.pos { color: #6ee7a8; }+ .ledger td.amt.neg { color: var(--text-primary, #e8ebf2); }+ .ledger a { color: var(--accent, #6c8cff); }+ .muted { color: var(--text-secondary, #9aa3b2); }+ .empty { padding: 1.4rem 0; color: var(--text-secondary, #9aa3b2); text-align: center; font-size: 0.9rem; }+ .signin { text-align: center; padding: 3rem 1rem; }+ .signin a { color: var(--accent, #6c8cff); font-weight: 600; }+ .skel { background: linear-gradient(90deg, var(--surface-2,#1c1f27) 25%, var(--surface-1,#14161c) 50%, var(--surface-2,#1c1f27) 75%); background-size: 200% 100%; animation: sk 1.2s infinite; border-radius: 8px; }+ @keyframes sk { from { background-position: 200% 0; } to { background-position: -200% 0; } }+ .row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1.1rem; margin-top: 1.1rem; }+ @media (max-width: 820px) { .row-2 { grid-template-columns: 1fr; } }+ [hidden] { display: none !important; }+ </style>+ </head>+ <body>+ <a href="#main-content" class="h-skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content" class="credits-wrap">+ <div class="credits-head">+ <div>+ <h1>Credits</h1>+ <p>+ Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute.+ Hold $THREE for up to 30% off every spend.+ </p>+ </div>+ </div>++ <!-- Signed-out -->+ <section id="signin-state" class="card signin" hidden>+ <p>Sign in to view your balance and top up.</p>+ <p><a href="/login?next=/credits">Sign in →</a></p>+ </section>++ <!-- Signed-in -->+ <div id="app-state" hidden>+ <div class="credits-grid">+ <!-- Balance -->+ <section class="card" aria-label="Your balance">+ <h2>Balance</h2>+ <div class="balance-amount" id="balance">$0.00</div>+ <div class="balance-sub">+ <div><span class="k">Deposited</span><span class="v" id="lifetime-dep">$0.00</span></div>+ <div><span class="k">Spent</span><span class="v" id="lifetime-spent">$0.00</span></div>+ </div>+ <div class="tier-pill" id="tier-pill" hidden></div>+ <div class="row-2" style="margin-top:1.2rem">+ <div>+ <h2>What credits buy</h2>+ <div class="buys" id="buys"></div>+ </div>+ </div>+ </section>++ <!-- Deposit -->+ <section class="card" aria-label="Add credits">+ <h2>Add credits</h2>+ <div class="seg" role="group" aria-label="Deposit asset">+ <button type="button" data-asset="SOL" aria-pressed="true">SOL</button>+ <button type="button" data-asset="THREE" aria-pressed="false">$THREE</button>+ </div>+ <div class="field">+ <label for="amount" id="amount-label">Amount (SOL)</label>+ <div class="amt-row">+ <input id="amount" type="number" min="0" step="0.001" inputmode="decimal" placeholder="0.0" />+ <span class="unit" id="amount-unit">SOL</span>+ </div>+ <div class="quick" id="quick"></div>+ <div class="est" id="estimate"></div>+ </div>+ <button class="btn" id="deposit-btn" type="button">Connect wallet & deposit</button>+ <div class="status" id="status" role="status" aria-live="polite"></div>++ <details class="manual">+ <summary>Sent from another wallet? Verify by signature</summary>+ <p class="muted" style="font-size:0.82rem;margin:0.6rem 0 0.3rem">Send to this three.ws deposit wallet:</p>+ <div class="addr" id="deposit-addr">—</div>+ <input id="manual-sig" type="text" placeholder="Paste transaction signature" />+ <button class="btn secondary" id="verify-btn" type="button" style="margin-top:0.6rem">Verify deposit</button>+ </details>+ </section>+ </div>++ <!-- Ledger -->+ <section class="card" style="margin-top:1.1rem" aria-label="History">+ <h2>History</h2>+ <div id="ledger-host">+ <table class="ledger" id="ledger" hidden>+ <thead>+ <tr><th>When</th><th>Activity</th><th style="text-align:right">Amount</th><th style="text-align:right">Balance</th></tr>+ </thead>+ <tbody id="ledger-body"></tbody>+ </table>+ <div class="empty" id="ledger-empty" hidden>No activity yet. Add credits to get started.</div>+ </div>+ </section>+ </div>++ <!-- Initial loading -->+ <div id="loading-state">+ <div class="credits-grid">+ <div class="card"><div class="skel" style="height:120px"></div></div>+ <div class="card"><div class="skel" style="height:220px"></div></div>+ </div>+ </div>+ </main>++ <script src="/brand.js" defer></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/src/credits.js"></script>+ </body>+</html>diff --git a/prompts/billion-dollar-program/00-README.md b/prompts/billion-dollar-program/00-README.mdnew file mode 100644index 000000000..7d2fc4b3f--- /dev/null+++ b/prompts/billion-dollar-program/00-README.md@@ -0,0 +1,151 @@+# three.ws — Production → $1B Program++> **Read this file in full before running any prompt in this folder.** Every prompt+> here (`01-*` … `44-*`) assumes the context below — do not re-derive it. Each prompt+> is a single, self-contained task meant to be pasted into its own fresh agent chat.++> **Note on this folder.** This is one complete, deduplicated, coherent 44-prompt+> program. Sibling folders under `prompts/` (e.g. `road-to-1b/`, `production-1b/`,+> `samples/`, `production-readiness/`) are parallel drafts generated concurrently —+> this folder (`billion-dollar-program/`) is the consolidated, authoritative set.+> If you only run one program, run this one.++## What this is++A sequenced program to take **three.ws** from "feature-rich but uneven" to+**production-grade and ready to scale to a $1B platform**. Each numbered file is one+self-contained task. Run them roughly in phase order — later phases assume earlier+ones are done — but any single prompt can be run independently.++This program is about **finishing, hardening, polishing, and growing what already+exists** so the platform is correct, reliable, fast, accessible, secure, observable,+and conversion-optimized. Net-new feature invention lives in the sibling folders+(`feature-innovation/`, `moonshots/`, `inventions/`).++## The bar (non-negotiable — applies to every prompt)++Every prompt inherits the operating rules in **`/CLAUDE.md`**. Re-read it. The rules+that matter most here:++- **No mocks, no fake data, no placeholders, no TODOs, no stubs.** If you touch it,+ finish it. Real APIs, real endpoints, real data.+- **No "good enough."** Fix mediocrity the moment you see it.+- **No errors without solutions.** Every error has a root cause; find it and fix it.+ Ship working fallbacks and failsafes, never lazy propagation. Never leak a vendor's+ internal state (e.g. a provider's billing page) to an end user.+- **Every state is designed** — loading, empty, error, populated, overflow.+- **The only coin is `$THREE`** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+ Never reference any other coin anywhere. See `/CLAUDE.md` for the two+ runtime-data-only mechanical exceptions.+- **Adopt vetted OSS over hand-rolling**; add hardening to new/unprotected paths+ rather than refactoring working code. Prefer the existing **cockatiel** resilience+ helper for retries/circuit-breakers.+- **Definition of done**: the checklist in `/CLAUDE.md` must be true. If you can't+ verify a step, say so explicitly — never claim done you can't verify.++## How to run a prompt++1. Open a fresh chat in this repo.+2. Paste the prompt file contents, or reference it: "Execute+ `prompts/billion-dollar-program/NN-*.md`".+3. Let the agent work end-to-end. It should use `TodoWrite` for multi-step work,+ exercise UI in a real browser (`npm run dev`, port 3000), and run the relevant tests.+4. Spot-check against the prompt's **Acceptance** section.+5. Commit + push only when the user asks (the agent pushes to **both** remotes,+ `threeD` and `threews`, per `/CLAUDE.md`).++## Repository orientation (so every prompt starts from truth)++- **`STRUCTURE.md`** maps every product surface to its directory. Read it before+ exploring the ~60 top-level dirs.+- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000). `pages/*.html`+ (~168 pages), `src/` (~810 modules), `public/`.+- Backend: Vercel functions in `api/` (~960 handlers), Cloudflare workers in+ `workers/` (18). Routing, functions, crons, headers, env all in `vercel.json`.+- 3D: Three.js + glTF/GLB. Avatar/animation pipeline under `public/animations/`,+ `src/glb-canonicalize.js`, `src/animation-retarget.js`. Model workers in+ `workers/model-*`. The avatar rule in `/CLAUDE.md` is law (no rig allowlist).+- Tests: `npm test` = `vitest run && playwright test` (456 vitest files). `npm run+ lint` (eslint), `npm run typecheck` (tsc on jsconfig). CI is `.github/workflows/ci.yml`+ with jobs: **lint**, **test**, **guards** (`check-api-not-bundled`, `check:images`,+ `build:pages`), **typecheck** (advisory).+- Changelog: every user-visible change gets an entry in `data/changelog.json`, then+ `npm run build:pages` regenerates `CHANGELOG.md` + `public/changelog.{json,xml}`.+- **Lean on the existing audit tooling — do not reinvent it:** `audit:deploy`,+ `audit:pages`, `audit:handlers`, `audit:web`, `audit:mcp`, `check:images`,+ `seo:meta`, `verify`, `verify:solana`, `verify:onchain`, `smoke:onchain`,+ `smoke:mcp`, `snapshot`. (See `package.json` scripts.)+- Resilience helpers and payments plumbing already exist in `api/_lib/` (x402-spec,+ x402-paid-endpoint, agent-wallet, secret-box, rate-limit, forge-health). Build on them.++## Known traps (from `/CLAUDE.md`)++- **Concurrent agents share this worktree.** Stage explicit paths only (never+ `git add -A`). Re-check `git status` before committing.+- **`npx vercel build` overwrites `api/*.js` in place** with esbuild bundles. Check+ `head -1` for `__defProp`/`createRequire` before committing a large `api/` diff.+- **Never pull/fetch/merge from the `threeD` remote** — it is push-only.++## Phases & index++**Phase 0 — Foundation (stop the platform from lying about "done")**+- `01` Test suite green + CI gate+- `02` Dead paths & broken links — every button works, every link resolves+- `03` Zero console errors & warnings across all pages+- `04` No-mocks / no-fake-data / no-TODO / no-stub sweep+- `05` Secrets & env hygiene++**Phase 1 — Cross-cutting production hardening**+- `06` Error handling & resilience (`api/` + `workers/`)+- `07` Security hardening (authz, input validation, headers, SSRF)+- `08` Rate limiting & abuse prevention+- `09` Accessibility (WCAG 2.2 AA)+- `10` Performance & Core Web Vitals+- `11` Mobile responsiveness (320 / 768 / 1440)+- `12` Every state designed (loading / empty / error / overflow)+- `13` Design-system consistency (tokens, spacing, typography, theming)+- `14` SEO & structured data++**Phase 2 — Product surface completeness (each end-to-end)**+- `15` Forge / Text→3D / Avatar generation pipeline+- `16` Marketplace+- `17` Agent profiles, Agent Studio & economy+- `18` Wallet & x402 payments+- `19` Walk companion, Page-Agent & Feature Tour+- `20` Scene Studio & Animation Studio+- `21` Avatar creator / Character Studio / Selfie→avatar+- `22` Pump.fun launch, Oracle, trading & $THREE surfaces+- `23` MCP servers (production-ready)+- `24` SDK publishing & docs+- `25` Worlds & Coin Clash (token-gated 3D)++**Phase 3 — Scale, infra, observability**+- `26` Observability (logging, metrics, error tracking)+- `27` Database integrity & migrations+- `28` Deploy pipeline & rollback safety+- `29` Uptime monitoring & public status page+- `30` Load & stress testing+- `31` Solana RPC & on-chain resilience+- `32` Caching, CDN & R2 asset strategy++**Phase 4 — Growth to $1B**+- `33` Onboarding & activation funnel+- `34` Home / landing conversion+- `35` Pricing & monetization surfaces+- `36` Growth analytics instrumentation+- `37` Developer experience & docs site+- `38` Referral & virality loops+- `39` Trust, safety & moderation+- `40` Legal, compliance, ToS & privacy+- `41` i18n completion+- `42` PWA & offline & notifications+- `43` Brand, press & social proof+- `44` Launch-readiness review (the final gate)++## Prompt anatomy++Each file has: **Why this matters for $1B**, **Mission**, **Map** (where things+live — trust but verify; files move), **Do this** (ordered steps), **Must-not**+(guardrails), and **Acceptance** (a checklist that must be all-true before claiming+done). If a path is stale, find the real one and proceed — never stop because a path+was wrong.diff --git a/prompts/billion-dollar-program/01-test-suite-green-and-ci-gate.md b/prompts/billion-dollar-program/01-test-suite-green-and-ci-gate.mdnew file mode 100644index 000000000..945ca83d4--- /dev/null+++ b/prompts/billion-dollar-program/01-test-suite-green-and-ci-gate.md@@ -0,0 +1,92 @@+# 01 — Test suite green + CI gate++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++CI is the only thing standing between a green checkmark and a money-path+regression reaching production. Right now the suite is large (458 vitest files ++a Playwright e2e set) but the gate is soft: lint allows the warning backlog and+typecheck is advisory (`continue-on-error: true`). A platform that ships real+USDC payments cannot tolerate "passing" CI that lets type errors and lint+warnings through. Make the suite genuinely green and reliable, then ratchet the+gate so "green" actually means "safe to merge."++## Mission++Get `npm test` (`vitest run && playwright test`) fully green and non-flaky, then+deliver a concrete, staged plan (and the first ratchet step) to flip the advisory+typecheck job to a hard gate and tighten eslint to `--max-warnings 0`.++## Map (trust but verify — files move)++- **CI definition** — [.github/workflows/ci.yml](../../.github/workflows/ci.yml).+ Jobs: `lint` (`npx eslint .`), `test` (`npx vitest run`), `guards`+ (`check-api-not-bundled` + `check:images` + `build:pages`), `typecheck`+ (advisory, `continue-on-error: true`).+- **Vitest config** — [vitest.config.js](../../vitest.config.js). Note the+ 120s test/hook timeouts and `MAX_FORKS` cap for small CI/Codespace hosts.+- **Playwright config** — [playwright.config.js](../../playwright.config.js).+ `testDir: tests/e2e`, `retries: 1`, `fullyParallel: false`, dev-server cold+ budget 180s. Specs in [tests/e2e/](../../tests/e2e).+- **Scripts** — [package.json](../../package.json): `test`, `test:core`+ (`--maxWorkers=1`), `test:gate` ([scripts/test-gate.mjs](../../scripts/test-gate.mjs),+ the curated deploy-critical subset), `lint`, `lint:fix`, `typecheck`+ (`tsc -p jsconfig.json`).+- **Typecheck scope** — [jsconfig.json](../../jsconfig.json): `checkJs: false`,+ opt-in via `// @ts-check` pragma; `include` is the ratchet allowlist.+- **Lint config** — [eslint.config.js](../../eslint.config.js).+- **Source guards** — [scripts/check-api-not-bundled.mjs](../../scripts/check-api-not-bundled.mjs),+ [scripts/audit-image-loading.mjs](../../scripts/audit-image-loading.mjs) (`check:images`).++## Do this++1. Run `npx vitest run` and capture every failure. Fix each at the root — never+ `.skip` a real test to go green. If a test depends on live credentials that+ are absent locally, confirm it is already guarded; if not, gate it cleanly on+ env presence rather than deleting it.+2. Re-run failing files in isolation (`npx vitest run path/to/file.test.js`) and+ 3x in a row to separate true failures from flakes. For flakes, find the cause+ (shared global state, real timers, unmocked I/O, fork contention) and fix it —+ do not just bump a timeout. `vitest.config.js` already sets generous ceilings.+3. Start the dev server (`npm run dev`, port 3000) and run `npx playwright test`.+ Fix e2e failures at the source. Honor `fullyParallel: false` and the cold-start+ budget; do not lower assertions to pass.+4. Confirm the guards job is green: `node scripts/check-api-not-bundled.mjs`,+ `npm run check:images`, `npm run build:pages`.+5. Run `npm run lint` and count warnings. Burn the backlog down with `npm run+ lint:fix` for auto-fixables, then hand-fix the rest — no blanket+ `eslint-disable` of whole files. Track the count before and after.+6. Run `npm run typecheck`. Catalog the errors by file. Fix the cheap ones now+ and add `// @ts-check` + the file to `jsconfig.json` `include` as you bring each+ clean (the ratchet rule the jsconfig comment describes).+7. Write the staged ratchet plan into this task's report: (a) flip eslint to+ `--max-warnings 0` in `ci.yml` once the count hits 0; (b) flip typecheck's+ `continue-on-error` to `false` once `npm run typecheck` is clean. Land whichever+ ratchet is already achievable (likely eslint) in `ci.yml` now.+8. Re-run the full `npm test` once more end-to-end to confirm a clean, repeatable+ green before claiming done.++## Must-not++- Do not skip, delete, or weaken a test to make CI green — fix the code or the test.+- Do not flip typecheck/eslint to a hard gate while errors/warnings remain; that+ breaks every other agent's PR. Ratchet only when the count is actually zero.+- Do not commit a `vercel build`-bundled `api/*.js` (check `head -1` for `__defProp`).+- Do not reference any coin other than `$THREE` in any test or fixture.+- Do not mask flakiness with retries or longer timeouts in place of a real fix.++## Acceptance (all true before claiming done)++- [ ] `npx vitest run` passes locally with zero failures, repeatable across 3 runs.+- [ ] `npx playwright test` passes against `npm run dev` with no skipped real specs.+- [ ] `guards` job commands all pass (`check-api-not-bundled`, `check:images`, `build:pages`).+- [ ] Current eslint warning count is recorded and reduced (target 0); any+ achievable ratchet (`--max-warnings 0`) is landed in `ci.yml`.+- [ ] A concrete, staged plan to flip the typecheck gate is documented, with the+ first ratchet step applied or explicitly blocked-and-explained.+- [ ] No coin other than `$THREE` introduced; no new mocks/stubs/TODOs.+- [ ] If a step could not be verified locally (e.g. live-cred e2e), it is called+ out explicitly rather than claimed.diff --git a/prompts/billion-dollar-program/02-dead-paths-and-broken-links.md b/prompts/billion-dollar-program/02-dead-paths-and-broken-links.mdnew file mode 100644index 000000000..89d7acf71--- /dev/null+++ b/prompts/billion-dollar-program/02-dead-paths-and-broken-links.md@@ -0,0 +1,90 @@+# 02 — Dead paths & broken links++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Nothing kills trust faster than a button that does nothing or a link that 404s.+With ~125 pages, ~810 src modules, and ~961 api handlers, dead-ends accumulate+silently — a nav entry to a page that no longer exists, an `<a href="#">` that+was never wired, a CTA whose handler was deleted. Every dead path is a leak in+the conversion funnel and a screenshot of brokenness. `/CLAUDE.md` is explicit:+"If a button exists, it must work. If a link exists, it must go somewhere."++## Mission++Audit every interactive element and route so that every button does something,+every `<a href>`/route resolves to a live destination, and every nav entry goes+somewhere real — then fix or remove every dead-end found.++## Map (trust but verify — files move)++- **Full-site audit harness** — [scripts/page-audit.mjs](../../scripts/page-audit.mjs)+ (`npm run audit:web`). Drives real Chromium over every page in desktop + mobile,+ records failed network requests, HTTP >= 400, missing `<title>`, and **empty+ links/buttons**. Writes `reports/page-audit-<ts>.{json,md}`.+- **Route-documentation guard** — [scripts/audit-page-index.mjs](../../scripts/audit-page-index.mjs)+ (`npm run audit:pages`). Cross-checks `vercel.json` routes against+ [data/pages.json](../../data/pages.json); flags pages with no manifest entry.+- **Empty-handler guard** — [scripts/audit-empty-handlers.mjs](../../scripts/audit-empty-handlers.mjs)+ (`npm run audit:handlers`). Fails on any `api/*.js` that is empty or exports+ nothing (Vercel routes to it but it can never respond).+- **Routing & headers** — [vercel.json](../../vercel.json) (rewrites/routes for+ pretty paths and dynamic routes).+- **Navigation source of truth** — [public/nav-data.js](../../public/nav-data.js)+ (`NAV_GROUPS`, every menu item's `href`), rendered by+ [public/nav.js](../../public/nav.js), styled by [public/nav.css](../../public/nav.css).+- **Surfaces to crawl** — [pages/](../../pages) (~125 `*.html`), [src/](../../src)+ (~810 modules), [public/](../../public).++## Do this++1. Start `npm run dev` (port 3000) and run `BASE_URL=http://localhost:3000 npm run+ audit:web`. Open the generated `reports/page-audit-*.md` and triage every+ empty-link/empty-button finding and every HTTP >= 400 / requestfailed entry.+2. Run `npm run audit:pages --strict` and `npm run audit:handlers`. Fix every gap:+ a flagged empty handler is either implemented (real response) or deleted with+ its route; a route missing from `data/pages.json` gets a manifest entry.+3. Walk every `href` in [public/nav-data.js](../../public/nav-data.js) `NAV_GROUPS`+ and the top-level links. For each, confirm the destination resolves to a live+ page (in the browser, not just file existence). Fix or remove dead entries —+ nav is the single source of truth, so a broken entry breaks it everywhere.+4. Grep the codebase for placeholder links and no-op handlers and resolve each:+ `href="#"`, `href="javascript:void(0)"`, `onclick=""`, `<a>` with no href,+ `<button>` with no listener. Wire the real action or remove the element.+5. Cross-check dynamic routes (agent profiles, dashboards, `/launches`, marketplace+ detail pages) — click through from a list view into a detail view and back.+ The "list links to detail" connection in `/CLAUDE.md` must hold.+6. For any page that legitimately can't resolve yet (e.g. a feature behind auth or+ a not-yet-built surface), make the entry point honest: gate it, label it, or+ remove it — never leave a live link to a dead place.+7. Exercise the primary CTAs in a real browser (Forge "Generate", marketplace+ "Buy", wallet "Connect", launch flow): every one performs a real action, not a+ silent failure. Watch the Network tab to confirm real calls fire.+8. Re-run `npm run audit:web`, `npm run audit:pages --strict`, and `npm run+ audit:handlers`; confirm the dead-path findings are cleared. Add a+ `data/changelog.json` entry for any user-visible fix, then `npm run build:pages`.++## Must-not++- Do not "fix" a broken link by pointing it at the homepage — route it to the+ correct destination or remove the element.+- Do not delete a working feature to silence an audit finding; understand first.+- Do not introduce mocks, stubs, TODOs, or `href="#"` placeholders.+- Do not reference any coin other than `$THREE` in nav, copy, or links.+- Do not edit working code paths you didn't need to touch — additive fixes only.++## Acceptance (all true before claiming done)++- [ ] `npm run audit:web` reports zero empty-link / empty-button findings and no+ unexplained HTTP >= 400 across the crawled pages.+- [ ] `npm run audit:pages --strict` and `npm run audit:handlers` both exit clean.+- [ ] Every `href` in `public/nav-data.js` resolves to a live page in the browser.+- [ ] No `href="#"`, `javascript:void(0)`, or no-op handler remains on a shipped+ interactive element.+- [ ] Primary CTAs (Forge, marketplace, wallet, launch) perform real actions with+ real network calls, verified in a real browser.+- [ ] Existing tests still pass (`npm test`); changelog updated for visible fixes+ and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/03-zero-console-errors.md b/prompts/billion-dollar-program/03-zero-console-errors.mdnew file mode 100644index 000000000..caf69420c--- /dev/null+++ b/prompts/billion-dollar-program/03-zero-console-errors.md@@ -0,0 +1,85 @@+# 03 — Zero console errors & warnings++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++A console full of red is a tell that the team doesn't sweat the details — and+the warnings are often real bugs wearing a yellow coat (a 404'd asset, a failed+fetch with a swallowed error, a React/Three.js misuse that leaks memory). Across+~125 pages, every console error is a paper cut on the perceived quality of the+platform and a hint to a savvy user that something is broken under the hood.+`/CLAUDE.md`'s definition of done requires "No console errors. No console+warnings from your code."++## Mission++Load every page, capture all console errors and warnings (plus uncaught+exceptions and failed requests), and fix each at the source — no suppression,+no `console.warn` muting, no try/catch that just swallows.++## Map (trust but verify — files move)++- **Full-site console audit** — [scripts/page-audit.mjs](../../scripts/page-audit.mjs)+ (`npm run audit:web`). Drives real Chromium over every page (desktop + mobile)+ and records `console.error`/`console.warn`, `pageerror` (uncaught exceptions),+ `requestfailed`, and HTTP >= 400. Output: `reports/page-audit-<ts>.{json,md}`.+ Targets via `BASE_URL` (default `https://three.ws`; use `http://localhost:3000`).+- **Visual snapshot harness** — [scripts/page-snapshot.mjs](../../scripts/page-snapshot.mjs)+ (`npm run snapshot`). Full-page Chromium screenshots of every page — useful to+ confirm a console fix didn't break the render.+- **Page manifest (the page list both harnesses crawl)** — [data/pages.json](../../data/pages.json).+- **e2e specs** — [tests/e2e/](../../tests/e2e) (Playwright). Existing specs like+ `club.spec.js`, `nav-auth.spec.js` already assert no page errors on key flows.+- **Surfaces** — [pages/](../../pages) (~125 `*.html`), [src/](../../src) (~810+ modules), [public/](../../public). Shared boot/nav: [public/nav.js](../../public/nav.js).++## Do this++1. Start `npm run dev` (port 3000) and run `BASE_URL=http://localhost:3000 npm run+ audit:web`. Read `reports/page-audit-*.md` and build a per-page list of every+ console error, warning, uncaught exception, and failed request.+2. Triage by root cause, not by page. The same offender (a missing favicon, a bad+ import, a deprecated Three.js API, an unguarded `null` access) usually fires on+ many pages — fix it once at the source.+3. For each finding, fix the cause: 404'd asset → correct the path or ship the+ asset; failed fetch → handle the error at the boundary with a designed error+ state (per `/CLAUDE.md`), never an empty catch; deprecation warning → migrate to+ the current API; `null`/`undefined` access → guard the real data flow.+4. Never silence. Do not delete `console.warn` calls, wrap noise in+ `try{}catch{}`, or filter the audit's output to hide a finding. The bar is no+ warnings *from our code*; legitimate third-party noise must be understood and+ documented, not blanket-suppressed.+5. Pay special attention to the heavy 3D pages (Forge, Scene Studio, Club, Walk):+ WebGL context warnings, texture/format issues, and animation-retarget warnings+ are real signals. Cross-check against the avatar rule in `/CLAUDE.md`.+6. Re-run `npm run audit:web` after each batch of fixes and confirm the count+ drops toward zero. Spot-check fixed pages live with the browser console open.+7. Run `npm run snapshot` on the pages you changed and eyeball the screenshots to+ confirm no fix introduced a visual regression.+8. Run the e2e specs that assert clean console (`npx playwright test`) and the unit+ suite (`npx vitest run`). Add a `data/changelog.json` entry if any fix is+ user-visible (e.g. a previously-broken feature now works), then `npm run build:pages`.++## Must-not++- Do not suppress, filter, or delete console output to make the count drop — fix+ the cause.+- Do not wrap errors in empty `try/catch` or swallow rejected promises.+- Do not introduce mocks, stubs, fake data, or TODOs while fixing.+- Do not reference any coin other than `$THREE` in any copy or asset you touch.+- Do not refactor working modules beyond what the fix requires — additive, surgical.++## Acceptance (all true before claiming done)++- [ ] `npm run audit:web` reports zero `console.error`, zero `console.warn` from+ our code, zero `pageerror`, and no unexplained failed requests across pages.+- [ ] Every fix addresses a root cause; no suppression, output filtering, or empty+ catch was used to hide a finding.+- [ ] Heavy 3D pages (Forge, Scene Studio, Club, Walk) load clean in a real browser+ with the console open.+- [ ] `npm run snapshot` of changed pages shows no visual regression.+- [ ] `npx vitest run` and `npx playwright test` pass.+- [ ] Changelog updated for any user-visible fix and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/04-no-mocks-no-stubs-sweep.md b/prompts/billion-dollar-program/04-no-mocks-no-stubs-sweep.mdnew file mode 100644index 000000000..99b9a34d0--- /dev/null+++ b/prompts/billion-dollar-program/04-no-mocks-no-stubs-sweep.md@@ -0,0 +1,95 @@+# 04 — No-mocks / no-fake-data / no-TODO / no-stub sweep++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++`/CLAUDE.md`'s hard rules are absolute: no mocks, no fake data, no placeholders,+no TODOs, no stub functions, no `setTimeout` fake-loading, no fallback sample+arrays shipped to production. Every one of these is a promise the product can't+keep — a "feature" that secretly renders canned data, a progress bar that fakes+work, a handler that quietly does nothing. A $1B platform cannot ship a single+one. This sweep finds and eliminates them across the real source tree.++## Mission++Quantify every shortcut marker in shipped source, then fix or delete each one so+the codebase contains no TODO/FIXME, no `not implemented`, no production+mock/fake/sample arrays, and no fake `setTimeout` loading — per `/CLAUDE.md`.++## Map (trust but verify — files move)++- **Shipped source to sweep** — [api/](../../api) (~961 handlers), [src/](../../src)+ (~810 modules), [public/](../../public), [workers/](../../workers) (18). Exclude+ test files (`*.test.js`, `*.spec.js`), `node_modules`, and vendored dirs.+- **Hard rules reference** — [/CLAUDE.md](../../CLAUDE.md) "Hard rules+ (non-negotiable)" §1–6 and "The only coin — $THREE".+- **Empty-handler guard (catches stub handlers)** — [scripts/audit-empty-handlers.mjs](../../scripts/audit-empty-handlers.mjs)+ (`npm run audit:handlers`): fails on any `api/*.js` that exports nothing.+- **Resilience helpers to use instead of fakes** — [api/_lib/](../../api/_lib)+ (`forge-health.js`, `x402-spec.js`, `rate-limit.js`; `cockatiel` for real+ retries/circuit-breakers — never a `setTimeout` stand-in).+- **Baseline marker counts (re-measure first — they drift):** ~62 `// TODO`+ comments, ~6 `FIXME`, ~2 `const sample|mock|fake = [...]` arrays, ~7+ `setTimeout` calls near `progress`/`loading`/`width` in `src/`, 0+ `throw … not implemented`. Confirm with the greps below before you start.++## Do this++1. **Quantify first.** Run, and record the exact counts (re-run at the end to+ prove zero):+ - TODO/FIXME: `grep -rIn --include='*.js' --include='*.mjs' --include='*.html' -E 'TODO|FIXME' api src public workers | grep -v node_modules`+ - not implemented: `grep -rIn -iE "not implemented|notImplemented|throw new Error\(['\"\`].*not impl" api src public workers`+ - prod sample/mock/fake arrays: `grep -rIn -E 'const (sample|mock|fake|dummy)[A-Za-z]*\s*=\s*\[' api src public workers`+ - fake loading: `grep -rIn -E 'setTimeout' src | grep -iE 'progress|loading|fake|width'`+ - commented-out code blocks and `implement later`/`stub`/`placeholder`.+2. **TODO/FIXME — implement or delete.** For each, either build the real behavior+ the comment describes, or remove it if it's stale. No TODO survives. If a+ comment documents a genuine known limitation, convert it to honest user-facing+ handling (designed error/empty state), not a silent gap.+3. **Stub functions / empty handlers — finish them.** Run `npm run audit:handlers`;+ any flagged file gets a real implementation or is deleted along with its route.+ Hunt for functions that `return null`/`return []`/do nothing where the caller+ expects real data, and wire them to the real API.+4. **Production sample/mock/fake arrays — replace with real fetch.** Any+ `const sampleAgents = [...]` or fallback array rendered to users must become a+ real call to the live endpoint, with designed loading/empty/error states.+ Mocks belong only in `tests/` — leave those alone.+5. **Fake `setTimeout` loading/progress — make it real.** Replace simulated+ progress and `setTimeout` "loading" with progress driven by the actual async+ operation (real fetch/stream/poll). If the operation has no progress signal,+ use an honest indeterminate indicator (skeleton/spinner), not a faked bar.+6. **Commented-out code — delete or implement.** Per `/CLAUDE.md` §3, no+ commented-out code in committed work.+7. **`throw new Error("not implemented")` — implement it.** None should exist; if+ the grep surfaces any, build the real path.+8. **Verify and log.** Re-run every grep from step 1 and confirm zero in shipped+ source. Run `npm run audit:handlers`, `npx vitest run`, and exercise any+ surface you changed in a real browser (`npm run dev`). Add a `data/changelog.json`+ entry for any user-visible change (e.g. a screen that now shows real data), then+ `npm run build:pages`.++## Must-not++- Do not touch or remove mocks inside `tests/` — those are legitimate test doubles.+- Do not delete a feature to make a marker disappear; build the real version.+- Do not swap one shortcut for another (e.g. a sample array for a hardcoded+ constant) — wire the real data source.+- Do not reference any coin other than `$THREE` in any replacement data, fixture,+ or copy; use the $THREE CA or a clearly-synthetic placeholder.+- Do not refactor working code beyond what removing the marker requires.++## Acceptance (all true before claiming done)++- [ ] Start-of-task marker counts are recorded; end-of-task re-run shows **zero**+ TODO/FIXME/`not implemented`/prod sample-array/fake-`setTimeout` markers in+ `api`, `src`, `public`, `workers` (tests excluded).+- [ ] `npm run audit:handlers` exits clean (no empty/export-less handlers).+- [ ] Every former mock/sample surface now fetches real data with designed+ loading/empty/error states, verified in a real browser.+- [ ] No commented-out code remains in the files touched.+- [ ] No coin other than `$THREE` introduced anywhere.+- [ ] `npx vitest run` passes; changelog updated for user-visible changes and+ `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/05-secrets-and-env-hygiene.md b/prompts/billion-dollar-program/05-secrets-and-env-hygiene.mdnew file mode 100644index 000000000..f0a1dc981--- /dev/null+++ b/prompts/billion-dollar-program/05-secrets-and-env-hygiene.md@@ -0,0 +1,99 @@+# 05 — Secrets & env hygiene++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++This platform holds custody keys, x402 payment routing addresses, RPC and AI+provider credentials, and a Telegram bot token. A single leaked secret in git+history is a wallet drain or a takeover — the kind of incident that ends a $1B+trajectory overnight. Equally damaging in slow motion: an undocumented env var+that makes a surface silently fail in production because nobody knew to set it.+Both must be closed: nothing secret committed, everything required documented.++## Mission++Ensure `.env.example` documents every env var the code actually reads, no secret+is committed or sits in git history, anything ever exposed is rotated, and the+required env per surface is documented.++## Map (trust but verify — files move)++- **Centralized env access** — [api/_lib/env.js](../../api/_lib/env.js). Lazy by+ design: `req()` throws at first use on a missing var, `opt()`/`addr()` for+ optional/address values. This is the canonical inventory of what the backend reads.+- **Env template** — [.env.example](../../.env.example) (~246 documented vars,+ grouped by surface; copy to `.env.local` for dev). The doc that must stay in+ sync with what the code reads.+- **Secret handling** — [api/_lib/secret-box.js](../../api/_lib/secret-box.js)+ (encryption at rest), [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js)+ (custody key derivation/spend guards).+- **Deploy env surface** — [vercel.json](../../vercel.json) (functions, crons,+ headers; env is set in the Vercel dashboard, not committed).+- **Ignore rules (already block .env files)** — [.gitignore](../../.gitignore)+ (lines for `.env`, `.env.local`, `.env*.local`, `.env*`, etc.).+- **Note:** there is currently **no** dedicated secret-scan workflow in+ [.github/workflows/](../../.github/workflows) — installing one is in scope.++## Do this++1. **Build the read-set.** Grep every `process.env.X`, `req('X')`, `opt('X')`,+ `addr(env.X)` across [api/](../../api), [src/](../../src), [workers/](../../workers),+ and [scripts/](../../scripts). Dedupe into the authoritative list of vars the+ code reads. `api/_lib/env.js` is the spine; capture the rest too.+2. **Reconcile with `.env.example`.** Diff the read-set against+ [.env.example](../../.env.example). Add every read-but-undocumented var with a+ one-line comment (purpose, format, whether required), grouped under its surface.+ Mark each as required/optional. Remove entries for vars no longer read.+3. **Scan working tree + history for committed secrets.** Run a real scanner —+ `npx gitleaks detect --no-banner` (or `npx --yes @trufflesecurity/trufflehog+ git file://. --only-verified`). Triage every hit: real secret vs. test fixture+ vs. example placeholder. Treat the $THREE CA and clearly-synthetic placeholders+ as non-secrets.+4. **For any real secret found committed or in history:** rotate it at the provider+ immediately, update the value in Vercel/Upstash/etc. (never in the repo), and+ document the rotation in this task's report. A scrubbed value that was ever+ pushed is already compromised — rotation is non-negotiable; removal alone is not.+5. **Confirm `.gitignore` coverage.** Verify every `.env*` variant and any local+ key/credential file is ignored (`git check-ignore .env .env.local`). Add any+ gap. Ensure no `.env*` file is currently tracked (`git ls-files | grep -E '\.env'`).+6. **Document required env per surface.** For each major surface (Forge/text→3D,+ wallet/x402, pump.fun/Oracle, MCP, Solana RPC), list the vars it needs to+ function so an operator knows what to set. Keep this in `.env.example` group+ comments — the existing file is already grouped by surface; extend that pattern.+7. **Verify graceful degradation.** Confirm a surface with a missing optional var+ fails honestly (designed error/clear log) rather than crashing unrelated+ endpoints — the lazy `req()` pattern in `env.js` exists for exactly this; check+ it holds for any var you add.+8. **Add a secret-scan CI gate** (no GitHub Actions secret scan exists today): a+ `gitleaks` job in [.github/workflows/ci.yml](../../.github/workflows/ci.yml) so+ future pushes are blocked on a committed secret. Run `npx vitest run` to confirm+ nothing broke. Add a `data/changelog.json` entry only if a user-visible/security+ change resulted, then `npm run build:pages`.++## Must-not++- Do not commit any real secret, key, or token — values live in Vercel/Upstash,+ not the repo. `.env.example` holds placeholders only.+- Do not "fix" an exposed secret by deleting it from the file without rotating it+ at the provider — an exposed secret is a compromised secret.+- Do not paste a real coin's mint/creator/holder address anywhere; the only coin+ is `$THREE` (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+- Do not introduce mocks, stubs, or TODOs; do not weaken `env.js` guards.+- Do not log secret values in any new error path you add.++## Acceptance (all true before claiming done)++- [ ] Every env var read by `api/`, `src/`, `workers/`, `scripts/` is documented in+ `.env.example` (purpose + format + required/optional), grouped by surface.+- [ ] `gitleaks`/`trufflehog` scan of working tree **and** history is clean (or+ every finding triaged as a non-secret placeholder, documented).+- [ ] Any real secret ever committed is rotated at the provider and the rotation+ is recorded; no secret value sits in the repo or history.+- [ ] No `.env*`/credential file is tracked; `.gitignore` covers all variants.+- [ ] Required-env-per-surface is documented so an operator can configure cleanly.+- [ ] A secret-scan CI gate is added to `ci.yml`; `npx vitest run` passes.+- [ ] Only `$THREE` referenced; changelog updated if any user-visible/security+ change resulted and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/06-error-handling-resilience.md b/prompts/billion-dollar-program/06-error-handling-resilience.mdnew file mode 100644index 000000000..e49144767--- /dev/null+++ b/prompts/billion-dollar-program/06-error-handling-resilience.md@@ -0,0 +1,104 @@+# 06 — Error handling & resilience (api/ + workers/)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++A $1B platform never dies because an upstream blinked. Solana RPC throttles, OpenAI+returns a 529, pump.fun times out, an image provider 502s — and the user must still+get a fast, honest, recoverable result, never a hung spinner or a leaked vendor stack+trace. `/CLAUDE.md` is explicit: **no errors without solutions; ship working fallbacks+and failsafes; lazy error propagation is not engineering.** Resilience is what turns+demo-grade into platform-grade.++## Mission++Wrap every external call in `api/` and `workers/` in a timeout + retry + circuit+breaker via the existing **cockatiel** helper, handle errors only at the boundaries+(network, user input) while internal code trusts itself, and guarantee no unhandled+promise rejection and no provider internals ever reach a user.++## Map (trust but verify — files move)++- **Resilience helper (build on this — do not re-roll)** — [api/_lib/resilience.js](../../api/_lib/resilience.js):+ `withBreaker(name, fn, { fallback, threshold, halfOpenAfterMs })`, `isCircuitError`.+ It is the ONLY current cockatiel consumer — that is the gap this prompt closes.+- **Boundary error envelope** — [api/_lib/http.js](../../api/_lib/http.js): `wrap()`+ (catches unhandled rejections, redacts keyed RPC URLs from 5xx bodies, emits a+ correlation `ref`), `serverError`, `respondError`, `redactUrl`.+- **LLM provider chain** — [api/_lib/llm.js](../../api/_lib/llm.js) (`llmComplete`,+ anthropic/openai/nvidia/groq fetch at lines ~95/169/183/238),+ [api/_lib/llm-health.js](../../api/_lib/llm-health.js) (probe timeouts).+- **Solana RPC failover** — [api/_lib/solana/rpc-fallback.js](../../api/_lib/solana/rpc-fallback.js)+ (`createRpcFallback`, rotation + cooldown), [api/_lib/solana/connection.js](../../api/_lib/solana/connection.js),+ [api/_lib/helius.js](../../api/_lib/helius.js), [api/_lib/onchain.js](../../api/_lib/onchain.js).+- **Other upstreams** — pump.fun (`frontend-api-v3.pump.fun`, `gmgn.ai`),+ [api/_lib/birdeye.js](../../api/_lib/birdeye.js), [api/_lib/aixbt.js](../../api/_lib/aixbt.js),+ Telegram/IPFS/Pinata. Image/3D providers in [workers/](../../workers): `model-trellis`,+ `model-hunyuan3d`, `model-triposg`, `rembg`, `texture`, `unirig`.+- **MCP error masking** — [api/_lib/mcp-error-sanitize.js](../../api/_lib/mcp-error-sanitize.js)+ (`sanitizeToolError`), used by [api/_lib/mcp-dispatch.js](../../api/_lib/mcp-dispatch.js).+- **Tests** — [tests/resilience.test.js](../../tests/resilience.test.js),+ [tests/api/mcp-resilience.test.js](../../tests/api/mcp-resilience.test.js),+ [tests/api/pump-trending-resilience.test.js](../../tests/api/pump-trending-resilience.test.js).++## Do this++1. **Inventory raw external calls.** `grep -rnE "fetch\(|new Connection\(|axios" api/+ workers/` and cross-reference the host list (`grep -rhoE "https://[a-z.-]+" api/+ workers/`). Mark every site that hits Solana RPC, an LLM proxy, an image/3D+ provider, pump.fun/gmgn, Birdeye, or Telegram/IPFS. That set is your work queue.+2. **Every external call gets a timeout.** Any `fetch` without `signal:+ AbortSignal.timeout(ms)` (or equivalent) is a bug — a hung socket stalls the lambda.+ Add a tight, intent-appropriate timeout (probes ~5s, generations longer).+3. **Wrap each upstream in a named breaker.** Use `withBreaker('pumpfun:trending',+ () => …, { fallback, threshold, halfOpenAfterMs })` so an outage fails fast instead+ of every request paying the full timeout. Name breakers per logical upstream.+ Provide a real `fallback` (cached value, neutral empty result) — never silently null.+4. **Solana goes through the failover path.** Confirm RPC reads/writes use+ `createRpcFallback`/`rpc-fallback.js` (rotation + cooldown), not a bare+ `new Connection(url)`. Retire any one-off connection that bypasses rotation.+5. **No unhandled promise rejections.** Verify every Vercel handler is wrapped by+ `wrap()` (or equivalent try/catch at the boundary). Audit fire-and-forget calls+ (`void something()`, background telemetry) — every floating promise needs a+ `.catch`. Internal pure functions stay un-try/catched; trust them.+6. **Mask every vendor internal.** Boundary errors must map to neutral, actionable+ copy via the `http.js` envelope (and `sanitizeToolError` for MCP). No raw stack,+ no keyed RPC URL, no provider billing/quota text, no 402/credit message reaches the+ client. Raw detail lives only in `console.error` + the `ref`.+7. **Add coverage for each new failure mode.** Extend `tests/resilience.test.js` (and+ the mcp/pump resilience tests) so timeout, open-circuit, 429/529, and fallback are+ asserted. Run `npx vitest run tests/resilience.test.js tests/api/*resilience*.test.js`.+8. **Sanity-check live.** `npm run dev`, exercise a forge generation and a pump/oracle+ read with the network throttled; confirm graceful degrade, no console errors, real+ elapsed time. If anything is user-visible, add a `data/changelog.json` entry (tag+ `infra` or `improvement`) and run `npm run build:pages`.++## Must-not++- Do not hand-roll a new retry/cooldown/breaker — extend `withBreaker`/cockatiel.+- Do not swallow errors into silent nulls without a designed fallback or a log line.+- Do not let any vendor stack, keyed URL, billing/quota/credit message, or 402 detail+ reach a user — mask at the boundary, log raw server-side with a `ref`.+- Do not add try/catch to internal pure code — handle at boundaries only.+- Do not break working failsafes (the Solana rotation, `wrap()` redaction, fail-closed+ limiters). Add resilience; never weaken what already protects money paths.+- Do not reference any coin other than `$THREE`.++## Acceptance (all true before claiming done)++- [ ] Every external call site in `api/` + `workers/` has a timeout and a named+ `withBreaker` (or the existing Solana failover) — verified by grep, no bare+ timeout-less `fetch` to a third party remains.+- [ ] No unhandled promise rejection path: every handler is `wrap()`-ed, every+ fire-and-forget promise has a `.catch`.+- [ ] Throttling/killing an upstream degrades gracefully in a real browser — no hung+ spinner, no console error, neutral copy, real elapsed time.+- [ ] No vendor internals (stack, keyed URL, billing/quota/402) appear in any client+ response; raw detail is logged with a correlation `ref`.+- [ ] `tests/resilience.test.js` + the mcp/pump resilience tests pass, with new cover+ for timeout, open-circuit, 429/529, and fallback.+- [ ] Any user-visible change has a `data/changelog.json` entry and `npm run+ build:pages` is clean.diff --git a/prompts/billion-dollar-program/07-security-hardening.md b/prompts/billion-dollar-program/07-security-hardening.mdnew file mode 100644index 000000000..48b3b5209--- /dev/null+++ b/prompts/billion-dollar-program/07-security-hardening.md@@ -0,0 +1,117 @@+# 07 — Security hardening (authz, validation, headers, SSRF)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The platform moves real value: custodial wallet payouts, x402 USDC settlement, $THREE+gating, on-chain launches. One missing authorization check, one unvalidated body, one+server-side fetch that follows an attacker URL, and a $1B platform becomes a breach+headline. Security is not a phase you bolt on — it is the precondition for every dollar+that flows through three.ws. This prompt hardens the four highest-leverage classes:+authorization, input validation, response headers, and SSRF.++## Mission++Confirm every endpoint authorizes its caller, every input is zod-validated at the+boundary, security headers (CSP, HSTS, X-Frame-Options, Referrer-Policy,+Permissions-Policy) are correct in `vercel.json`, CORS is allowlisted, and every+server-side URL/image fetch is SSRF-guarded — then run `/security-review` and fix+everything it surfaces.++## Map (trust but verify — files move)++- **Input validation (zod — ~123 files use it)** — [api/_lib/validate.js](../../api/_lib/validate.js):+ shared schemas (`email`, `slug`, `httpUrl`, `createAvatarBody`, …) + helpers+ `parse(schema, input)`, `validateQuery(req, schema)`, `isValidSolanaAddress`,+ `isValidEvmAddress`, `isUuid`. Validation 400s go through+ [api/_lib/http.js](../../api/_lib/http.js) `validationError`.+- **AuthZ helpers** — [api/_lib/auth.js](../../api/_lib/auth.js) (`getSessionUser`,+ `authenticateBearer`, `verifyCsrfToken`, `isSameSiteOrigin`, `hasScope`),+ [api/_lib/account-auth.js](../../api/_lib/account-auth.js) (`resolveAccount`),+ [api/_lib/admin.js](../../api/_lib/admin.js) (`requireAdmin`),+ [api/_lib/csrf.js](../../api/_lib/csrf.js),+ [api/_lib/x402/access-control.js](../../api/_lib/x402/access-control.js) (`installAccessControl`).+- **CORS** — [api/_lib/http.js](../../api/_lib/http.js) `cors(req, res, { origins,+ methods, credentials })` + `isAllowedOrigin` (the allowlist: `APP_ORIGIN`,+ x402scan, agentic.market, `*.ibm.com`, localhost in dev). Reuse it; do not invent.+- **SSRF guards** — [api/_lib/ssrf.js](../../api/_lib/ssrf.js)+ (`validatePublicUrl`, `assertPublicHttpsUrl`, `safeFetchJson`, `pinnedAgent`),+ [api/_lib/ssrf-guard.js](../../api/_lib/ssrf-guard.js) (`assertSafePublicUrl`,+ `fetchSafePublicUrl`, `fetchSafePublicUrlPinned`),+ [api/_lib/fetch-model.js](../../api/_lib/fetch-model.js) (`fetchModel` — the SSRF pioneer).+- **Security headers** — [vercel.json](../../vercel.json) `headers` blocks (~line 202+):+ `content-security-policy`, `strict-transport-security`, `x-content-type-options`,+ `referrer-policy`, `permissions-policy`, `x-frame-options`.+- **Skill + tests** — `/security-review` skill;+ [tests/api/security-csrf-gates.test.js](../../tests/api/security-csrf-gates.test.js),+ [tests/api/x402-security-fixes.test.js](../../tests/api/x402-security-fixes.test.js),+ [tests/api/validate.test.js](../../tests/api/validate.test.js).++## Do this++1. **AuthZ audit — every state-changing endpoint authorizes the caller.** Inventory+ `api/` POST/PUT/PATCH/DELETE handlers; confirm each calls `getSessionUser` /+ `authenticateBearer` / `resolveAccount` / `requireAdmin` (or x402 `installAccessControl`+ for paid routes) AND checks ownership (the resource belongs to the caller). Flag any+ handler that mutates without an authZ gate; close the gap. Verify CSRF via+ `verifyCsrfToken`/`isSameSiteOrigin` on cookie-auth state changes.+2. **Input validation everywhere.** Every handler that reads `req.body`/query/params+ must run it through a zod schema (reuse `validate.js`, add a `.strict()` schema where+ missing) and return `validationError` on failure. `grep -rn "req.body" api/` and+ confirm each is validated, not dot-accessed raw. No unbounded strings, no unchecked+ numbers feeding limits/pagination.+3. **SSRF on every server-side fetch of a user/DB URL.** `grep -rnE "fetch\(" api/` and+ find any call whose URL comes from user input or the DB (image render, GLB fetch,+ webhook, metadata, proxy). Route it through `fetchSafePublicUrl` /+ `fetchSafePublicUrlPinned` / `safeFetchJson` — pinned variant for anything whose+ response is forwarded or executed. No raw `fetch(userUrl)` may remain.+4. **CORS allowlist, not wildcard.** Confirm `cors()` callers pass an explicit+ `origins` allowlist (or rely on `isAllowedOrigin`); flag any `origins: '*'` on a+ credentialed or state-changing route and tighten it. Public read-only APIs may stay+ `*` — document why.+5. **Security headers complete and correct.** Verify `vercel.json` sets CSP, HSTS+ (`max-age` + `includeSubDomains` + `preload`), `x-content-type-options: nosniff`,+ `referrer-policy`, `permissions-policy`, and `x-frame-options`/`frame-ancestors` for+ every served surface. Tighten CSP where `'unsafe-inline'`/`'unsafe-eval'` can be+ dropped without breaking a real page (test in browser before removing).+6. **Run the security review.** Invoke the `/security-review` skill on the working+ tree. Triage every finding to root cause and fix it — no "accepted risk" without an+ explicit, written reason. Re-run until clean.+7. **Validate live + tests.** `npm run dev`; confirm headers land (`curl -I`), CORS+ preflight behaves, an unauthorized mutation is rejected, a private-IP URL fetch is+ blocked. Run `npx vitest run tests/api/security-csrf-gates.test.js+ tests/api/x402-security-fixes.test.js tests/api/validate.test.js` and add cover for+ any newly-closed gap.+8. **Changelog if user-visible.** Security hardening that changes behavior gets a+ `data/changelog.json` entry (tag `security`); run `npm run build:pages`.++## Must-not++- Do not weaken an existing control to "make it work" — fix the caller, not the guard.+- Do not add `origins: '*'` to a credentialed/state-changing route, and do not loosen+ the SSRF IP blocklist (metadata, RFC1918, loopback, CGNAT must stay blocked).+- Do not trust client-supplied IDs/ownership — re-check ownership server-side.+- Do not dismiss a `/security-review` finding without a root-cause fix or written+ justification.+- Do not break working pages by over-tightening CSP — verify each removal in a browser.+- Do not reference any coin other than `$THREE`.++## Acceptance (all true before claiming done)++- [ ] Every state-changing `api/` endpoint authorizes the caller and verifies resource+ ownership; CSRF enforced on cookie-auth mutations — verified by audit.+- [ ] Every handler that reads body/query/params validates it via zod and returns a+ clean `validationError` on bad input; no raw unvalidated `req.body` access remains.+- [ ] Every server-side fetch of a user/DB-supplied URL goes through the SSRF guard;+ `grep` shows no raw `fetch(userUrl)`.+- [ ] CORS is allowlisted on credentialed/mutating routes; any `*` is read-only and+ justified.+- [ ] `vercel.json` sets correct CSP, HSTS, X-Content-Type-Options, Referrer-Policy,+ Permissions-Policy, and X-Frame-Options for every served surface (confirmed via+ `curl -I`).+- [ ] `/security-review` runs clean (or every finding has a root-cause fix).+- [ ] Security/CSRF/validate tests pass with cover for any closed gap; user-visible+ changes logged in `data/changelog.json` and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/08-rate-limiting-abuse.md b/prompts/billion-dollar-program/08-rate-limiting-abuse.mdnew file mode 100644index 000000000..f964a3f96--- /dev/null+++ b/prompts/billion-dollar-program/08-rate-limiting-abuse.md@@ -0,0 +1,116 @@+# 08 — Rate limiting & abuse prevention++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Every expensive path on three.ws costs real money: forge generations burn GPU/provider+credits, LLM proxies burn tokens, Solana/Helius/Birdeye reads burn shared API quota,+and x402/payout endpoints move USDC. Unlimited, those become a free attack on the+platform's wallet and a denial-of-service on every honest user. A $1B platform meters+its costly surfaces, makes payments idempotent so a replay can't double-charge, and+stops bots before they scale. This is cost control, fairness, and uptime in one.++## Mission++Ensure every expensive / paid / auth / generation endpoint is rate-limited per+user+IP via the existing `rate-limit.js` registry, payment endpoints are idempotent via+the x402 idempotency cache, and bot/abuse mitigation plus quota tiers are in place —+starting from an inventory of which endpoints currently lack limits.++## Map (trust but verify — files move)++- **Rate-limit registry (build on this — do not re-roll)** —+ [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js): the `limits` object (named+ buckets: `authIp`, `registerIp`, `pumpMetaIp`, `imgProxyIp`, `cohortsIp`, `aixbtIp`,+ `sdpIp`, `avatarPayoutDaily`, …), `clientIp(req)`, and `getLimiter(name, { limit,+ window, critical })` — `critical: true` fails CLOSED in prod (money/cost buckets),+ non-critical fails open. ~418 files already import it.+- **Limit responses** — [api/_lib/http.js](../../api/_lib/http.js): `rateLimited(res,+ result, message)`, `setRateLimitHeaders(res, result)`. Use these so 429s carry the+ standard retry headers.+- **x402 idempotency** — [api/_lib/x402/idempotency-cache.js](../../api/_lib/x402/idempotency-cache.js):+ `hashRequestPayload`, `hashPaymentProof`, `reserve`/`get`/`set`/`release`, `INFLIGHT`,+ `isInflight` (Redis-backed; refuses to boot in prod without Upstash unless+ `X402_ALLOW_MEMORY_FALLBACK=1`). Same id + different payload → 409 Conflict.+- **x402 payment plumbing** — [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js)+ (`paidEndpoint`), [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js),+ [api/_lib/x402-spending-cap.js](../../api/_lib/x402-spending-cap.js),+ [api/_lib/x402/access-control.js](../../api/_lib/x402/access-control.js).+- **Costly endpoints to verify** — [api/forge.js](../../api/forge.js) (generation ++ rigging buckets), [api/chat.js](../../api/chat.js) (LLM proxy), pump/oracle reads+ (Helius/Birdeye), [api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js) ++ payout routes, MCP dispatch in [api/_lib/mcp-dispatch.js](../../api/_lib/mcp-dispatch.js).+- **Tests** — [tests/api/http-rate-limited.test.js](../../tests/api/http-rate-limited.test.js),+ [tests/api/chat-proxy-ratelimit.test.js](../../tests/api/chat-proxy-ratelimit.test.js).++## Do this++1. **Inventory unlimited expensive endpoints.** For every handler in `api/`, classify:+ does it cost money (provider/GPU/token/RPC quota), move value (x402/payout/launch),+ gate auth (login/register/reset), or generate (forge/avatar/image/LLM)? `grep -rLn+ "rate-limit\|limits\.\|clientIp" api/` to find handlers in those classes that import+ no limiter. That list is the work queue — produce it explicitly.+2. **Add a named bucket per gap.** For each unlimited costly endpoint, add a bucket to+ the `limits` registry (descriptive name, sensible `limit`/`window`, `critical: true`+ for money/cost paths so a Redis outage fails closed) and enforce it with+ `clientIp(req)` + `rateLimited(res, rl, msg)`. Match the existing per-IP (and+ per-user where authenticated) keying convention.+3. **Per user+IP, not just IP.** Authenticated costly endpoints should key on the user+ id when present (so one user can't rotate IPs) AND fall back to IP for anonymous+ callers. Add a per-resource ceiling where one entity is the cost driver (mirror+ `avatarPayoutDaily` keyed on the wallet, not the caller).+4. **Idempotency on every payment endpoint.** Confirm each x402/paid route uses+ `idempotency-cache.js`: `reserve` before settling, `set` the response, return the+ cached body on replay, and 409 on same-id/different-payload. Any payment route+ without this can double-charge — fix it. Verify the prod no-memory-fallback boot+ check is intact.+5. **Bot / abuse mitigation.** Ensure auth + registration + generation surfaces resist+ scripted abuse: burst + sustained windows (mirror `irlPinBurst` + `irlPinHourly`),+ honeypot/timing on signup, and per-device keying where a device token exists. Confirm+ anonymous generation can't be farmed for free GPU.+6. **Quota tiers.** Wire tiered ceilings (anon < authenticated < $THREE-gated/paid) so+ value flows to holders and paying agents get headroom. Reuse existing tier/gating+ helpers (`three-tier.js`, holder/play passes) rather than inventing a parallel+ system — surface a clear, actionable message when a tier limit is hit.+7. **Test the limits.** Extend `tests/api/http-rate-limited.test.js` and the chat+ ratelimit test to cover each new bucket (burst trips, headers present, critical+ buckets fail closed, idempotency replay returns cached / 409s on mismatch). Run+ `npx vitest run tests/api/http-rate-limited.test.js tests/api/chat-proxy-ratelimit.test.js`.+8. **Verify live + changelog.** `npm run dev`; hammer a newly-limited endpoint and+ confirm a clean 429 with retry headers and helpful copy (not a raw error). Any+ user-visible change (new limit, tier) → `data/changelog.json` entry (tag+ `improvement` or `security`) + `npm run build:pages`.++## Must-not++- Do not hand-roll a counter/limiter — extend the `limits` registry in `rate-limit.js`.+- Do not mark a money/cost bucket non-critical (it would fail open on a Redis outage and+ silently uncap a paid path); do not weaken an existing `critical` bucket.+- Do not skip idempotency on a payment route, and do not enable the in-memory+ idempotency fallback in production (`X402_ALLOW_MEMORY_FALLBACK`) without explicit+ reason.+- Do not return a raw error on a limit hit — use `rateLimited()` with retry headers and+ actionable copy.+- Do not set ceilings so tight they break legitimate interactive use (size each window+ to a real workflow, like the existing buckets do).+- Do not reference any coin other than `$THREE`.++## Acceptance (all true before claiming done)++- [ ] An explicit inventory exists of expensive/paid/auth/generation endpoints; every+ one is now rate-limited via a named `limits` bucket (verified by grep — no costly+ handler lacks a limiter).+- [ ] Authenticated costly endpoints key on user+IP (plus a per-resource ceiling where a+ single entity drives cost); money/cost buckets are `critical` (fail closed).+- [ ] Every payment/x402 endpoint is idempotent via `idempotency-cache.js`: replay+ returns the cached response, same-id/different-payload returns 409; prod+ no-memory-fallback boot check intact.+- [ ] Bot/abuse mitigation (burst + sustained windows, signup protection) and tiered+ quotas (anon < auth < holder/paid) are in place with clear messaging.+- [ ] Limit hits return a clean 429 with retry headers and helpful copy in a real+ browser.+- [ ] Rate-limit + idempotency tests pass with cover for each new bucket; user-visible+ changes logged in `data/changelog.json` and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/09-accessibility-wcag.md b/prompts/billion-dollar-program/09-accessibility-wcag.mdnew file mode 100644index 000000000..d586fb7c8--- /dev/null+++ b/prompts/billion-dollar-program/09-accessibility-wcag.md@@ -0,0 +1,95 @@+# 09 — Accessibility (WCAG 2.2 AA)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++A platform that excludes keyboard, screen-reader, and low-vision users is leaving+real users — and in many markets, legal compliance — on the table. Accessibility is+also a proxy for craft: semantic structure, focus management, and contrast are the+same primitives that make UI feel polished to everyone. A $1B platform passes WCAG+2.2 AA on its core flows without anyone having to ask.++## Mission++Bring every primary surface (home, forge, marketplace, wallet, agent profiles,+create flows) to WCAG 2.2 AA: semantic HTML, ARIA on interactive elements, full+keyboard operability, visible focus, sufficient contrast, screen-reader labels, and+honored reduced-motion.++## Map (trust but verify — files move)++- **Pages** — [pages/](../../pages) (~125 `*.html`). Start with high-traffic flows:+ `home.html`, `forge.html`, `marketplace*.html`, `agent-detail.html`,+ `create-prompt.html`, `agent-wallet.html`.+- **Shared nav** — [public/nav.html](../../public/nav.html), [public/nav.js](../../public/nav.js)+ (desktop dropdowns + mobile drawer; `aria-pressed` already on the walk toggle),+ [public/nav.css](../../public/nav.css).+- **Design tokens (focus ring, contrast)** — [public/tokens.css](../../public/tokens.css)+ (`--focus-ring-color` and friends), [DESIGN-TOKENS.md](../../DESIGN-TOKENS.md).+ Focus styles already exist in [public/buttons.css](../../public/buttons.css),+ [public/home.css](../../public/home.css), and others — extend, don't fork.+- **Reduced motion** — already honored in [public/tokens.css](../../public/tokens.css),+ [public/footer.css](../../public/footer.css), [public/features-landing.css](../../public/features-landing.css);+ many `src/` animation modules are not. Search `prefers-reduced-motion`.+- **JS components** — [src/](../../src) (~810 modules). Interactive widgets that build+ DOM (modals, tabs, menus, viewers) often ship `<div onclick>` without roles/labels.++## Do this++1. **Baseline audit.** Run an axe scan against the running app (no dep needed):+ `npm run dev`, then `npx @axe-core/cli http://localhost:3000/forge+ http://localhost:3000/marketplace http://localhost:3000/ http://localhost:3000/create/prompt`.+ Record every violation by page; this is your worklist.+2. **Semantic structure.** Each page needs one `<h1>`, a logical heading order, and+ landmark regions (`<header><nav><main><footer>`). Replace generic `<div>` wrappers+ that are really headers/nav/main with the semantic element. Add a "skip to content"+ link as the first focusable element on long pages.+3. **Interactive elements.** Every clickable `<div>`/`<span>` becomes a `<button>` or+ gets `role="button"`, `tabindex="0"`, and keydown (Enter/Space) handling. Icon-only+ controls get `aria-label`. Toggles get `aria-pressed`; tabs get `role="tab"` ++ `aria-selected`; modals get `role="dialog"`, `aria-modal`, focus trap, and Esc-to-close.+4. **Keyboard operability.** Tab through each core flow with no mouse: every control+ reachable, in a sane order, no keyboard trap, dropdowns/drawers open & close via+ keyboard. The mobile drawer in `nav.js` must trap focus while open and restore it on+ close.+5. **Visible focus.** Every interactive element shows a clear focus ring using the+ existing `--focus-ring-color` token (via `:focus-visible`). No `outline: none`+ without a replacement. Audit `src/` and `public/*.css` for naked `outline: none`.+6. **Contrast.** Verify text and UI contrast against backgrounds (4.5:1 body, 3:1 large+ text / UI components) in both light and dark themes. Fix failing pairs by remapping to+ compliant tokens in `tokens.css` — never hardcode a one-off hex.+7. **Screen reader & forms.** Every input has an associated `<label>` (or `aria-label`);+ error messages are announced (`aria-describedby` / `aria-live`); decorative images get+ `alt=""`, meaningful images get real `alt`. Async status (forge progress, save+ results) uses an `aria-live` region.+8. **Reduced motion.** Wrap non-essential `src/` animations (loops, parallax, auto-play+ 3D spin) in `@media (prefers-reduced-motion: reduce)` or a JS check, degrading to a+ static/instant state.+9. **Re-audit & test.** Re-run the axe scan — zero serious/critical violations on the+ targeted pages. Run `npm test` (vitest + playwright) and add/extend a Playwright check+ asserting skip-link presence, focus visibility, and drawer focus trap on at least the+ home and forge routes. Add a changelog entry; `npm run build:pages`.++## Must-not++- Do not add ARIA that lies about state (e.g. static `aria-expanded="true"`); ARIA must+ reflect live state or be omitted.+- Do not remove focus outlines without a stronger visible replacement.+- Do not hardcode colors to "fix" contrast — remap design tokens so both themes stay correct.+- Do not regress working interactions while making them accessible; verify each in a browser.+- Do not reference any coin other than `$THREE` in any new copy or label.++## Acceptance (all true before claiming done)++- [ ] axe scan on home, forge, marketplace, agent-detail, create/prompt shows zero+ serious/critical violations.+- [ ] Every core flow is fully keyboard operable with no trap; visible focus on every control.+- [ ] One `<h1>` and correct landmarks per audited page; skip-to-content link works.+- [ ] Text/UI contrast passes 4.5:1 / 3:1 in both light and dark themes.+- [ ] Inputs are labeled; async status and errors are announced via `aria-live`.+- [ ] Reduced-motion is honored across `src/` animations on the audited pages.+- [ ] `npm test` passes; new a11y Playwright checks added; changelog updated and+ `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/10-performance-core-web-vitals.md b/prompts/billion-dollar-program/10-performance-core-web-vitals.mdnew file mode 100644index 000000000..a137031a9--- /dev/null+++ b/prompts/billion-dollar-program/10-performance-core-web-vitals.md@@ -0,0 +1,87 @@+# 10 — Performance & Core Web Vitals++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Speed is the silent conversion lever. Every 100ms of LCP and every layout shift costs+sign-ups, and Core Web Vitals directly affect search ranking — the cheapest growth+channel. This platform ships a heavy Three.js/GLB stack on top of ~125 pages; if those+assets block first paint, the front door feels slow and acquisition leaks before the+user sees the product. Fast must be the default, not a flag.++## Mission++Hit good Core Web Vitals on the primary surfaces — LCP < 2.5s, CLS < 0.1, INP < 200ms —+by lazy-loading heavy modules and 3D, enforcing image-loading attributes, code-splitting,+debouncing input handlers, and preconnecting/preloading critical origins.++## Map (trust but verify — files move)++- **Heaviest pages** — [pages/home.html](../../pages/home.html),+ [pages/forge.html](../../pages/forge.html) (both already use `preconnect`/`preload`),+ marketplace and walk landing pages. These mount Three.js.+- **3D / GLB loaders** — `src/` modules importing `GLTFLoader` / `three.module` (e.g.+ [src/avatar-picker.js](../../src/avatar-picker.js), [src/club.js](../../src/club.js),+ [src/avatar-export.js](../../src/avatar-export.js)). Grep `GLTFLoader|three.module`.+ These are the biggest bundles — they must dynamic-`import()` on demand, not at page load.+- **Dynamic import (existing pattern)** — many `src/` files already use `import(...)`+ (e.g. [src/agent-detail.js](../../src/agent-detail.js)); follow that pattern.+- **Image loading guard** — [scripts/audit-image-loading.mjs](../../scripts/audit-image-loading.mjs)+ via `npm run check:images` (strict: every JS-rendered `<img>` in `src/` needs `loading=`).+ Codemod helper: [scripts/codemod-lazy-images.mjs](../../scripts/codemod-lazy-images.mjs).+- **Build config** — [vite.config.js](../../vite.config.js) (chunking, build target),+ [public/tokens.css](../../public/tokens.css) (motion tokens for `will-change`/`transform`).+- **Audit tooling** — `npm run audit:web` ([scripts/page-audit.mjs](../../scripts/page-audit.mjs)),+ `npm run snapshot` ([scripts/page-snapshot.mjs](../../scripts/page-snapshot.mjs)).++## Do this++1. **Measure first.** `npm run dev`, then run Lighthouse on the heaviest routes:+ `npx lighthouse http://localhost:3000/ --only-categories=performance --view`+ and repeat for `/forge` and `/marketplace`. Record LCP, CLS, INP/TBT per page — this+ is your before/after baseline. Note the LCP element and the largest network requests.+2. **Lazy-load the 3D stack.** Confirm every Three.js/GLTFLoader import is behind a+ dynamic `import()` triggered by viewport/interaction (IntersectionObserver or click),+ never at module top level on a page that paints text first. Defer the canvas mount+ until after first contentful paint.+3. **Image loading.** Run `npm run check:images` — fix every offender so JS-rendered+ `<img>` carries `loading="lazy"` and `decoding="async"`. For above-the-fold LCP images+ in static HTML, use `loading="eager"` + `fetchpriority="high"` (don't lazy-load the LCP+ image). Set explicit `width`/`height` (or `aspect-ratio`) on every image to kill CLS.+4. **Eliminate layout shift.** Reserve space for async content (skeletons, fixed-aspect+ media, font-swap with `font-display: optional/swap` and preloaded fonts). Audit feeds+ and the forge result area for content that pushes layout on load.+5. **Code-split & budget.** Inspect the Vite build output (`npx vite build`) for oversized+ chunks; split route-specific and 3D code into async chunks. Set and document a bundle+ budget (e.g. initial JS < 200KB gzipped per primary route) and bring offenders under it.+6. **Debounce & schedule.** Debounce/throttle search, scroll, and resize handlers;+ move non-urgent work off the critical path (`requestIdleCallback` / `requestAnimationFrame`).+ Use `transform`/`opacity` + `will-change` for animations (never animate layout props).+7. **Network priming.** Add `preconnect`/`dns-prefetch` for real cross-origin asset hosts+ (R2, RPC, fonts) and `preload` the LCP image + critical font on the heaviest pages,+ matching the existing pattern in `home.html`/`forge.html`. Remove dead preloads.+8. **Re-measure & verify.** Re-run Lighthouse on the same routes — LCP < 2.5s, CLS < 0.1,+ INP/TBT in the good band. Run `npm run audit:web` and `npm run snapshot` and confirm no+ console errors. `npm test`. Add a changelog entry; `npm run build:pages`.++## Must-not++- Do not lazy-load the LCP image or above-the-fold hero — that regresses LCP.+- Do not eager-load the full Three.js/GLB stack on pages that paint text first.+- Do not animate layout-triggering properties (top/left/width/height) — use transforms.+- Do not introduce fake `setTimeout` loading bars; use real async + skeletons.+- Do not bypass `npm run check:images` strict mode — fix the images, don't disable the guard.++## Acceptance (all true before claiming done)++- [ ] Lighthouse on home, forge, marketplace: LCP < 2.5s, CLS < 0.1, INP/TBT in the good band.+- [ ] `npm run check:images` passes strict; every image has dimensions and correct `loading=`.+- [ ] Three.js/GLB code is dynamic-imported on demand; not in the initial route bundle.+- [ ] Documented bundle budget met; oversized chunks split; `npx vite build` clean.+- [ ] Input/scroll handlers debounced; animations use transform/opacity + `will-change`.+- [ ] `preconnect`/`preload` cover real critical origins; no dead hints; no console errors.+- [ ] `npm test`, `npm run audit:web`, `npm run snapshot` pass; changelog updated and+ `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/11-mobile-responsiveness.md b/prompts/billion-dollar-program/11-mobile-responsiveness.mdnew file mode 100644index 000000000..3d5fbdbd6--- /dev/null+++ b/prompts/billion-dollar-program/11-mobile-responsiveness.md@@ -0,0 +1,85 @@+# 11 — Mobile responsiveness (320 / 768 / 1440)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Most first touches arrive on a phone. If the home hero overflows at 320px, the forge+canvas tanks a mid-range mobile GPU, or a primary CTA sits under the keyboard, the+funnel dies before the user understands the product. A $1B platform is flawless from a+cheap Android in portrait up to a 1440px desktop — the same flows, no horizontal+scroll, no dead zones, touch targets you can actually hit.++## Mission++Make every key flow (home, forge, marketplace, wallet, agent profiles, create) correct+and comfortable at 320px, 768px, and 1440px: proper viewport meta, fluid flex/grid+layouts, ≥44px touch targets, a working mobile nav, and a 3D canvas that stays smooth on+mobile GPUs.++## Map (trust but verify — files move)++- **Pages** — [pages/](../../pages) (~125 `*.html`). Both [pages/home.html](../../pages/home.html)+ and [pages/forge.html](../../pages/forge.html) already declare `viewport` — verify all+ primary pages do.+- **Mobile nav** — [public/nav.js](../../public/nav.js) (`renderDrawer`, `initDrawer`,+ the mobile drawer + walk toggle), [public/nav.css](../../public/nav.css),+ [public/nav.html](../../public/nav.html).+- **Layout CSS** — [public/](../../public) `*.css`. Several use fixed `width: NNNpx`+ (e.g. [public/app-next.css](../../public/app-next.css), [public/auth.css](../../public/auth.css)) —+ candidates to convert to fluid flex/grid. Grep `width: *[0-9]{3,}px`.+- **Design tokens** — [public/tokens.css](../../public/tokens.css) (spacing scale, type+ ladder) so breakpoints reflow against shared tokens, not magic numbers.+- **3D on mobile** — `src/` modules mounting Three.js/GLTFLoader (grep `GLTFLoader`).+ Set device pixel ratio caps and quality fallbacks here.+- **Visual check tooling** — `npm run snapshot` ([scripts/page-snapshot.mjs](../../scripts/page-snapshot.mjs)),+ Playwright ([playwright.config.js](../../playwright.config.js)) for scripted viewports.++## Do this++1. **Drive real viewports.** `npm run dev`, open the core flows in browser devtools at+ **320×568**, **768×1024**, and **1440×900** (and one landscape phone). Walk home →+ forge → result, marketplace → detail, wallet, and a create flow at each width.+2. **Viewport meta.** Confirm every primary page has+ `<meta name="viewport" content="width=device-width, initial-scale=1">` with no+ `maximum-scale`/`user-scalable=no` (pinch-zoom must stay enabled for a11y).+3. **Kill horizontal scroll.** At 320px nothing overflows: no fixed pixel widths wider+ than the viewport, long words/URLs wrap (`overflow-wrap`), tables/grids scroll inside+ a contained region, images are `max-width: 100%`. Convert offending fixed-width blocks+ to fluid flex/grid using token spacing.+4. **Touch targets.** Every tappable control is ≥44×44px with adequate spacing so+ neighbors aren't mis-tapped. Audit nav links, icon buttons, chips, and close buttons.+5. **Mobile nav.** The drawer in `nav.js` opens/closes cleanly, the body locks scroll+ while open, the walk toggle works, and it dismisses on link tap and on backdrop tap.+ Verify it doesn't cover content or trap the user.+6. **Forms & keyboard.** On mobile, primary CTAs aren't hidden behind the on-screen+ keyboard; inputs use correct `inputmode`/`type` (email, numeric, search); focused+ fields scroll into view.+7. **3D on mobile GPUs.** In the Three.js mounts, cap `renderer.setPixelRatio` (e.g.+ `Math.min(devicePixelRatio, 2)`), provide a lighter quality path or a tap-to-load+ poster on small/low-power devices, and ensure the canvas resizes correctly on+ rotation. Confirm acceptable frame rate on a throttled mobile profile.+8. **Snapshot & verify.** Run `npm run snapshot` and review the captures across widths;+ run the Playwright suite (extend with a mobile viewport project for home + forge if+ absent). `npm test`. Add a changelog entry; `npm run build:pages`.++## Must-not++- Do not disable pinch-zoom (`user-scalable=no` / `maximum-scale=1`) — it breaks a11y.+- Do not hide core functionality on mobile; reflow it, don't remove it.+- Do not ship fixed pixel widths that overflow 320px — use fluid flex/grid + tokens.+- Do not render full-resolution 3D at uncapped DPR on mobile; cap quality and frame cost.+- Do not reference any coin other than `$THREE` in any responsive copy or fallback.++## Acceptance (all true before claiming done)++- [ ] Home, forge, marketplace, wallet, and a create flow work at 320 / 768 / 1440 with+ no horizontal scroll and no clipped content.+- [ ] Every primary page has correct, zoom-enabled viewport meta.+- [ ] All touch targets are ≥44px with safe spacing; nav drawer opens/closes/locks scroll.+- [ ] Mobile CTAs stay reachable above the keyboard; inputs use correct `inputmode`/`type`.+- [ ] 3D canvases cap DPR and run smoothly on a throttled mobile profile; resize on rotate.+- [ ] `npm run snapshot` captures look correct across widths; `npm test` passes.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/12-every-state-designed.md b/prompts/billion-dollar-program/12-every-state-designed.mdnew file mode 100644index 000000000..bc4ddb646--- /dev/null+++ b/prompts/billion-dollar-program/12-every-state-designed.md@@ -0,0 +1,86 @@+# 12 — Every state designed (loading / empty / error / overflow)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The difference between a toy and a product is what happens when there's no data, the+network fails, or a name is 80 characters long. A blank void on first load reads as+broken; an unstyled error reads as abandoned; an empty marketplace with no call to+action loses the user who would have created the first listing. A $1B platform designs+every state so the user is never confused, stuck, or staring at nothing.++## Mission++Audit every list, grid, feed, and detail view and ensure all four states are+deliberately designed: **loading** (skeletons over spinners), **empty** (actionable —+tells the user what to do next), **error** (recoverable with retry), and **overflow**+(0 / 1 / 1000 items, very long names, missing thumbnails).++## Map (trust but verify — files move)++- **Data-driven surfaces** — `src/` modules that fetch then render lists/grids/feeds.+ Grep for `fetch(`, `innerHTML =`, `.map(`, `appendChild` in `src/` to find render+ paths. High-value targets: marketplace, agent profiles/feed, forge gallery/results,+ wallet/transactions, launches feed, changelog, notifications.+- **Forge result states (gold standard reference)** — see+ [prompts/production-1b/15-forge-text-to-3d-pipeline.md](./15-forge-text-to-3d-pipeline.md):+ every phase labeled, real elapsed time, no fake `setTimeout` bars. Match that bar.+- **Shared styles for states** — [public/tokens.css](../../public/tokens.css) (spacing,+ surfaces, motion for skeleton shimmer). Reuse existing skeleton/empty-state CSS where+ present (grep `skeleton` / `empty-state` across `public/*.css`); establish a shared+ pattern where missing.+- **Pages hosting these views** — [pages/](../../pages) (marketplace, agent-detail,+ forge, wallet, launches, etc.).+- **APIs feeding them** — [api/](../../api) handlers (to reproduce error/empty responses+ for testing). Tests live in [tests/](../../tests).++## Do this++1. **Inventory.** Build a checklist of every list/grid/feed/detail view across `src/`.+ For each, record where its data comes from and which of the four states currently+ exist vs. are missing.+2. **Loading = skeletons.** Replace bare spinners and blank gaps with skeleton screens+ that match the final layout (so there's no shift when data arrives). No fake progress+ bars — drive UI off real request lifecycle.+3. **Empty = actionable.** Each empty state explains why it's empty and gives the next+ action with a working CTA (e.g. "No agents yet — create your first" → links to the+ create flow). Never a bare "No data." Design a reusable empty-state component if one+ doesn't exist.+4. **Error = recoverable.** On fetch failure, show a designed error with a plain-language+ message and a **Retry** that re-runs the request. Never leak raw stack traces, vendor+ billing/quota text, or provider URLs — keep raw detail in logs, show neutral copy.+5. **Overflow & edge counts.** Verify each view at **0**, **1**, and **~1000** items:+ pagination/virtualization or "load more" for large lists; sensible single-item layout;+ no jank. Truncate long names with ellipsis + full value on hover/`title`; wrap long+ descriptions; provide a fallback for missing/broken thumbnails.+6. **Reproduce each state in the browser.** `npm run dev` and force every state: throttle+ to Offline for error, point at an empty account for empty, paste a long name, and load+ a large feed. Confirm each is designed and reachable — no dead states.+7. **Wire the failsafes.** Per `/CLAUDE.md`, errors are handled at boundaries (network /+ user input) with working fallbacks; internal code trusts itself. Make sure a failed+ sub-request degrades that section gracefully instead of blanking the whole page.+8. **Test & ship.** Add/extend tests asserting empty and error rendering for at least the+ marketplace and one feed (component or Playwright). `npm test`. Add a changelog entry+ for the user-visible polish; `npm run build:pages`.++## Must-not++- Do not ship a bare spinner where a skeleton matching the layout belongs.+- Do not leave a "No data" / blank empty state with no next action.+- Do not surface raw errors, stack traces, or vendor billing/quota text to users.+- Do not let one failed sub-request blank the entire page — degrade the section only.+- Do not use fake `setTimeout` loading; drive states off the real request lifecycle.+- Do not reference any coin other than `$THREE` in any state copy.++## Acceptance (all true before claiming done)++- [ ] Every list/grid/feed/detail view has designed loading, empty, error, and overflow states.+- [ ] Loading uses skeletons matching final layout; no layout shift on data arrival; no fake bars.+- [ ] Empty states are actionable with a working CTA; error states have a working Retry.+- [ ] 0 / 1 / 1000 items, long names, and missing thumbnails all render cleanly.+- [ ] No raw errors or vendor internals reach users; failures degrade per-section.+- [ ] Each state reproduced in a real browser; tests cover empty + error for key views.+- [ ] `npm test` passes; changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/13-design-system-consistency.md b/prompts/billion-dollar-program/13-design-system-consistency.mdnew file mode 100644index 000000000..6f8421afe--- /dev/null+++ b/prompts/billion-dollar-program/13-design-system-consistency.md@@ -0,0 +1,89 @@+# 13 — Design-system consistency (tokens, spacing, typography, theming)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Consistency is what makes a platform feel like one product instead of forty pages glued+together. When spacing, type, color, and interaction states come from a single+vocabulary, every new surface inherits quality for free and the brand reads as+trustworthy. Drift — a one-off hex here, a magic `13px` there, a button with no focus+state — is the visual equivalent of bugs. A $1B platform speaks one design language+everywhere, in both light and dark.++## Mission++Unify the platform on the canonical design tokens: every surface references shared+spacing, type, color, radius, and motion tokens; every interactive element has hover /+active / focus states; light and dark themes are correct everywhere; and no surface+reintroduces a parallel palette.++## Map (trust but verify — files move)++- **Canonical tokens (single source of truth)** — [public/tokens.css](../../public/tokens.css)+ (φ-based spacing scale, type ladder, surfaces, ink, stroke, radius, shadow, blur,+ motion, `--focus-ring-color`) and [DESIGN-TOKENS.md](../../DESIGN-TOKENS.md) (vocabulary+ + migration guidance). Per-surface palettes (`--mk-*`, `--pd-*`, `--ibm-*`, …) were+ **removed in B02** — do not reintroduce; a surface accent REMAPS these tokens.+- **Token loading** — imported by [public/style.css](../../public/style.css) and+ [public/nav.css](../../public/nav.css) so tokens reach full-stylesheet pages and+ nav-only/embed surfaces. New pages just link one of those.+- **Theming (no-flash boot + runtime)** — [scripts/inject-theme-boot.mjs](../../scripts/inject-theme-boot.mjs)+ (pre-paint `data-theme` apply; key `twx_theme`), [public/theme-switcher.js](../../public/theme-switcher.js)+ (toggle, persistence, cross-tab sync), the nav toggle in [public/nav.js](../../public/nav.js).+- **Per-surface stylesheets** — [public/](../../public) `*.css` (~many). These are where+ drift hides: hardcoded hex/rgba/px, ad-hoc spacing, missing `:focus-visible`. Existing+ focus styles in [public/buttons.css](../../public/buttons.css), [public/home.css](../../public/home.css),+ [public/home-polish.css](../../public/home-polish.css) — extend, don't fork.++## Do this++1. **Read the vocabulary.** Read `DESIGN-TOKENS.md` and `tokens.css` end to end so you+ use the real token names (`var(--space-md)`, `var(--surface-1)`, `var(--text-sm)`,+ `--focus-ring-color`, motion tokens). Do not invent new names where one exists.+2. **Find the drift.** Grep `public/*.css` and inline `src/`/`pages/` styles for+ hardcoded color (`#`, `rgb(`, `rgba(`, `hsl(`) and raw pixel spacing/sizing that an+ existing token already expresses. Build a list of offenders by file.+3. **Migrate to tokens.** Replace each hardcoded value with the nearest correct token+ (color → surface/ink/stroke token; spacing/size → φ scale; font sizes → type ladder;+ radii/shadows/blur/motion → their tokens). If a genuinely new primitive is needed, add+ it once to `tokens.css` and document it in `DESIGN-TOKENS.md`, then use it everywhere.+4. **Kill parallel palettes.** If any reintroduced `--mk-*`/`--pd-*`/`--ibm-*`-style+ namespace or standalone color set exists, collapse it into a thin theme layer that+ remaps the canonical tokens. One palette, not eight.+5. **Interaction states everywhere.** Every interactive element (buttons, links, chips,+ tabs, cards, inputs) has consistent **hover**, **active**, and **`:focus-visible`**+ states drawn from tokens — using the shared focus ring, not ad-hoc outlines. Audit for+ controls missing any of the three.+6. **Verify both themes.** `npm run dev`, toggle light/dark via the nav switch on home,+ forge, marketplace, wallet, and a settings/dashboard page. Confirm no unreadable+ contrast, no token that only works in one theme, and no flash on reload (theme-boot+ working). Run `node scripts/inject-theme-boot.mjs` (dry run) to confirm every real page+ carries the boot.+7. **Typography & spacing rhythm.** Confirm headings, body, and labels map to the type+ ladder and that section/card padding uses the spacing scale — fix one-off rhythm that+ breaks the φ system.+8. **Lock it & ship.** Run `npm run build:pages`, `npm run audit:web`, and `npm test`;+ re-grep to confirm the hardcoded-value count dropped (ideally to zero on touched+ files). Add a changelog entry for the visible consistency pass; `npm run build:pages`.++## Must-not++- Do not reintroduce a parallel per-surface palette — remap canonical tokens instead.+- Do not hardcode a hex/rgba/px that an existing token already expresses.+- Do not invent a new token name when one exists; only add to `tokens.css` for a genuinely+ new primitive, and document it.+- Do not ship an interactive element missing hover/active/`:focus-visible`.+- Do not break the no-flash theme boot or leave a token that fails in one theme.++## Acceptance (all true before claiming done)++- [ ] Touched surfaces reference tokens; hardcoded hex/rgba/raw-px count dropped (zero where feasible).+- [ ] No parallel palette remains; surface accents are thin remaps of canonical tokens.+- [ ] Every interactive element has consistent hover, active, and `:focus-visible` states from tokens.+- [ ] Light and dark themes are correct on home, forge, marketplace, wallet, and a dashboard page; no flash.+- [ ] Typography and spacing map to the type ladder and φ spacing scale; any new token documented in `DESIGN-TOKENS.md`.+- [ ] `npm run audit:web` and `npm test` pass.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/14-seo-structured-data.md b/prompts/billion-dollar-program/14-seo-structured-data.mdnew file mode 100644index 000000000..e8b8a0117--- /dev/null+++ b/prompts/billion-dollar-program/14-seo-structured-data.md@@ -0,0 +1,90 @@+# 14 — SEO & structured data++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Organic search and well-formed link previews are the cheapest, most durable growth+channel a platform has. Unique titles and descriptions win impressions; Open Graph and+Twitter cards turn every shared link into an ad; JSON-LD structured data earns rich+results; canonicals and a clean sitemap keep crawlers efficient. With ~125 pages, the+compounding cost of missing or duplicate metadata is enormous — and increasingly,+LLM-driven discovery reads `llms.txt`. A $1B platform is fully indexable and previews+beautifully everywhere.++## Mission++Ensure every canonical, indexable page has a unique title and meta description, correct+Open Graph + Twitter cards, valid JSON-LD, a self-referencing canonical, and that the+sitemap, robots, and llms.txt all reflect reality — leaning on the existing injection+tooling rather than hand-editing 125 files.++## Map (trust but verify — files move)++- **SEO injectors (the engine — use these)** — [scripts/inject-seo-meta.mjs](../../scripts/inject-seo-meta.mjs)+ (idempotently backfills `<title>`, description, canonical, OG/Twitter, WebPage/WebSite+ JSON-LD; never overwrites existing tags; re-points stale static OG images at+ `/api/page-og`), [scripts/inject-blog-seo.mjs](../../scripts/inject-blog-seo.mjs) (blog+ posts). Run via `npm run seo:meta`.+- **Catalog (single source of copy)** — [data/pages.json](../../data/pages.json) feeds+ the injector, sitemap, and llms.txt. Titles/descriptions live here — edit copy here, not+ in 125 HTML heads.+- **Page index build** — `npm run build:pages` ([scripts/build-page-index.mjs](../../scripts/build-page-index.mjs)),+ audited by [scripts/audit-page-index.mjs](../../scripts/audit-page-index.mjs) (`npm run audit:pages`).+- **Discovery surfaces** — [public/sitemap/index.html](../../public/sitemap/index.html)+ (human sitemap), [public/robots.txt](../../public/robots.txt),+ [public/llms.txt](../../public/llms.txt) + [public/llms-full.txt](../../public/llms-full.txt).+- **Dynamic OG cards** — `/api/page-og` (per-page social image) referenced by the injector.+- **Routing (route → file resolution)** — [vercel.json](../../vercel.json) `routes` table,+ which the injector uses to map a route to its HTML file.++## Do this++1. **Coverage scan.** `npm run seo:meta` in dry-run (read the script's flags) to see which+ pages are missing title / description / canonical / OG / Twitter / JSON-LD. Cross-check+ counts: grep `pages/*.html` for `rel="canonical"`, `og:title`, `application/ld+json` and+ compare against the indexable page count to find the gaps.+2. **Fix copy at the source.** For every indexable page, ensure `data/pages.json` has a+ **unique**, descriptive title (≤ ~60 chars) and meta description (~120–160 chars) — no+ duplicates, no boilerplate, real human language describing that page's value. This is+ where you edit copy.+3. **Inject.** Run `npm run seo:meta` (write mode) to backfill title, description,+ canonical, OG, Twitter, and WebPage/WebSite JSON-LD across pages. Confirm it filled gaps+ without clobbering hand-authored tags.+4. **Richer structured data where it earns rich results.** Beyond WebPage/WebSite, add the+ correct schema.org type to high-value templates: `BreadcrumbList` on nested pages,+ `Product`/`Offer` on marketplace listings, `Article`/`BlogPosting` on blog posts,+ `SoftwareApplication`/`Organization` where appropriate. Validate every block.+5. **Canonicals & duplicates.** Every page self-references a canonical absolute URL;+ collapse duplicate/parameterized routes onto one canonical. Ensure non-indexable surfaces+ (embeds, widgets, kiosk) are `noindex` and excluded from the sitemap.+6. **Sitemap, robots, llms.** Regenerate via `npm run build:pages` so the sitemap matches+ the live page set; verify `robots.txt` points to the sitemap and doesn't block indexable+ routes; confirm `llms.txt` / `llms-full.txt` reflect current pages and product framing.+7. **Validate previews & markup.** Validate JSON-LD (Google Rich Results / Schema.org+ validator) on a sample of each template; check OG/Twitter previews resolve (per-page+ `/api/page-og` image renders, not a single static fallback). `npm run dev` and spot-check+ `<head>` on home, forge, marketplace, a blog post, and an agent profile.+8. **Verify & ship.** Run `npm run audit:pages` (strict) and `npm test`. Add a changelog+ entry if the SEO improvements are user-visible (e.g. share-preview cards); `npm run build:pages`.++## Must-not++- Do not duplicate titles/descriptions across pages — each must be unique and descriptive.+- Do not hand-edit metadata into 125 HTML heads — edit `data/pages.json` and run the injector.+- Do not let the injector overwrite a page's existing hand-authored tags.+- Do not index embed/widget/kiosk surfaces or list them in the sitemap.+- Do not ship invalid JSON-LD; validate every block before claiming done.+- Do not reference any coin other than `$THREE` in any title, description, or structured data.++## Acceptance (all true before claiming done)++- [ ] Every indexable page has a unique, descriptive title and meta description (no duplicates).+- [ ] Every indexable page has a self-referencing canonical, OG + Twitter cards, and valid JSON-LD.+- [ ] High-value templates carry the right schema type (Product/Article/Breadcrumb/etc.), all validated.+- [ ] Per-page `/api/page-og` social images render (no single static fallback on shared links).+- [ ] Sitemap matches the live page set; robots points to it; llms.txt/llms-full.txt are current.+- [ ] Non-indexable surfaces are `noindex` and excluded from the sitemap.+- [ ] `npm run audit:pages` (strict) and `npm test` pass; changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/15-forge-text-to-3d-pipeline.md b/prompts/billion-dollar-program/15-forge-text-to-3d-pipeline.mdnew file mode 100644index 000000000..bab6447fe--- /dev/null+++ b/prompts/billion-dollar-program/15-forge-text-to-3d-pipeline.md@@ -0,0 +1,86 @@+# 15 — Forge / Text→3D / Avatar generation pipeline (production-grade, end-to-end)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The Forge is the platform's front door: "describe it → get a 3D thing" is the demo+that makes people screenshot and share. If text→3D, selfie→avatar, or prompt→avatar+ever shows a spinner that never resolves, a raw vendor error, or a T-posed mesh, the+core promise breaks and acquisition dies at the first touch. This surface must feel+instant, never dead-end, and never leak provider internals.++## Mission++Make every generation path — text→3D object, text→avatar, selfie→avatar, image→3D —+correct, resilient, and beautifully stated in every phase, with the **free NVIDIA NIM+lane primary** and paid lanes as silent backstops the user never sees billing for.++## Map (trust but verify — files move)++- **Forge UI** — [src/forge.js](../../src/forge.js), [pages/forge.html](../../pages/forge.html),+ [src/forge-showcase.js](../../src/forge-showcase.js), [src/home-forge.js](../../src/home-forge.js).+- **Prompt→avatar UI** — [src/create-prompt.js](../../src/create-prompt.js),+ [pages/create-prompt.html](../../pages/create-prompt.html). Selfie flow:+ `/create/selfie`.+- **Text→image (provider chain)** — [api/_mcp3d/text-to-image.js](../../api/_mcp3d/text-to-image.js).+ Free-first cascade: **NVIDIA NIM FLUX → Vertex Imagen → Replicate (paid backstop)**.+- **Reconstruct + auto-rig** — [api/avatars/_actions.js](../../api/avatars/_actions.js)+ (`handleReconstruct`), [api/_lib/reconstruct-finalize.js](../../api/_lib/reconstruct-finalize.js),+ [api/_lib/regen-provider.js](../../api/_lib/regen-provider.js), [api/_lib/auto-rig.js](../../api/_lib/auto-rig.js).+- **Backends & tiers** — [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js),+ [api/_lib/forge-health.js](../../api/_lib/forge-health.js) (`GET /api/forge?health`),+ [api/forge.js](../../api/forge.js). Model workers in [workers/](../../workers):+ `model-trellis`, `model-hunyuan3d`, `unirig`, `longcat`.+- **Tests** — [tests/api/text-to-image.test.js](../../tests/api/text-to-image.test.js),+ `tests/api/forge-free-first.test.js`, `tests/api/forge-fallback.test.js`,+ `tests/api/forge-health.test.js`, `tests/api/reconstruct-finalize.test.js`,+ `tests/forge-avatar-humanoid.test.js`.++## Do this++1. **Exercise every lane in a real browser** (`npm run dev`): text→3D object, prompt→avatar,+ selfie→avatar. Watch the Network tab and console. Confirm the free NIM lane serves+ first (`/api/forge?health` shows `nvidia: ok`).+2. **No provider internals ever reach the user.** Audit every error path in the chain+ above: billing/credit/quota messages, raw stack traces, and vendor URLs must be+ masked to neutral, actionable copy. Keep raw detail in server logs only.+3. **Every phase is designed:** reference-image render, reconstruct, rig — each with a+ live label, real elapsed time, and a skeleton/progress affordance (not a fake+ `setTimeout` bar). Empty state tells the user what to type; error state says what+ to do next.+4. **Resilience:** a hung or throttled free lane must hand off to the next lane within+ a tight timeout, never stall the pipeline. Verify the cascade with the existing+ fallback tests; add cover for any uncovered failure mode (timeout, 402, 429, NSFW,+ no-face, OOM).+5. **Right page for the input:** plain objects belong on Text→3D; humanoid prompts on+ the avatar flow. Make the routing/affordances obvious so users don't land a "box"+ on the face pipeline.+6. **Rig quality:** confirm generated humanoids drive the canonical clip library (no+ T-pose fallback unless genuinely non-humanoid, per the `/CLAUDE.md` avatar rule).+7. **Result handling:** every finished model has a working viewer, a real thumbnail+ (not a 1px snapshot), correct "rigged/static" tagging, and natural next steps+ (open in editor, make another, launch, walk).+8. Run `npx vitest run tests/api/text-to-image.test.js tests/api/forge-*.test.js+ tests/api/reconstruct-finalize.test.js` and the avatar humanoid test. Add a+ changelog entry for any user-visible change; `npm run build:pages`.++## Must-not++- Do not surface any third party's billing page, credit balance, or raw error to a buyer.+- Do not add a hardcoded rig allowlist — extend `glb-canonicalize.js` bone maps instead.+- Do not ship a fake progress bar or a spinner with no timeout.+- Do not reference any coin other than `$THREE`.++## Acceptance (all true before claiming done)++- [ ] Text→3D, prompt→avatar, and selfie→avatar all complete successfully in a real+ browser with the free NIM lane primary; no console errors/warnings.+- [ ] Every failure mode (402/429/timeout/NSFW/no-face/OOM/unconfigured) yields a+ neutral, actionable message — no vendor internals, verified by tests.+- [ ] Loading/empty/error/done states are all designed; elapsed time is real.+- [ ] Generated humanoids are rigged and animate (no unjustified T-pose); thumbnails render.+- [ ] All forge/text-to-image/reconstruct tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/16-marketplace.md b/prompts/billion-dollar-program/16-marketplace.mdnew file mode 100644index 000000000..5391472e5--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/17-agent-profiles-studio-economy.md b/prompts/billion-dollar-program/17-agent-profiles-studio-economy.mdnew file mode 100644index 000000000..a3f8858b6--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/18-wallet-x402-payments.md b/prompts/billion-dollar-program/18-wallet-x402-payments.mdnew file mode 100644index 000000000..033f8978d--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/19-walk-page-agent-tour.md b/prompts/billion-dollar-program/19-walk-page-agent-tour.mdnew file mode 100644index 000000000..0efe0b969--- /dev/null+++ b/prompts/billion-dollar-program/19-walk-page-agent-tour.md@@ -0,0 +1,133 @@+# 19 — Walk companion, Page-Agent & Feature Tour++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++These three surfaces are how three.ws makes a 3D agent *show up* on any page — the+corner mascot that strolls a site, the drop-in narrator that explains a product, and+the guided tour that walks a first-time visitor through the platform. They are the+embeddable, shareable, screenshot-worthy front of the funnel and the reason a+developer installs `@three-ws/walk` or `@three-ws/page-agent` instead of building+their own. If the companion janks, the narrator picks a T-posed avatar, or the tour+dead-ends, the "living 3D web" promise dies on first contact and so does virality.++## Mission++Take the Walk companion (mascot + full-page playground + diverse avatar picker), the+`<page-agent>` narrator, and the 3D Feature Tour to end-to-end production polish:+every state designed, every avatar rigged and animating, smooth at 60fps, and never a+broken hand-off between modes.++## Map (trust but verify — files move)++- **Walk SDK (`@three-ws/walk`)** — [walk-sdk/src/index.js](../../walk-sdk/src/index.js)+ (public API), [walk-sdk/src/companion.js](../../walk-sdk/src/companion.js) (corner+ mascot), [walk-sdk/src/playground.js](../../walk-sdk/src/playground.js) (full-page+ stroll/platformer), [walk-sdk/src/picker.js](../../walk-sdk/src/picker.js) ++ [walk-sdk/src/roster.js](../../walk-sdk/src/roster.js) (diverse avatar picker ++ `WALK_AVATARS`), [walk-sdk/src/config.js](../../walk-sdk/src/config.js),+ [walk-sdk/package.json](../../walk-sdk/package.json), [walk-sdk/README.md](../../walk-sdk/README.md).+- **Walk app entries** — [src/walk-companion.js](../../src/walk-companion.js) (on-demand+ platform inject), [src/walk-playground.js](../../src/walk-playground.js). Pages:+ [pages/walk-landing.html](../../pages/walk-landing.html) (`/walk`),+ [pages/walk-embed.html](../../pages/walk-embed.html) (`/walk-embed` code generator),+ [pages/walk-leaderboard.html](../../pages/walk-leaderboard.html),+ [pages/walk-analytics.html](../../pages/walk-analytics.html).+- **Page-Agent SDK (`@three-ws/page-agent`)** — [page-agent-sdk/src/index.js](../../page-agent-sdk/src/index.js)+ (public API), [page-agent-sdk/src/element.js](../../page-agent-sdk/src/element.js)+ (`<page-agent>` custom element), [page-agent-sdk/src/page-agent.js](../../page-agent-sdk/src/page-agent.js)+ (controller), [page-agent-sdk/src/catalog.js](../../page-agent-sdk/src/catalog.js)+ (**rigged-only** catalog), [page-agent-sdk/src/picker.js](../../page-agent-sdk/src/picker.js),+ [page-agent-sdk/src/narrator.js](../../page-agent-sdk/src/narrator.js),+ [page-agent-sdk/src/lipsync.js](../../page-agent-sdk/src/lipsync.js),+ [page-agent-sdk/src/stage.js](../../page-agent-sdk/src/stage.js). Demos:+ [page-agent-sdk/examples/](../../page-agent-sdk/examples). Publish:+ [page-agent-sdk/PUBLISHING.md](../../page-agent-sdk/PUBLISHING.md).+- **Feature Tour** — [src/feature-tour/index.js](../../src/feature-tour/index.js)+ (`createFeatureTour`, `?tour=start` bootstrap), [src/feature-tour/director.js](../../src/feature-tour/director.js)+ (curriculum stepping/spotlight/pointing), [src/feature-tour/controls.js](../../src/feature-tour/controls.js)+ (playback bar), [src/feature-tour/free-roam.js](../../src/feature-tour/free-roam.js)+ (hand-off to click-to-walk), [src/feature-tour/guide-avatar.js](../../src/feature-tour/guide-avatar.js)+ (guide character), [src/feature-tour/narrator.js](../../src/feature-tour/narrator.js),+ [src/feature-tour/chapters.js](../../src/feature-tour/chapters.js),+ [src/feature-tour/curriculum.js](../../src/feature-tour/curriculum.js),+ [src/feature-tour/spotlight.js](../../src/feature-tour/spotlight.js). App entry:+ [src/feature-tour.js](../../src/feature-tour.js). Page: [pages/tour.html](../../pages/tour.html) (`/tour`).+- **Universal rig pipeline (do not bypass)** — [src/glb-canonicalize.js](../../src/glb-canonicalize.js),+ [src/animation-retarget.js](../../src/animation-retarget.js), gate in+ [src/animation-manager.js](../../src/animation-manager.js) (`supportsCanonicalClips()`).+- **Tests** — [tests/walk-gestures.test.js](../../tests/walk-gestures.test.js),+ [page-agent-sdk/test/catalog.test.js](../../page-agent-sdk/test/catalog.test.js),+ [tests/feature-tour-curriculum.test.js](../../tests/feature-tour-curriculum.test.js).++## Do this++1. **Exercise all three in a real browser** (`npm run dev`, port 3000): load `/walk`,+ click the corner companion to detach into the full-page playground, open the avatar+ picker; load a page with `<page-agent>` (use `page-agent-sdk/examples/index.html`)+ and let it narrate; launch the Feature Tour via `?tour=start` and run it to free-roam+ hand-off. Watch the console and Network tab the whole time — zero errors/warnings.+2. **Every avatar is rigged and animates.** Confirm the Walk roster and the Page-Agent+ catalog only surface rigged GLBs that drive the canonical clip library (idle/walk+ legs included), never a bind-pose T-pose. If a humanoid won't animate, it's a+ bone-name gap — extend [src/glb-canonicalize.js](../../src/glb-canonicalize.js) and+ add a case in `tests/glb-canonicalize.test.js`. Do not hardcode a rig allowlist.+3. **Avatar picker diversity.** Audit `WALK_AVATARS` (roster.js) and the page-agent+ catalog for a genuinely diverse set (skin tones, body types, styles, presentation) —+ not five variants of one model. Make the picker keyboard-navigable, focus-trapped,+ with hover/active/focus states and a designed empty/loading state if a GLB fails.+4. **Every state designed for each surface:** companion loading (skeleton, not a dead+ sprite), playground empty/first-run hint, picker loading/error, narrator+ caption-while-speaking + muted state, tour loading/paused/finished/exit-confirm.+ No fake `setTimeout` progress bars — real asset-load progress only.+5. **Mode hand-offs never break.** Companion → playground detach, playground → page+ navigation persistence ([src/walk-companion.js] transitions), Tour director →+ `free-roam.js` click-to-walk and back. Verify each transition leaves no orphaned+ canvas, listener, or animation loop (check for leaked `requestAnimationFrame`).+6. **Performance.** Lazy-load three.js and avatar GLBs; cap the playground/companion+ frame budget; pause render loops when the tab is hidden or the element is offscreen+ (IntersectionObserver). Confirm no layout thrash and a smooth 60fps on a mid-range+ device profile (DevTools Performance trace).+7. **Embed integrity.** The `/walk-embed` code generator and the `<page-agent>` script+ tag must produce working, copy-pasteable snippets that load from the published+ package paths — exercise the generated snippet in a blank HTML file.+8. **Accessibility & resilience.** ARIA labels on companion/picker/tour controls,+ `prefers-reduced-motion` respected (reduce idle sway, no auto-walk), and a missing+ avatar/manifest falls back gracefully (next roster entry) instead of a blank canvas.+9. **Run the tests:** `npx vitest run tests/walk-gestures.test.js+ tests/feature-tour-curriculum.test.js page-agent-sdk/test/catalog.test.js`. Add+ cover for any failure mode you fixed (GLB load failure, picker empty, tour exit).+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` bone maps for any new+ skeleton instead, and never ship a T-posed humanoid.+- Do not break the existing companion/playground/tour code paths while polishing — add+ to unprotected paths, don't refactor working logic for its own sake.+- Do not ship a fake progress bar, a render loop that runs while the tab is hidden, or+ a picker that lists unrigged/missing avatars.+- Do not leave a broken mode hand-off, orphaned canvas, or leaked animation loop.+- Do not reference any coin other than `$THREE` in copy, narration, or sample data.++## Acceptance (all true before claiming done)++- [ ] `/walk` companion, full-page playground, and avatar picker all work in a real+ browser with no console errors/warnings; detach + page-navigation persistence work.+- [ ] `<page-agent>` mounts from the example, narrates with live captions and a muted+ state, and offers a rigged-only, diverse, keyboard-navigable picker.+- [ ] Feature Tour runs end-to-end (`?tour=start` → chapters → free-roam hand-off →+ exit), with loading/paused/finished/exit-confirm states designed.+- [ ] Every surfaced avatar is rigged and animates (no unjustified T-pose); any new+ skeleton convention added to `glb-canonicalize.js` with a test case.+- [ ] Loading/empty/error states designed across all three; no fake progress bars;+ render loops pause when hidden/offscreen; 60fps on a mid-range profile.+- [ ] The `/walk-embed` snippet and the `<page-agent>` script tag work pasted into a+ blank page.+- [ ] `prefers-reduced-motion` and ARIA/keyboard support verified.+- [ ] Listed tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/20-scene-animation-studio.md b/prompts/billion-dollar-program/20-scene-animation-studio.mdnew file mode 100644index 000000000..9a1b6ba82--- /dev/null+++ b/prompts/billion-dollar-program/20-scene-animation-studio.md@@ -0,0 +1,124 @@+# 20 — Scene Studio & Animation Studio++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Creators don't just want an avatar — they want to *stage* it and *make it move*. Scene+Studio (import GLBs, compose a scene, edit materials/lights, export) and Animation+Studio (pose with IK, keyframe a timeline, export an animated GLB you can sell) are+the surfaces that turn three.ws from a generator into a creation tool — the moment a+user makes something they own and can list for USDC. A pro-grade editor that imports+cleanly, never loses work, and exports a sellable artifact is what makes three.ws a+platform creators return to, not a one-shot toy.++## Mission++Make Scene Studio and Animation Studio production-grade: clean GLB import, real+material/light editing, IK posing and a keyframe timeline that exports a valid+animated GLB, every state designed, and a working path from "animate" to "list for+sale" — all on the universal canonical-rig pipeline.++## Map (trust but verify — files move)++- **Scene Studio (`/scene`)** — [pages/scene.html](../../pages/scene.html) (host page),+ [src/scene-studio/main.js](../../src/scene-studio/main.js) (entry, mounts the editor),+ [src/scene-studio/studio.css](../../src/scene-studio/studio.css) (chrome).+ Vendored three.js r184 editor under [src/scene-studio/vendor/](../../src/scene-studio/vendor)+ — read [src/scene-studio/vendor/README.md](../../src/scene-studio/vendor/README.md)+ for the re-vendoring rules and local mods. Static decoder/lib assets ship under+ `public/scene-studio/` (draco, basis, libs, fonts, images).+- **Animation Studio (`/pose`)** — [pages/pose.html](../../pages/pose.html) (host),+ [src/pose-studio.js](../../src/pose-studio.js) (controller: FK gizmos, IK drag,+ timeline, export UI), [src/pose-animation.js](../../src/pose-animation.js) (keyframe+ document + interpolation, bakes `THREE.AnimationClip`), [src/pose-rig.js](../../src/pose-rig.js)+ (rig abstraction + `solveIK()` / `IK_CHAINS`), [src/pose-presets.js](../../src/pose-presets.js).+- **Animation data** — [public/animations/manifest.json](../../public/animations/manifest.json)+ (clip index), [public/animations/clips/](../../public/animations/clips) (retargeted+ JSON clips). Build pipeline: [scripts/build-animations.mjs](../../scripts/build-animations.mjs)+ (Mixamo FBX → retarget → canonical clips), [scripts/fbx-to-glb.mjs](../../scripts/fbx-to-glb.mjs).+- **Animation gallery + selling** — [pages/animations.html](../../pages/animations.html),+ [src/animations-gallery.js](../../src/animations-gallery.js),+ [api/animations/sell.js](../../api/animations/sell.js) (list/delist for sale),+ [api/animations/clips.js](../../api/animations/clips.js) (save/list clips),+ [api/animations/presign.js](../../api/animations/presign.js) (R2 upload),+ [api/x402/animation-download.js](../../api/x402/animation-download.js) (paid download).+- **Universal rig pipeline (the spine of both)** — [src/glb-canonicalize.js](../../src/glb-canonicalize.js)+ (bone-name + up-axis normalization on import), [src/animation-retarget.js](../../src/animation-retarget.js)+ (rebind canonical clips onto any rig).+- **Tests** — [tests/pose-animation.test.js](../../tests/pose-animation.test.js),+ [tests/animation-upright-invariant.test.js](../../tests/animation-upright-invariant.test.js),+ [tests/glb-canonicalize.test.js](../../tests/glb-canonicalize.test.js),+ [tests/animation-retarget.test.js](../../tests/animation-retarget.test.js).++## Do this++1. **Exercise Scene Studio in a real browser** (`npm run dev`): open `/scene`, import a+ GLB (Add → Model), select a mesh, edit a material (color/metalness/roughness) and a+ light, then export the scene as GLB. Re-import the exported file to prove it round-trips+ (meshes, materials, lights survive). Watch console/Network — zero errors/warnings.+2. **Exercise Animation Studio in a real browser:** open `/pose`, load the built-in+ mannequin and a user avatar GLB, pose with FK gizmos and IK drag (grab a hand/foot,+ confirm the chain solves), add timeline keyframes, scrub, then export an animated+ GLB. Re-open the exported GLB in the viewer to confirm it plays.+3. **Import is bulletproof.** Every imported GLB runs through+ [src/glb-canonicalize.js](../../src/glb-canonicalize.js) so arbitrary skeletons+ (Mixamo/Avaturn/VRM/Daz/Blender, etc.) normalize to the canonical set. A humanoid+ that won't pose/retarget is a bone-name gap — extend `glb-canonicalize.js` and add a+ `tests/glb-canonicalize.test.js` case. Never hardcode a rig allowlist; a genuinely+ non-humanoid prop falls back gracefully, not to a broken editor.+4. **Every state designed** for both studios: loading (skeleton/progress on GLB load,+ real bytes not a fake bar), empty (no model yet → "import a GLB to start" with a+ sample), error (bad/corrupt file → actionable message, not a stack trace), and+ overflow (large scene/long timeline stays responsive). Mask any vendor/decoder error.+5. **No lost work.** Confirm the timeline and scene state survive a tab refresh+ (autosave/local persistence) or, if not present, add it. Warn on unload with unsaved+ changes. Undo/redo must work for pose + scene edits.+6. **Export quality.** The exported animated GLB must have a valid `AnimationClip` with+ canonical bone tracks, play upright (no flipped/tilted root — see+ `animation-upright-invariant.test.js`), and carry a real name. The scene export must+ be self-contained (embedded textures/materials/lights).+7. **"Animate → sell" path works end-to-end.** From Animation Studio, save the clip+ ([api/animations/clips.js]), presign + upload the artifact ([api/animations/presign.js]),+ list it for sale ([api/animations/sell.js]) with a USDC price, and confirm it shows+ in the gallery ([pages/animations.html]) with a working preview and an x402 paid+ download ([api/x402/animation-download.js]). No mocks — real R2 + real listing.+8. **Performance & accessibility.** Lazy-load heavy editor modules and decoders; pause+ the render loop when the tab is hidden; keyboard shortcuts for play/pause/keyframe;+ ARIA on timeline controls; `prefers-reduced-motion` respected in previews.+9. **Run the tests:** `npx vitest run tests/pose-animation.test.js+ tests/animation-upright-invariant.test.js tests/glb-canonicalize.test.js+ tests/animation-retarget.test.js`. Cover any failure mode you fixed (bad-GLB import,+ export of an unrigged mesh, IK chain with a missing bone).+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` for new skeletons so+ IK/posing/export work on any humanoid.+- Do not edit the vendored three.js editor upstream files without recording the change+ per `src/scene-studio/vendor/README.md` (the re-vendor must stay reproducible).+- Do not ship a fake progress bar, an export that produces an invalid/upright-flipped+ GLB, or a "sell" flow backed by mocks.+- Do not let a corrupt import or decoder failure surface a raw stack trace or vendor URL.+- Do not reference any coin other than `$THREE` (prices/payments are USDC; never name+ another token).++## Acceptance (all true before claiming done)++- [ ] Scene Studio imports a GLB, edits a material + light, exports a self-contained+ scene GLB that round-trips on re-import — no console errors/warnings.+- [ ] Animation Studio poses with FK + IK, keyframes a timeline, and exports a valid+ animated GLB that plays upright in the viewer.+- [ ] Arbitrary skeletons normalize via `glb-canonicalize.js`; any new convention added+ with a test case; no rig allowlist, no unjustified T-pose.+- [ ] Loading/empty/error/overflow states designed in both studios; vendor/decoder+ errors masked; no fake progress bars.+- [ ] Unsaved-work protection (autosave or unload warning) and undo/redo work.+- [ ] "Animate → save → upload → list for sale → gallery → x402 download" works+ end-to-end with real R2 and real listings.+- [ ] Listed tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/21-avatar-creator-character-studio.md b/prompts/billion-dollar-program/21-avatar-creator-character-studio.mdnew file mode 100644index 000000000..f5f815e73--- /dev/null+++ b/prompts/billion-dollar-program/21-avatar-creator-character-studio.md@@ -0,0 +1,130 @@+# 21 — Avatar creator / Character Studio / Selfie→avatar++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++"Make *me* a 3D avatar" is the most personal thing a user does on three.ws — sculpt a+character from scratch, turn a selfie into a rigged avatar, or describe one in words —+and it's the asset they carry into Walk, Worlds, the marketplace, and their agent+profile. If the creator is clumsy, the selfie pipeline dead-ends, or the result lands+as a frozen T-pose, the user never gets to the "wow, that's me, and it moves"+screenshot that drives sharing. This surface must feel like a real character creator+and always produce a rigged avatar that animates.++## Mission++Make the three avatar-creation paths — Character Studio (sculpt face+body), selfie→avatar,+and prompt→avatar — correct, resilient, and beautifully stated, each producing a+canonical-rigged GLB the user can export and publish to the gallery, all on the+universal rig pipeline (no allowlist).++## Map (trust but verify — files move)++- **Character Studio (full builder)** — [character-studio/](../../character-studio)+ (React/Vite app, MIT fork of m3-org/CharacterStudio — see+ [character-studio/LICENSE](../../character-studio/LICENSE)).+ [character-studio/package.json](../../character-studio/package.json) (`@m3-org/characterstudio`,+ builds to `/avatar-studio/` base), [character-studio/index.html](../../character-studio/index.html).+ Sculpting/body engine under `character-studio/src/library/` (e.g.+ `characterManager.js`, `VRMExporter*.js`). Wrapper page that iframes the studio:+ [pages/avatar-studio.html](../../pages/avatar-studio.html). Routes: `/avatar-studio`,+ `/create/studio` → `avatar-studio.html` (see [vercel.json](../../vercel.json)).+- **Avatar SDK (`@three-ws/avatar`)** — [avatar-sdk/package.json](../../avatar-sdk/package.json)+ (web component `<agent-3d>`; `./creator`, `./viewer`, `./react` subpaths),+ [avatar-sdk/src/creator.js](../../avatar-sdk/src/creator.js) (modal iframe controller ++ presigned upload), [avatar-sdk/src/viewer.js](../../avatar-sdk/src/viewer.js),+ [avatar-sdk/README.md](../../avatar-sdk/README.md).+- **Selfie→avatar / prompt→avatar (UI)** — [pages/create-selfie.html](../../pages/create-selfie.html)+ (`/create/selfie`), [src/selfie-pipeline.js](../../src/selfie-pipeline.js),+ [src/selfie-capture.js](../../src/selfie-capture.js); [pages/create-prompt.html](../../pages/create-prompt.html)+ (`/create/prompt`), [src/create-prompt.js](../../src/create-prompt.js).+- **Reconstruct + auto-rig (backend)** — [api/avatars/_actions.js](../../api/avatars/_actions.js)+ (`reconstruct`, `upload`, `upload-proxy`), [api/avatars/index.js](../../api/avatars/index.js)+ (list/create metadata), [api/avatars/from-forge.js](../../api/avatars/from-forge.js),+ [api/_lib/reconstruct-finalize.js](../../api/_lib/reconstruct-finalize.js) (shared+ tail: canonicalize → rig gate → materialize), [api/_lib/auto-rig.js](../../api/_lib/auto-rig.js),+ [api/_lib/regen-provider.js](../../api/_lib/regen-provider.js).+- **Gallery (publish target)** — [public/gallery/index.html](../../public/gallery/index.html),+ [public/gallery/gallery.js](../../public/gallery/gallery.js),+ [pages/gallery-picker.html](../../pages/gallery-picker.html).+- **Universal rig pipeline (must respect)** — [src/glb-canonicalize.js](../../src/glb-canonicalize.js)+ (bone-name + up-axis normalize at ingest), [src/animation-retarget.js](../../src/animation-retarget.js),+ gate in [src/animation-manager.js](../../src/animation-manager.js)+ (`supportsCanonicalClips()`).+- **Tests** — [tests/api/reconstruct-finalize.test.js](../../tests/api/reconstruct-finalize.test.js),+ [tests/api/avatars-from-forge.test.js](../../tests/api/avatars-from-forge.test.js),+ [tests/glb-canonicalize.test.js](../../tests/glb-canonicalize.test.js).++## Do this++1. **Exercise all three creation paths in a real browser** (`npm run dev`): Character+ Studio at `/avatar-studio` (sculpt a face, adjust body, change an outfit, export+ GLB); `/create/selfie` (capture/upload a photo → rigged avatar); `/create/prompt`+ (describe an avatar → rigged avatar). Watch console/Network — zero errors/warnings.+2. **Every result is canonical-rigged and animates.** Confirm `reconstruct-finalize.js`+ canonicalizes every GLB and the auto-rig gate ([api/_lib/auto-rig.js]) produces a+ skeleton that drives idle/walk (legs included). A humanoid that lands T-posed is a+ bug — fix the bone map in `glb-canonicalize.js` (+ a `tests/glb-canonicalize.test.js`+ case), never hardcode a rig allowlist. Only a genuinely non-humanoid mesh may fall+ back to the default rig via `supportsCanonicalClips()`.+3. **No provider internals reach the user.** Audit every error path in+ [api/avatars/_actions.js], [api/_lib/reconstruct-finalize.js],+ [api/_lib/regen-provider.js], and the selfie/prompt UIs: provider quota/billing,+ raw stack traces, vendor URLs, NSFW/no-face/OOM responses must become neutral,+ actionable copy. Keep raw detail in server logs only.+4. **Every phase is designed.** Selfie capture (camera permission prompt, face-not-found+ hint, retake), reconstruct, and rig each show a live label + real elapsed time ++ progress affordance (not a fake `setTimeout` bar). Empty state tells the user what to+ do; error state says how to recover; Character Studio loading uses a skeleton, not a+ blank canvas.+5. **Resilience.** A hung/throttled provider must time out and either retry or hand off+ (reuse the existing `regen-provider` chain / cockatiel helper), never stall a spinner+ forever. Verify the cascade and add cover for uncovered failure modes (402/429/+ timeout/NSFW/no-face/OOM/unconfigured).+6. **Export + publish path works end-to-end.** From any creation path, export the GLB+ and publish it to the gallery: confirm the avatar appears in+ [public/gallery/index.html](../../public/gallery/index.html) with the correct+ `visibility`, a real thumbnail (not a 1px snapshot), correct rigged/static tagging,+ and an owner-scoped storage key (you can't claim someone else's GLB).+7. **Right input → right path.** Make affordances obvious so a "humanoid" prompt goes+ to the avatar flow (not a box on a non-humanoid pipeline), and the selfie flow guides+ the user to a clear, face-forward photo.+8. **Accessibility, mobile, performance.** Camera/selfie flow works on mobile (320px),+ ARIA on creator controls and the picker, keyboard navigation, lazy-load the heavy+ `<agent-3d>` runtime and Character Studio bundle, and respect `prefers-reduced-motion`+ in previews. Confirm Character Studio's iframe wrapper sizing is responsive.+9. **Run the tests:** `npx vitest run tests/api/reconstruct-finalize.test.js+ tests/api/avatars-from-forge.test.js tests/glb-canonicalize.test.js`. Add cover for+ any failure mode or new bone mapping you fixed.+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` bone maps so every+ humanoid animates; never ship a bind-pose T-pose for a riggable humanoid.+- Do not surface any provider's billing page, credit balance, quota, or raw error to the+ user — mask to neutral, actionable copy.+- Do not ship a fake progress bar, a spinner with no timeout, or a "publish" backed by+ mocks/sample arrays.+- Do not let a user claim or overwrite another user's avatar/storage key.+- Do not reference any coin other than `$THREE` in copy, metadata, or sample data.++## Acceptance (all true before claiming done)++- [ ] Character Studio (sculpt), selfie→avatar, and prompt→avatar all complete in a real+ browser with no console errors/warnings; each exports a GLB.+- [ ] Every produced humanoid is canonical-rigged and animates (no unjustified T-pose);+ any new skeleton convention added to `glb-canonicalize.js` with a test case.+- [ ] Every failure mode (402/429/timeout/NSFW/no-face/OOM/unconfigured) yields a+ neutral, actionable message — no vendor internals, verified by tests.+- [ ] Loading/empty/error states designed for all three paths; elapsed time is real; no+ fake progress bars.+- [ ] Export → publish-to-gallery works with a real thumbnail, correct visibility ++ rigged/static tag, and owner-scoped storage.+- [ ] Mobile (320px) selfie flow, ARIA/keyboard support, and lazy-loading verified.+- [ ] Listed tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/22-pump-oracle-trading-three.md b/prompts/billion-dollar-program/22-pump-oracle-trading-three.mdnew file mode 100644index 000000000..ce6790af1--- /dev/null+++ b/prompts/billion-dollar-program/22-pump-oracle-trading-three.md@@ -0,0 +1,145 @@+# 22 — Pump.fun launch, Oracle, trading & $THREE++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The token surfaces are where three.ws meets real money and real on-chain stakes:+launch-a-coin, the Launchpad Studio, Coin Intelligence/Radar, the Oracle conviction+engine, the Trader Leaderboard, Smart Money, Arm-your-agent, the Strategy Lab, and the+`$THREE` token page. These pages must show real Solana data, never stall on a flaky+RPC, never leak a provider error — and they must be **flawless on $THREE-only+compliance**, because a single stray ticker in code, copy, or sample data is a+credibility (and legal) failure for the platform's own token.++## Mission++Harden every pump/oracle/trading surface to production: real-data feeds with resilient+RPC, every state designed, no leaked provider internals — and run a strict $THREE-only+compliance audit that confirms the only coin promoted anywhere is `$THREE`+(CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).++## Map (trust but verify — files move)++- **Launch-a-coin** — [pages/launch.html](../../pages/launch.html) (`/launch`),+ [src/pump/launch-token-modal.js](../../src/pump/launch-token-modal.js) (launcher modal).+ Pump backend dispatch: [api/pump/[action].js](../../api/pump/%5Baction%5D.js)+ (`launches`, `snapshot`, etc.), [api/pump/safety.js](../../api/pump/safety.js),+ [api/pump/trending.js](../../api/pump/trending.js).+- **Launchpad Studio (page-builder + CMS)** — [pages/launchpad.html](../../pages/launchpad.html)+ (`/launchpad`), [src/editor/launchpad-studio.js](../../src/editor/launchpad-studio.js)+ (template → live preview → publish to `/p/<slug>`).+- **Platform launch directory (runtime exception — keep)** — [pages/launches.html](../../pages/launches.html)+ (`/launches`, renders coins launched through three.ws over `pump_agent_mints`),+ [pages/launch-detail.html](../../pages/launch-detail.html) (`/launches/<mint>`,+ runtime user-supplied mint).+- **Coin Intelligence / Radar** — [pages/coin-intel.html](../../pages/coin-intel.html)+ (`/coin-intel`), [pages/radar.html](../../pages/radar.html) (`/radar`),+ [src/radar.js](../../src/radar.js), [api/pump/coin-intel.js](../../api/pump/coin-intel.js).+- **Oracle (conviction)** — [pages/oracle.html](../../pages/oracle.html) (`/oracle`),+ [src/oracle.js](../../src/oracle.js), [api/oracle/feed.js](../../api/oracle/feed.js),+ [api/oracle/coin.js](../../api/oracle/coin.js), conviction engine in+ [api/_lib/oracle/conviction.js](../../api/_lib/oracle/conviction.js) (+ `narrative.js`,+ `archetype.js`, `known-wallets.js`, `settle.js` in [api/_lib/oracle/](../../api/_lib/oracle)).+- **Arm-your-agent (trading automation)** — [pages/arm.html](../../pages/arm.html)+ (`/arm`, `/oracle/arm`), [src/arm.js](../../src/arm.js) (reuses `/api/agents`,+ `/api/oracle/watch`, `/api/oracle/test-alert`).+- **Strategy Lab** — [public/strategy-lab.html](../../public/strategy-lab.html)+ (`/strategy-lab`). Sniper dashboard: [src/dashboard-next/pages/sniper.js](../../src/dashboard-next/pages/sniper.js).+- **Trader Leaderboard / Smart Money** — [pages/leaderboard.html](../../pages/leaderboard.html)+ (`/leaderboard`), [src/leaderboard.js](../../src/leaderboard.js),+ [api/_lib/trader-stats.js](../../api/_lib/trader-stats.js);+ [pages/smart-money.html](../../pages/smart-money.html) (`/smart-money`),+ [api/pump/smart-money.js](../../api/pump/smart-money.js).+- **$THREE token page** — [pages/three-token.html](../../pages/three-token.html)+ (`/three-token`), [src/three-token-page.js](../../src/three-token-page.js),+ [api/three-token/[action].js](../../api/three-token/%5Baction%5D.js),+ [src/pump/three-token-data.js](../../src/pump/three-token-data.js) (canonical mint),+ [api/_lib/token/config.js](../../api/_lib/token/config.js).+- **Tests** — [tests/api/granite-oracle.test.js](../../tests/api/granite-oracle.test.js),+ [tests/smart-money.test.js](../../tests/smart-money.test.js),+ [tests/api/pump-curve.test.js](../../tests/api/pump-curve.test.js).++## Do this++1. **Exercise every surface in a real browser** (`npm run dev`): `/launch`, `/launchpad`,+ `/launches` + a `/launches/<mint>` detail, `/coin-intel`, `/radar`, `/oracle`, `/arm`,+ `/strategy-lab`, `/leaderboard`, `/smart-money`, `/three-token`. Watch console/Network+ — zero errors/warnings; every page renders real Solana/pump data, not a placeholder.+2. **Run the $THREE-only compliance audit.** Grep the codebase for any non-`$THREE`+ ticker/symbol or hardcoded mint in code, comments, copy, fixtures, and sample data:+ ```+ grep -rniE '\$[A-Z]{2,6}\b' pages/ src/ api/ public/ | grep -v 'THREE'+ grep -rnoE '[1-9A-HJ-NP-Za-km-z]{32,44}' api/pump api/oracle src/pump src/kol+ ```+ Confirm every hit is one of: the `$THREE` CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`;+ a clearly-synthetic placeholder (`THREEsynthetic1111…`); a Solana utility mint (wSOL+ `So111…112`, USDC `EPjF…Dt1v`); a platform fee / wallet / EVM factory address (not a+ coin); a **runtime user-supplied** mint (launcher input, `/launches/<mint>`); or the+ **platform launch directory** over `pump_agent_mints`. Remove or fix anything that+ markets/recommends/hardcodes another coin. Treat a stray ticker like a leaked secret.+3. **No provider/RPC internals reach the user.** Audit error paths in `api/pump/*`,+ `api/oracle/*`, and `api/_lib/oracle/*`: Helius/RPC/DEX errors, rate-limit bodies,+ raw stack traces, and vendor URLs must become neutral, actionable copy. Keep raw+ detail in server logs only.+4. **Resilient on-chain reads.** Every Solana RPC / pump / Helius call must time out and+ retry/fall back via the existing cockatiel resilience helper — never stall a feed.+ Verify the trending/coin-intel/oracle feeds degrade gracefully when RPC is slow or a+ provider 429s (designed stale/partial state, not a dead spinner).+5. **Every state designed** on each surface: loading (skeleton rows, not spinners),+ empty (e.g. no launches yet, no conviction signals yet → tell the user what's next),+ error (RPC down → "data delayed, retrying" with a retry), and overflow (long lists+ paginated/virtualized; long names truncated). Designed for 0 / 1 / 1000 items.+6. **Launch + arm flows are real and safe.** Confirm `/launch` produces a real pump.fun+ launch (the launcher accepts the runtime mint/params — generic plumbing exception),+ `/launches` lists it, and `/arm` wires conviction-threshold automation through+ `/api/oracle/watch` with real agent state. No fake fills, no mock PnL on the+ leaderboard — `trader-stats.js` must compute from real on-chain history.+7. **$THREE token page integrity.** `/three-token` must read live price/holders/activity+ from real APIs, reference only the canonical mint+ (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`), and degrade gracefully if a feed is+ down. Any "buy/swap" affordance routes to a legitimate runtime-mint swap, never names+ another token.+8. **Accessibility, mobile, performance.** ARIA on tables/controls, keyboard nav,+ responsive at 320/768/1440, lazy-load charts/3D, debounce search inputs, paginate+ large feeds. No layout thrash on live-updating tables.+9. **Run the tests:** `npx vitest run tests/api/granite-oracle.test.js+ tests/smart-money.test.js tests/api/pump-curve.test.js`. Add cover for any RPC-failure+ or error-masking path you fixed; add a test asserting no non-`$THREE` ticker appears+ in shipped copy/fixtures if a gap exists.+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not mention, hardcode, link, render, or recommend any coin other than `$THREE`+ anywhere — code, comments, copy, fixtures, sample data, or commit message. The only+ two exceptions are runtime user-supplied mints (launcher input, `/launches/<mint>`)+ and the platform launch directory over `pump_agent_mints`. Never paste a real+ non-`$THREE` mint/creator/holder address into tests or fixtures.+- Do not surface a raw RPC/Helius/DEX/provider error, rate-limit body, or vendor URL to+ the user.+- Do not ship a feed with no timeout/fallback, a fake-loading bar, or mock PnL/fills.+- Do not break the working pump/oracle data paths while hardening — add to unprotected+ paths, prefer the existing cockatiel helper over hand-rolled retries.++## Acceptance (all true before claiming done)++- [ ] All token surfaces render real Solana/pump data in a real browser with no console+ errors/warnings: `/launch`, `/launchpad`, `/launches`(+detail), `/coin-intel`,+ `/radar`, `/oracle`, `/arm`, `/strategy-lab`, `/leaderboard`, `/smart-money`,+ `/three-token`.+- [ ] $THREE-only audit clean: every ticker/mint in code, copy, and fixtures is `$THREE`,+ a synthetic placeholder, a utility mint/wallet, a runtime user-supplied mint, or+ the `pump_agent_mints` launch directory. No other coin promoted anywhere.+- [ ] Every provider/RPC failure yields neutral, actionable copy — no internals leaked.+- [ ] Feeds are resilient (timeout + retry/fallback via cockatiel) and degrade gracefully+ under slow/429 RPC.+- [ ] Loading/empty/error/overflow states designed across all surfaces (0/1/1000 items).+- [ ] Launch, arm, leaderboard, and $THREE token data are real (no mock fills/PnL); the+ $THREE page references only the canonical mint.+- [ ] ARIA/keyboard, responsive 320/768/1440, and lazy-loading verified.+- [ ] Listed tests pass; new RPC-failure / compliance coverage added where there was a gap.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/23-mcp-servers-production.md b/prompts/billion-dollar-program/23-mcp-servers-production.mdnew file mode 100644index 000000000..e9d91fbb7--- /dev/null+++ b/prompts/billion-dollar-program/23-mcp-servers-production.md@@ -0,0 +1,99 @@+# 23 — MCP servers (production-ready)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++MCP is how agents — Claude, Cursor, every autonomous buyer — actually reach+three.ws. If a manifest drifts, a remote endpoint stops answering its payment+challenge, or the one free lane (`forge_free`) silently breaks, the entire+agent-to-agent distribution channel goes dark and we lose the buyers who never+touch a browser. A registry-clean, smoke-passing, correctly-priced MCP surface+is the difference between "an app" and "a protocol other agents build on."++## Mission++Make every three.ws MCP server publishable and reliable: valid registry+manifests, passing smokes, correct per-tool x402 pricing, a working free+`forge_free` lane, and spec-compliant `PaymentRequired` transport — so a fresh+agent can discover and call our tools with zero hand-holding.++## Map (trust but verify — files move)++- **Hosted 3D-Agent MCP (remote)** — [api/mcp-3d.js](../../api/mcp-3d.js), backed by+ [api/_mcp3d/catalog.js](../../api/_mcp3d/catalog.js) (tool list + discovery copy),+ [api/_mcp3d/dispatch.js](../../api/_mcp3d/dispatch.js), [api/_mcp3d/pricing.js](../../api/_mcp3d/pricing.js)+ (per-tool USDC), [api/_mcp3d/discovery.js](../../api/_mcp3d/discovery.js), and the+ tool implementations in [api/_mcp3d/tools/studio.js](../../api/_mcp3d/tools/studio.js)+ (`forge_free` lives here — the ONE free tool: NVIDIA NIM / Microsoft TRELLIS text→3D).+- **Other remote endpoints** — [api/mcp.js](../../api/mcp.js), [api/mcp-agent.js](../../api/mcp-agent.js),+ [api/mcp-bazaar.js](../../api/mcp-bazaar.js), [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js)+ (free, $THREE-only probe), [api/ibm-mcp.js](../../api/ibm-mcp.js).+- **stdio MCP packages** — [mcp-server/](../../mcp-server), [mcp-bridge/](../../mcp-bridge),+ [packages/pumpfun-mcp/](../../packages/pumpfun-mcp), [packages/avatar-agent-mcp/](../../packages/avatar-agent-mcp),+ [packages/threews-avatar-mcp/](../../packages/threews-avatar-mcp), [packages/three-token-mcp/](../../packages/three-token-mcp),+ [packages/ibm-watsonx-mcp/](../../packages/ibm-watsonx-mcp), [packages/ibm-x402-mcp/](../../packages/ibm-x402-mcp).+- **x402 spec helper** — [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) (builds the+ `PaymentRequired` / `accepts[]` challenge as `structuredContent`).+- **Manifests** — each package's `server.json` + root `server*.json` (remote manifests).+- **Tooling** — `npm run audit:mcp` ([scripts/audit-mcp-manifests.mjs](../../scripts/audit-mcp-manifests.mjs)),+ `smoke:mcp` ([scripts/smoke-mcp-remotes.mjs](../../scripts/smoke-mcp-remotes.mjs)),+ `test:mcp` ([scripts/test-mcp-all.mjs](../../scripts/test-mcp-all.mjs)),+ `publish:mcp:dry` ([scripts/publish-mcp-servers.mjs](../../scripts/publish-mcp-servers.mjs)).++## Do this++1. **Audit manifests:** run `npm run audit:mcp`. Fix every violation — description+ ≤ 100 chars, `name` in `io.github.<owner>/<server>` form, https icons/URLs, and+ for stdio packages the `server.json` version MUST equal the package's `package.json`+ version (and `packages[0].identifier/version` + `mcpName` must match). Do not bump+ a version to dodge a real mismatch — align them.+2. **Smoke the remotes:** run `npm run smoke:mcp http://localhost:3000` against+ `npm run dev`, then against `https://three.ws`. Free endpoints must answer+ `initialize` + `tools/list` and run a read-only tool; paid endpoints must return+ a well-formed 401/402 with a valid `accepts[]` challenge. Fix any unhealthy one.+3. **Verify the free lane:** call `forge_free` end-to-end (no wallet, no key) and+ confirm it returns a real GLB URL + a three.ws viewer link via the NVIDIA NIM /+ TRELLIS path. It must NEVER demand payment. Confirm it is the only free generation+ tool in `catalog.js`.+4. **Price every paid tool correctly:** in `api/_mcp3d/pricing.js`, confirm generation+ tools price by tier from `forge-tiers.js` (same numbers as `POST /api/x402/forge`),+ mesh edits carry their flat per-call USDC, and read-only tools (status/preview/+ inspection) stay free. No tool may settle for the env minimum when it costs more.+5. **Spec compliance:** confirm an un-paid call to a paid tool returns a+ `PaymentRequired` result whose `structuredContent.accepts[]` carries valid+ requirements (asset = USDC, correct `payTo`, atomic amount) — built via+ `api/_lib/x402-spec.js`, not hand-rolled. Verify on both Base and Solana rails.+6. **Run the full MCP suite:** `npm run test:mcp -- --no-remote` (offline: manifests ++ each stdio package's `node --test`), then `npm run test:mcp http://localhost:3000`+ (with the live layer). All green.+7. **Dry-run the publish:** `npm run publish:mcp:dry`. It must validate every manifest+ and report cleanly with no auth/version errors.+8. **Docs + versioning:** each stdio package README must list its tools, install/run+ command, and a real call example. Bump versions only for genuine changes (semver),+ keeping `server.json` and `package.json` in lockstep. Add a `data/changelog.json`+ entry (tag `sdk` or `infra`) for any user-visible MCP change, then `npm run build:pages`.++## Must-not++- Do not gate `forge_free` behind payment, a wallet, or an API key — it is the free lane.+- Do not hardcode any mint other than `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`)+ in probes, fixtures, or docs; the pump-fun probe must stay $THREE-only.+- Do not hand-roll the `PaymentRequired` challenge — use `api/_lib/x402-spec.js`.+- Do not let a generation tool settle for the env-minimum price; price it by tier.+- Do not commit a `server.json`/`package.json` version mismatch or a >100-char description.+- Do not weaken or skip a smoke/manifest check to make the suite pass.++## Acceptance (all true before claiming done)++- [ ] `npm run audit:mcp` passes with zero violations.+- [ ] `npm run smoke:mcp` passes against both `localhost:3000` and `https://three.ws`.+- [ ] `forge_free` returns a real GLB URL + viewer link with no payment, wallet, or key.+- [ ] Every paid tool prices correctly (generation by tier, mesh edits flat, read-only free);+ paid tools return a valid `PaymentRequired` `structuredContent.accepts[]` on Base + Solana.+- [ ] `npm run test:mcp -- --no-remote` and `npm run test:mcp http://localhost:3000` both pass.+- [ ] `npm run publish:mcp:dry` reports clean for every server.+- [ ] Every stdio package README documents tools + a real call example; versions are in lockstep.+- [ ] Changelog updated (if user-visible) and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/24-sdk-publishing-docs.md b/prompts/billion-dollar-program/24-sdk-publishing-docs.mdnew file mode 100644index 000000000..cbd0199fb--- /dev/null+++ b/prompts/billion-dollar-program/24-sdk-publishing-docs.md@@ -0,0 +1,93 @@+# 24 — SDK publishing & docs++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The SDKs are how other teams build *on* three.ws instead of competing with it —+a `<agent-3d>` viewer in someone else's app, an agent paying an x402 endpoint+from another platform, a walk companion on a third party's homepage. A broken+`files[]`, a README example that doesn't run, or a `npm install @three-ws/avatar`+that throws on a fresh machine, and a would-be integrator bounces forever. Clean,+documented, dry-run-verified packages turn three.ws into infrastructure.++## Mission++Every published SDK has a correct `package.json` (exports, `files[]`, semver),+a README with real working examples, a clean dry-run publish, and a working+demo/example — so an external developer can install it and ship in minutes.++## Map (trust but verify — files move)++- **Top-level SDKs** (published, not workspaces) — [sdk/](../../sdk) (`@three-ws/sdk`),+ [solana-agent-sdk/](../../solana-agent-sdk) (`@three-ws/solana-agent`),+ [agent-payments-sdk/](../../agent-payments-sdk) (`@three-ws/agent-payments`),+ [agent-protocol-sdk/](../../agent-protocol-sdk) (`@three-ws/agent-protocol-sdk`).+- **App-adjacent SDKs** (workspaces) — [avatar-sdk/](../../avatar-sdk) (`@three-ws/avatar`),+ [walk-sdk/](../../walk-sdk) (`@three-ws/walk`), [tour-sdk/](../../tour-sdk) (`@three-ws/tour`).+- **Spec/schema/preset packages** — [packages/avatar-schema/](../../packages/avatar-schema)+ (`@three-ws/avatar-schema`), [packages/avatar-cli/](../../packages/avatar-cli)+ (`@three-ws/avatar-cli`), [packages/viewer-presets/](../../packages/viewer-presets)+ (`@three-ws/viewer-presets`), [packages/react/](../../packages/react) (`@three-ws/react`).+- **Examples / demos** — [examples/](../../examples) (`embed-test.html`, `web-component.html`,+ `two-agents.html`, `minimal.html`), [multiplayer/](../../multiplayer).+- **Publish tooling** — `npm run publish:packages:dry`+ ([scripts/publish-packages.mjs](../../scripts/publish-packages.mjs)),+ `publish:mcp:dry` ([scripts/publish-mcp-servers.mjs](../../scripts/publish-mcp-servers.mjs)),+ `publish:lib` ([scripts/publish-lib.mjs](../../scripts/publish-lib.mjs)), and the strongest+ gate — [scripts/verify-packages.mjs](../../scripts/verify-packages.mjs) (packs each tarball,+ installs it in a clean throwaway project, then exercises its real public surface).+- **Workspace map** — [STRUCTURE.md](../../STRUCTURE.md) "npm workspaces" + "Promotion path".++## Do this++1. **Inventory + verify names/versions:** for every SDK above, confirm `package.json`+ `name` matches STRUCTURE.md, `version` is sane semver, `type`/`exports`/`main`/`module`/+ `types` resolve, and `files[]` (or `.npmignore`) ships exactly the published surface —+ no `src` leak, no missing `dist`. Confirm a `prepublishOnly`/build runs the build.+2. **Run the real-consumer gate:** `node scripts/verify-packages.mjs` — it packs each+ package into its actual npm tarball, installs into a clean project resolving deps fresh,+ and imports the SDK / runs the CLI bin / boots the MCP server. Fix every `files[]` gap,+ broken export map, or missing runtime dep it surfaces.+3. **Dry-run both publishers:** `npm run publish:packages:dry` and `npm run publish:mcp:dry`.+ Both must report clean — no version-already-published surprises, no auth errors, no+ missing build outputs.+4. **READMEs must teach by example:** each README has install, a minimal runnable example+ (web component, `import`, or CLI invocation), the public API surface, and a link to the+ live page/demo. Every code block must actually run against the published surface — copy+ one into a scratch project and confirm.+5. **Wire a working demo per SDK:** `@three-ws/avatar` → an `examples/` page renders the+ `<agent-3d>` viewer; `@three-ws/walk` → the walk companion mounts; `@three-ws/tour` →+ the feature tour boots; payment/protocol SDKs → a runnable example call (real endpoint,+ no mock). Exercise each in a real browser (`npm run dev`) or node where applicable; zero+ console errors.+6. **Semver discipline:** bump only what changed (patch/minor/major per real diff). Keep+ any `peerDependencies` honest (Three.js, React versions) so installs don't warn. Do not+ publish from this prompt — dry-run + verify only, unless the user explicitly says publish.+7. **Cross-link the docs:** each SDK README links to STRUCTURE.md's workspace row and to its+ sibling SDKs where they compose (e.g. avatar viewer + walk companion). The best platforms+ feel like everything is linked.+8. **Changelog + build:** add a `data/changelog.json` entry (tag `sdk`) for any user-visible+ SDK doc/version change, then `npm run build:pages` (it validates the entry).++## Must-not++- Do not publish to npm/registry from this prompt unless the user explicitly asks — dry-run only.+- Do not ship a README example that doesn't run, or a `files[]` that leaks `src`/tests or drops `dist`.+- Do not reference any coin other than `$THREE` in any example, fixture, or doc.+- Do not use a mock/fake endpoint in an example — real APIs only (or a clearly synthetic placeholder).+- Do not bump versions cosmetically; semver must reflect the actual change.+- Do not break a working package's exports while "cleaning up" its config.++## Acceptance (all true before claiming done)++- [ ] Every SDK `package.json` has a correct `name`, semver `version`, resolving `exports`,+ and a tight `files[]`; builds run via `prepublishOnly`.+- [ ] `node scripts/verify-packages.mjs` passes for every package (clean-room install + surface check).+- [ ] `npm run publish:packages:dry` and `npm run publish:mcp:dry` both report clean.+- [ ] Each README has install + a runnable example + API surface + a live demo link; examples verified to run.+- [ ] At least one working demo per SDK is exercised with zero console errors.+- [ ] No coin other than `$THREE` appears anywhere in SDK source, examples, or docs.+- [ ] Changelog updated (if user-visible) and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/25-worlds-coin-clash.md b/prompts/billion-dollar-program/25-worlds-coin-clash.mdnew file mode 100644index 000000000..fd0f72379--- /dev/null+++ b/prompts/billion-dollar-program/25-worlds-coin-clash.md@@ -0,0 +1,106 @@+# 25 — Worlds & Coin Clash (token-gated 3D)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++"Every coin is a 3D world you can drop into" and "hold a coin, enlist, and fight+live armies" is the social loop that makes a token sticky beyond price — it turns+holders into citizens and a chart into a place. If a world dead-ends on a void, a+presence sync drops players, or the enlist gate lets a non-holder in (or locks a+real holder out), the network effect collapses. Reliable, every-state, token-gated+multiplayer is what makes three.ws a destination instead of a tool.++## Mission++Make every coin enterable as a live 3D world and make Coin Clash — token-gated+community warfare (hold the coin → enlist → rally battle power live) — correct,+multiplayer-reliable, beautifully stated in every phase, and $THREE-compliant for+anything the platform itself promotes.++## Map (trust but verify — files move)++- **Worlds lobby (front door)** — [pages/worlds.html](../../pages/worlds.html),+ [src/worlds-lobby.js](../../src/worlds-lobby.js) (pick/drop-in an avatar, list live+ coin-worlds, enter at `/walk?coin=<mint>`).+- **Worlds data + gating** — [api/community/worlds.js](../../api/community/worlds.js)+ (`GET /api/community/worlds`), [api/community/world-gate.js](../../api/community/world-gate.js)+ (per-coin holder threshold; creator-only POST), [api/community/ws-ticket.js](../../api/community/ws-ticket.js)+ (short-lived realtime ticket), [api/world/[action].js](../../api/world/[action].js)+ (per-world persistence: `load`/`save`).+- **Coin Clash UI** — [pages/clash.html](../../pages/clash.html), [src/clash.js](../../src/clash.js)+ (bracket → battle cards → enlist challenge → rally dock).+- **Coin Clash API + store** — [api/clash/[action].js](../../api/clash/[action].js)+ (`state`, `enlist`, `enlist-verify`, `rally`, `leaderboard`), backed by+ [api/_lib/clash.js](../../api/_lib/clash.js), [api/_lib/clash-store.js](../../api/_lib/clash-store.js),+ [api/_lib/crews-store.js](../../api/_lib/crews-store.js).+- **Realtime multiplayer** — [multiplayer/](../../multiplayer) (authoritative Colyseus server):+ [multiplayer/src/rooms/WalkRoom.js](../../multiplayer/src/rooms/WalkRoom.js),+ [multiplayer/src/rooms/ClashRoom.js](../../multiplayer/src/rooms/ClashRoom.js),+ presence in [multiplayer/src/presence-token.js](../../multiplayer/src/presence-token.js).+- **Hyperfy world host** — [deploy/world/](../../deploy/world) + [scripts/world-health.mjs](../../scripts/world-health.mjs).+- **Verify/smoke** — [scripts/verify-worlds-lobby.mjs](../../scripts/verify-worlds-lobby.mjs)+ (offline/unconfigured state), [scripts/verify-worlds-live.mjs](../../scripts/verify-worlds-live.mjs)+ (configured live worlds), [scripts/world-health.mjs](../../scripts/world-health.mjs)+ (asset-integrity check). Tests: [tests/clash-match.test.js](../../tests/clash-match.test.js),+ [tests/world-store.test.js](../../tests/world-store.test.js).++## Do this++1. **Exercise the worlds lobby** (`npm run dev`, `/worlds`): pick/drop-in an avatar with no+ sign-in, browse live coin-worlds, and enter one. Confirm both states work — configured+ (real grid via `GET /api/community/worlds`) and unconfigured (graceful "offline" layer+ where worlds are still enterable, the documented 503 degradation). Run+ `node scripts/verify-worlds-lobby.mjs` (and `verify-worlds-live.mjs` against a configured+ dev server): zero console errors beyond the one tolerated 503.+2. **Drop into a world end-to-end:** enter `/walk?coin=<mint>`, confirm the world loads (no+ void), the avatar spawns, persistence round-trips via `api/world/[action]` (`save`→`load`),+ and `scripts/world-health.mjs` reports every blueprint asset present (the 2026-06-12 void+ regression must not recur).+3. **Token-gate correctly:** verify `api/community/world-gate.js` — a coin creator can set a+ holder threshold, GET states the requirement publicly, and entry re-verifies the on-chain+ holding server-side. A real holder gets in; a non-holder hits a designed, actionable gate+ screen (tells them what to hold and how). Fail closed when creator/holding is unknown.+4. **Coin Clash full loop** (`/clash`): poll `state` → render the bracket → enlist (wallet+ challenge → `enlist-verify` confirms a live on-chain holding of the faction coin) → rally+ dock opens, taps batch and flush to `rally` as battle power. Confirm holdings are gated+ on-chain (no client trust) and the leaderboard reflects real effort.+5. **Design every state** across both surfaces: loading (skeleton, not a fake bar), empty+ (no live worlds / no active battles → what to do next), error (network/upstream failure →+ actionable recovery), and overflow (many worlds, long coin names, big armies). No blank+ voids, no dead buttons.+6. **Multiplayer reliability:** in the Colyseus rooms (`WalkRoom`, `ClashRoom`), verify+ presence join/leave, reconnect after a dropped socket, and ticket auth via+ `api/community/ws-ticket.js` + `presence-token.js`. A player who disconnects must not+ linger as a ghost; a reconnect must restore identity. Boot the server with+ `npm run dev:multi` (or `dev:walk-all`) and test two browser tabs.+7. **Run the suites:** `npx vitest run tests/clash-match.test.js tests/world-store.test.js`+ and the multiplayer package's own tests. Add coverage for any uncovered failure mode+ (gate-denied, upstream 503, presence drop/reconnect, matchmaking bye).+8. **$THREE compliance + changelog:** any coin the platform *promotes* must be `$THREE`+ (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); the worlds grid and faction roster are+ runtime launch-record feeds (allowed) — never hardcode/market a non-$THREE mint. Add a+ `data/changelog.json` entry for any user-visible change, then `npm run build:pages`.++## Must-not++- Do not let a non-holder past a token gate, or lock out a verified holder — gate on-chain, fail closed.+- Do not ship a world that can drop players into a void; assets must be verified present.+- Do not hardcode, market, or recommend any mint other than `$THREE` (runtime launch feeds are fine).+- Do not fake presence/multiplayer with timers or client-trusted state — use the authoritative rooms.+- Do not leave any state undesigned (no blank voids, no dead buttons, no never-resolving spinners).+- Do not weaken a verify/smoke/health check to make a run pass.++## Acceptance (all true before claiming done)++- [ ] `/worlds` works in both configured and unconfigured states; `verify-worlds-lobby.mjs`+ (and `verify-worlds-live.mjs` configured) pass with no unexpected console errors.+- [ ] Dropping into `/walk?coin=<mint>` loads a real world (no void), spawns the avatar, and+ persists via `api/world/[action]`; `scripts/world-health.mjs` reports all assets present.+- [ ] Token gating verified on-chain: holders enter, non-holders see a designed actionable gate.+- [ ] Coin Clash loop works end-to-end (state → enlist → enlist-verify → rally), holdings gated on-chain.+- [ ] Loading/empty/error/overflow states designed across both surfaces; presence join/leave/reconnect reliable.+- [ ] `tests/clash-match.test.js`, `tests/world-store.test.js`, and multiplayer tests pass; new failure modes covered.+- [ ] No promoted coin other than `$THREE`; changelog updated and `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/26-observability.md b/prompts/billion-dollar-program/26-observability.mdnew file mode 100644index 000000000..3cdae1eeb--- /dev/null+++ b/prompts/billion-dollar-program/26-observability.md@@ -0,0 +1,96 @@+# 26 — Observability (logging, metrics, error tracking)++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++You cannot scale what you cannot see. When the Forge hangs, a payment silently+fails, or a cron stops firing at 3am, the difference between a five-minute fix and+a five-hour outage is whether the right structured log, metric, and alert already+exist. At $1B scale every minute of operator blindness is revenue, trust, and+$THREE-holder confidence bleeding out. Observability is the nervous system that lets+a small team run a large platform.++## Mission++Make every hot path emit structured, correlated, PII-free logs; record metrics on+generation/payment/RPC paths; and ensure every server error reaches Sentry + a+deduped ops alert with a traceable ref — without leaking secrets or vendor internals.++## Map (trust but verify — files move)++- **Client logger** — [src/shared/log.js](../../src/shared/log.js) — gated logger+ (`error` always emits; `warn/info/debug` gated by DEV / `?debug` / `localStorage['tws:debug']`),+ exports `log` + `createLogger(tag)`.+- **HTTP boundary + correlation IDs** — [api/_lib/http.js](../../api/_lib/http.js) —+ `correlationId()`, `serverError()` (emits `[server-error <ref>]`, calls Sentry + alert),+ `wrap()`, and `redactUrl()` which strips `lat/lng/token/devicetoken` before logging.+- **Generation metrics** — [api/_lib/forge-events.js](../../api/_lib/forge-events.js) —+ `recordGenerationEvent()` (JSON line `evt:"forge_gen"` + Redis hourly rolling counters),+ `readGenerationMetrics()`; consumed by [api/_lib/forge-health.js](../../api/_lib/forge-health.js).+- **Payment/business metrics** — [api/_lib/axiom.js](../../api/_lib/axiom.js) —+ `recordPaymentMetric()`, `ingestEvent()` (no-op when `AXIOM_TOKEN`/`AXIOM_DATASET` unset).+- **Error tracking** — [api/_lib/sentry.js](../../api/_lib/sentry.js) —+ `captureException()`, `captureMessage()` (fetch-based envelope, 2.5s abort, no-op without `SENTRY_DSN`).+- **Ops alerts** — [api/_lib/alerts.js](../../api/_lib/alerts.js) — `sendOpsAlert(title, detail, opts)`,+ per-signature dedup (1h) + 20/hr global ceiling (Telegram).+- **x402 audit trail** — [api/_lib/x402/audit-log.js](../../api/_lib/x402/audit-log.js).+- **Tests** — [tests/api/healthz.test.js](../../tests/api/healthz.test.js),+ [tests/api/forge-health.test.js](../../tests/api/forge-health.test.js),+ [tests/api/audit-log.test.js](../../tests/api/audit-log.test.js).++## Do this++1. **Inventory the boundaries.** Read `http.js` end-to-end. Confirm every `api/`+ handler that can 5xx routes through `serverError()`/`wrap()` so it gets a `ref`,+ a Sentry capture, and an alert. Grep for raw `res.status(500)` /+ `console.error` that bypass the boundary and route them through `http.js`.+2. **Standardize log levels.** Audit `console.*` calls across `api/` and `src/`.+ Client code must use `src/shared/log.js` (no raw `console.log` shipping to prod);+ server code emits one structured JSON line per significant event with a stable+ `evt` key (mirror `forge_gen`). No free-text-only logs on hot paths.+3. **PII/secret redaction is non-negotiable.** Extend `redactUrl()` and any log+ payload builder to strip wallet secrets, bearer tokens, API keys, email, and+ precise geo. Add a test asserting a crafted error with a token in the URL ++ body never appears verbatim in the logged/captured payload.+4. **Metrics on hot paths.** Confirm `recordGenerationEvent()` fires on every forge+ lifecycle phase (start/done/failed). Wire `recordPaymentMetric()` (Axiom) on+ every x402 settle/verify/refund outcome if any path is missing it. These must be+ fail-open (a metrics hiccup never blocks the request).+5. **Correlation end to end.** Ensure the `ref` from `serverError()` is returned in+ the JSON error body AND attached to the Sentry/alert context, so a support ref+ maps to one log line. Add `ref` to the user-facing error copy where surfaced.+6. **Alert hygiene.** Verify `sendOpsAlert` dedup + 20/hr ceiling work (read+ `alerts.js`); confirm health crons (`world-health`, `redis-health`, `llm/health`)+ alert on degradation, not on every probe. No alert storms.+7. **Verify graceful no-op.** With `SENTRY_DSN`, `AXIOM_TOKEN`, and+ `TELEGRAM_*` unset locally, the whole stack must stay silent and non-throwing.+ Run the relevant tests and a local request to confirm.+8. Run `npx vitest run tests/api/healthz.test.js tests/api/forge-health.test.js+ tests/api/audit-log.test.js` plus any new redaction test. Add a `data/changelog.json`+ entry only if a user-visible surface changed (e.g. a `ref` shown on error pages),+ then `npm run build:pages`.++## Must-not++- Never log secrets, private keys, bearer tokens, raw wallet payloads, full emails,+ or precise geo — redact at the boundary.+- Never surface a vendor's billing/credit/quota message or raw stack to an end user;+ raw detail lives in server logs and Sentry only.+- Never make a request block on a metrics/alert/Sentry call — all are fire-and-forget.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror).+- No mocks, stubs, or TODOs; finish every path you touch. The only coin is `$THREE`.++## Acceptance (all true before claiming done)++- [ ] Every 5xx in `api/` produces a correlation `ref`, a Sentry capture, and a+ deduped ops alert; the same `ref` is in the response body and the log line.+- [ ] Hot paths (forge phases, x402 settle/verify/refund) emit structured metrics;+ all metric/alert/Sentry calls are fail-open and non-blocking.+- [ ] A redaction test proves tokens/secrets/PII never appear in logged or captured+ payloads (URL and body).+- [ ] With all observability env vars unset, the stack is silent and never throws.+- [ ] `tests/api/healthz`, `forge-health`, `audit-log` and any new test pass.+- [ ] Changelog updated only if user-visible; `npm run build:pages` is clean.diff --git a/prompts/billion-dollar-program/27-database-integrity-migrations.md b/prompts/billion-dollar-program/27-database-integrity-migrations.mdnew file mode 100644index 000000000..2b72ec0b3--- /dev/null+++ b/prompts/billion-dollar-program/27-database-integrity-migrations.md@@ -0,0 +1,94 @@+# 27 — Database integrity & migrations++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The database holds money truth: payment intents, agent revenue, skill licenses,+launch records. One non-idempotent migration that half-applies, one missing unique+index that lets a payment double-settle, or one unindexed hot query that table-scans+under load can corrupt balances or take the platform down during the exact traffic+spike you wanted. At $1B, schema discipline is the floor that everything else stands+on — it must be boringly safe, forward-only, and reversible.++## Mission++Guarantee every migration is idempotent and forward-safe, every hot query is indexed+and constrained, money paths are protected by unique/FK constraints, and no+destructive change ships without a backup — with retry and timeouts on the Neon client.++## Map (trust but verify — files move)++- **Migrations** — [api/_lib/migrations/](../../api/_lib/migrations) — ~134 `.sql`+ files (mixed `001_`, dated, and `YYYYMMDDHHMMSS_` naming). Idempotency via+ `CREATE TABLE/INDEX IF NOT EXISTS` and `DO $$ … EXCEPTION WHEN duplicate_object`.+- **Base schema** — [api/_lib/schema.sql](../../api/_lib/schema.sql) — ~1900 lines,+ `pgcrypto`/`citext`, fully idempotent (`IF NOT EXISTS` everywhere).+- **Neon client** — [api/_lib/db.js](../../api/_lib/db.js) — `@neondatabase/serverless`+ HTTP driver, lazy init, composable SQL fragments with placeholder renumbering.+- **Retry helper** — [api/_lib/db-retry.js](../../api/_lib/db-retry.js) — `withDbRetry`,+ 3 attempts, retries transient connection errors only (never SQLSTATE constraint errors).+- **Migration runner** — [scripts/apply-migrations.mjs](../../scripts/apply-migrations.mjs) —+ dry-run by default (`--apply` to write), `schema_migrations` ledger (filename + SHA-256),+ drift detection (refuses if a hash changed), `Pool` for multi-statement files.+ Scripts: `npm run db:status` (dry) / `npm run db:migrate` (apply).+- **Money-path examples** —+ [api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql](../../api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql)+ (anti-replay unique tx_hash),+ [api/_lib/migrations/20260621120000_revenue-integrity.sql](../../api/_lib/migrations/20260621120000_revenue-integrity.sql)+ (partial unique index + CHECK via DO/EXCEPTION).+- **Tests** — [tests/db-sql-compose.test.js](../../tests/db-sql-compose.test.js)+ (fragment placeholder renumbering), [tests/db-retry.test.js](../../tests/db-retry.test.js).++## Do this++1. **Establish the truth.** Run `npm run db:status` to see applied vs pending and+ confirm the `schema_migrations` ledger + drift detection work. Never edit a+ migration that has already applied (it breaks the SHA-256 drift guard) — add a+ new forward migration instead.+2. **Idempotency sweep.** Grep every file under `api/_lib/migrations/` for+ `CREATE TABLE`/`CREATE INDEX`/`ADD CONSTRAINT`/`ADD COLUMN` lacking+ `IF NOT EXISTS` or a `DO $$ … EXCEPTION` guard. Each must be safe to re-run on a+ DB that already has the object. Fix any that aren't (new migration if already applied).+3. **Hot-query indexes.** Identify the most-read tables (payments/intents, agent+ revenue, launches, marketplace, feeds). For each frequent `WHERE`/`ORDER BY`/`JOIN`,+ confirm a supporting index exists; add `CREATE INDEX IF NOT EXISTS` (use partial+ indexes where a column is nullable, mirroring the revenue-integrity pattern).+4. **Constraints on money paths.** Verify unique constraints prevent double-settle+ (e.g. one intent per on-chain tx_hash) and that foreign keys tie child rows to+ their owners. Add missing UNIQUE/FK/CHECK via the `DO $$ … EXCEPTION WHEN+ duplicate_object THEN NULL; END $$;` idempotent pattern.+5. **No destructive change without a backup.** Audit migrations for `DROP TABLE`,+ `DROP COLUMN`, `TRUNCATE`. For any new destructive op, require an explicit Neon+ branch/snapshot first and document the rollback; prefer additive deprecation+ (rename-then-drop in a later release) over in-place drops.+6. **Client safety.** Confirm money/critical reads/writes go through `withDbRetry`.+ Add a request-level query timeout (`Promise.race` against a bounded deadline)+ around long DB calls so a stalled Neon connection can't hang a serverless+ function past its limit. Keep retry classification (transient vs constraint) intact.+7. **Split-safety.** The runner splits multi-statement files on bare `;` at line+ ends — verify any new migration with `DO $$`/dollar-quoted bodies still parses+ (test against `db:status`), and that statements are individually idempotent.+8. Run `npx vitest run tests/db-sql-compose.test.js tests/db-retry.test.js`, then+ `npm run db:status` to confirm a clean, applied-or-pending state. Add a+ `data/changelog.json` entry only if a user-visible behavior changed; `npm run build:pages`.++## Must-not++- Never edit an already-applied migration — it trips the drift guard; add a forward one.+- Never ship `DROP`/`TRUNCATE`/`DROP COLUMN` without a Neon snapshot + documented rollback.+- Never make a migration non-idempotent; assume it may re-run on a partially-applied DB.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror).+- No mocks, stubs, or TODOs. The only coin is `$THREE` — no other mint in fixtures/seeds.++## Acceptance (all true before claiming done)++- [ ] `npm run db:status` shows a clean ledger; drift detection verified working.+- [ ] Every migration is idempotent (`IF NOT EXISTS` / `DO $$ … EXCEPTION`), safe to re-run.+- [ ] Hot tables have indexes covering their frequent `WHERE`/`ORDER BY`/`JOIN`.+- [ ] Money paths carry unique + FK + CHECK constraints (e.g. no double-settle per tx).+- [ ] No destructive migration lacks a backup/rollback plan; additive deprecation preferred.+- [ ] Critical DB calls use `withDbRetry` and a bounded query timeout.+- [ ] `db-sql-compose` and `db-retry` tests pass; changelog updated only if user-visible.diff --git a/prompts/billion-dollar-program/28-deploy-pipeline-rollback.md b/prompts/billion-dollar-program/28-deploy-pipeline-rollback.mdnew file mode 100644index 000000000..ae529a0fb--- /dev/null+++ b/prompts/billion-dollar-program/28-deploy-pipeline-rollback.md@@ -0,0 +1,92 @@+# 28 — Deploy pipeline & rollback safety++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++A platform handling real money and real assets must be able to ship safely and undo+instantly. The single worst footgun in this repo is `npx vercel build` rewriting+`api/*.js` source files in place with esbuild bundles — committing one corrupts the+backend silently. Add a missed cron registration, a desync between the two git+remotes, or a deploy with no fast rollback, and a routine push becomes an outage.+At $1B, deploys must be a non-event: gated, verified, mirrored, and reversible.++## Mission++Harden the deploy path so a bundled `api/` file can never reach `main`, the deploy+audit + build gates always run, crons stay in sync with their handlers, both git+remotes stay aligned, and rollback is one documented command away.++## Map (trust but verify — files move)++- **Bundle guard** — [scripts/check-api-not-bundled.mjs](../../scripts/check-api-not-bundled.mjs) —+ scans first 4096 bytes of every `api/**/*.js` for `__defProp`, `createRequire(`,+ `__toESM(`, `__toCommonJS(`; exits non-zero with `git restore -- api/ public/` recovery hint.+- **Deploy artifact audit** — [scripts/audit-deploy-artifacts.mjs](../../scripts/audit-deploy-artifacts.mjs) —+ catches committed symlinks + unsatisfied peers + undeclared `api/` imports. Run `npm run audit:deploy`.+- **Build orchestrator** — [scripts/build-vercel.mjs](../../scripts/build-vercel.mjs) —+ 5-phase build; phase 1 gates on `audit:deploy`, `test:gate`, `verify:solana`,+ `verify:onchain`, `audit:mcp`. Run `npm run build:vercel`.+- **Vercel config** — [vercel.json](../../vercel.json) — `routes`, `functions`, `headers`,+ `env`, and `crons` (~46 cron entries). Cron handlers live in [api/cron/](../../api/cron).+- **CI** — [.github/workflows/ci.yml](../../.github/workflows/ci.yml) — jobs: **lint**+ (`eslint .`), **test** (`vitest run`), **guards** (`check-api-not-bundled.mjs`,+ `check:images`, `build:pages`), **typecheck** (advisory, continue-on-error).+- **Tests** — [tests/deploy-artifacts.test.js](../../tests/deploy-artifacts.test.js).+- **Git remotes** — `origin` → `nirholas/three.ws` (canonical), `threeD` →+ `nirholas/3D-Agent` (push-only mirror). Per `/CLAUDE.md`, every push goes to BOTH.++## Do this++1. **Prove the bundle guard.** Read `check-api-not-bundled.mjs`. Confirm it runs in+ CI (guards job) and as a build gate. Before any large `api/` commit, run+ `node scripts/check-api-not-bundled.mjs` and `head -1` changed files for+ `__defProp`/`createRequire`; recover with `git restore -- api/ public/`. Add a+ `pre-commit`/local check note if not already enforced.+2. **Run the deploy audit.** `npm run audit:deploy` — fix any symlink, peer-dep, or+ undeclared-import finding it reports. This is the gate that caught the 2026-06-11+ outage class; it must pass clean.+3. **Cron registration sanity.** There is no validator that `vercel.json` crons map+ 1:1 to `api/cron/*` handlers (the counts differ because some handlers serve+ multiple schedules). Write/extend a script that, for every `crons[].path` in+ `vercel.json`, asserts a resolvable handler exists under `api/`, and flags any+ `api/cron/*` handler with no schedule. Wire it into the guards CI job.+4. **Verify the build gates fire.** Run `npm run build:vercel` (or inspect phase 1)+ and confirm `audit:deploy`, `test:gate`, `verify:solana`, `verify:onchain`,+ `audit:mcp` all run and that RPC-dependent verifies degrade to warnings (never+ hard-fail) when an RPC is down — a flaky RPC must not block a deploy.+5. **Dual-remote discipline.** Document and (where possible) script that every push+ goes to `origin` AND `threeD` in the same step; never force-push without explicit+ request; NEVER pull/fetch/merge from `threeD`. Surface an error if the two+ remotes' `main` diverge rather than silently leaving them out of sync.+6. **Rollback runbook.** Document the fast rollback: `vercel rollback` (or promote a+ prior production deployment in the Vercel dashboard) plus `git revert` using a+ NEUTRAL commit message (never echo the reverted title, per `/CLAUDE.md`). Capture+ how to re-point both remotes after a revert.+7. **Preview deploys.** Confirm preview/PR deployments are isolated from production+ data (no prod writes, no prod crons). If any preview can touch prod money/DB,+ gate it behind env separation.+8. Run `npx vitest run tests/deploy-artifacts.test.js`, `npm run audit:deploy`, and+ `node scripts/check-api-not-bundled.mjs`. Add a `data/changelog.json` entry only+ if a user-visible surface changed (deploy hardening is usually internal); if so,+ `npm run build:pages`.++## Must-not++- Never commit a bundled `api/*.js` (esbuild markers in the first bytes) — guard + recover.+- Never pull/fetch/merge from `threeD`; it is a push-only mirror. Push to BOTH remotes.+- Never force-push to either remote without an explicit request.+- Never let an RPC outage hard-block a deploy — verify steps degrade to warnings.+- No mocks, stubs, or TODOs in the pipeline scripts. The only coin is `$THREE`.++## Acceptance (all true before claiming done)++- [ ] `check-api-not-bundled.mjs` passes; documented recovery is `git restore -- api/ public/`.+- [ ] `npm run audit:deploy` passes clean (no symlink/peer/undeclared-import findings).+- [ ] A cron-sync check asserts every `vercel.json` cron has a handler (and flags orphans), wired into CI.+- [ ] Build gates run and RPC-dependent verifies degrade to warnings when RPC is down.+- [ ] Dual-remote push discipline is documented/scripted; divergence is surfaced, not hidden.+- [ ] A fast rollback runbook exists (Vercel promote/rollback + neutral-message revert).+- [ ] `deploy-artifacts` test passes; changelog updated only if user-visible.diff --git a/prompts/billion-dollar-program/29-uptime-status-page.md b/prompts/billion-dollar-program/29-uptime-status-page.mdnew file mode 100644index 000000000..c497dc6c9--- /dev/null+++ b/prompts/billion-dollar-program/29-uptime-status-page.md@@ -0,0 +1,90 @@+# 29 — Uptime monitoring & public status page++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Trust is the currency of a money-moving platform. When something breaks, users and+$THREE holders need a single honest place that tells them what's up, what's degraded,+and that the team already knows — before they tweet. A polished public status page+with real uptime history converts incidents from credibility losses into proof of+operational maturity. And external monitoring is the smoke detector that pages the+team even when the platform is too down to alert itself.++## Mission++Aggregate every health probe into one `/api/status` feed backing a public `/status`+page with real 90-day uptime history, wire external (off-box) uptime monitoring, and+ensure degradation pages the team via the existing ops-alert channel.++## Map (trust but verify — files move)++- **Public status page** — [pages/status.html](../../pages/status.html) — live+ dashboard, 90-day uptime bars, auto-polls `/api/status` every 5 min. Registered in+ [data/pages.json](../../data/pages.json) (`/status`, section "learn").+- **Status feed** — `api/status.js` (powers the page; verify path under [api/](../../api)).+- **Aggregate health** — [api/healthz.js](../../api/healthz.js) — probes Resend,+ x402 facilitator, SIWX payments table, bot heartbeat, alert watches.+- **Forge health** — [api/_lib/forge-health.js](../../api/_lib/forge-health.js)+ (served via `GET /api/forge?health`) — probes generation backends + Redis + world.+- **Admin probes** — [api/admin/redis-health.js](../../api/admin/redis-health.js),+ [api/admin/pump-cron-health.js](../../api/admin/pump-cron-health.js).+- **Health crons** — [api/cron/world-health.js](../../api/cron/world-health.js),+ `api/cron/uptime-check.js`, [api/llm/health.js](../../api/llm/health.js).+- **Ops alerts** — [api/_lib/alerts.js](../../api/_lib/alerts.js) — `sendOpsAlert()`,+ deduped + 20/hr ceiling (Telegram).+- **Nav** — [public/nav-data.js](../../public/nav-data.js) (`NAV_GROUPS`, single+ source of truth for menu items), [public/nav.js](../../public/nav.js).+- **Tests** — [tests/api/healthz.test.js](../../tests/api/healthz.test.js),+ [tests/api/forge-health.test.js](../../tests/api/forge-health.test.js).++## Do this++1. **Exercise what exists.** Open `/status` in a real browser (`npm run dev`) and+ hit `/api/status`. Confirm the page polls every 5 min, renders per-service dots,+ 90-day bars, and the "warming-up" first-deploy state. Note any probe missing.+2. **Make the feed complete.** Ensure `/api/status` aggregates ALL subsystems:+ `healthz` (Resend/x402/DB/heartbeat/watches), `forge?health` (gen backends + Redis+ + world), redis-health, pump-cron-health, world-health, llm/health. Add any+ probe that the public page should reflect; admin-gated probes feed status via the+ server (the public response must never leak admin detail or secrets).+3. **Real history, not synthetic.** Verify the 90-day uptime data is recorded from+ actual probe results (a cron writing samples to Redis/DB), not faked. If history+ storage is thin, persist each `uptime-check` result with a retention window so the+ bars reflect truth. No `setTimeout` fake data.+4. **Every state designed.** Confirm `/status` has designed loading, warming-up+ (no history yet), all-operational, degraded, and down states — accessible,+ responsive at 320/768/1440, with hover/focus on interactive elements.+5. **External monitoring.** Wire an off-box uptime monitor (e.g. an+ UptimeRobot/BetterStack/Checkly HTTP check, or a free cron-job.org ping) against+ `/api/healthz` and `/api/status` that pages the team independently of Vercel.+ Document the config and the alert destination. Do not invent a fake integration —+ set up a real one or document the exact steps + env to enable it.+6. **Degradation pages the team.** Confirm the health crons call `sendOpsAlert` on+ degradation only (not every probe), respecting dedup + the 20/hr ceiling — no+ alert storms. Add alerting for any subsystem currently probed-but-silent.+7. **Discoverability.** Add `/status` to `public/nav-data.js` (footer/utility group)+ and link it from error pages and the footer so users can find it when things break.+8. Run `npx vitest run tests/api/healthz.test.js tests/api/forge-health.test.js`,+ exercise `/status` in the browser (no console errors), then add a+ `data/changelog.json` entry (status page improvements are user-visible) and+ `npm run build:pages`.++## Must-not++- Never expose admin-only health detail, internal URLs, or secrets in the public `/api/status`.+- Never fake uptime history with `setTimeout` or hardcoded bars — record real samples.+- Never let the public page flip top-level "operational" to red on a single flaky probe — debounce.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror).+- No mocks, stubs, or TODOs. The only coin is `$THREE`.++## Acceptance (all true before claiming done)++- [ ] `/api/status` aggregates all subsystem probes; the public response leaks no admin detail/secrets.+- [ ] `/status` renders real 90-day history from recorded samples; loading/warming/degraded/down states designed.+- [ ] An external, off-box uptime monitor pings `/api/healthz` + `/api/status` and pages the team (real config documented).+- [ ] Health crons alert via `sendOpsAlert` on degradation only, respecting dedup + ceiling.+- [ ] `/status` is reachable from nav + footer + error pages; no console errors; responsive + accessible.+- [ ] `healthz` and `forge-health` tests pass; changelog updated and `npm run build:pages` clean.diff --git a/prompts/billion-dollar-program/30-load-stress-testing.md b/prompts/billion-dollar-program/30-load-stress-testing.mdnew file mode 100644index 000000000..66063bb0a--- /dev/null+++ b/prompts/billion-dollar-program/30-load-stress-testing.md@@ -0,0 +1,95 @@+# 30 — Load & stress testing++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++The day a launch goes viral is the day you find out whether the platform holds. If+the Forge GPU budget, the x402 verify path, or the public feeds buckle under a+traffic spike — or worse, if a spike silently burns the entire monthly Redis command+budget in a day — the moment you waited for becomes the outage that defines you. You+cannot guess capacity at $1B; you measure it, find the breaking point on purpose in a+safe lane, and prove the rate-limits and budgets hold before real users arrive.++## Mission++Identify the hottest and most-expensive endpoints, script realistic load tests+(k6/artillery) against a non-production target, prove the rate-limits and Redis+budget hold at their designed ceilings, find the breaking points, and document capacity.++## Map (trust but verify — files move)++- **Hottest endpoints** — [api/forge.js](../../api/forge.js) (text→3D, GPU-bound),+ [api/x402-checkout.js](../../api/x402-checkout.js) + [api/x402/forge.js](../../api/x402/forge.js)+ (payment prepare/verify), [api/feed.js](../../api/feed.js) ++ [api/feed-stream.js](../../api/feed-stream.js) + [api/trades/feed.js](../../api/trades/feed.js)+ (read-heavy, polled).+- **Rate limiting** — [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) — Upstash+ sliding-window (in-memory fallback for dev/tests); ~80+ named buckets; critical+ (money) buckets fail CLOSED, non-critical reads fail OPEN; `local: true` buckets+ never consume Redis. Key ceilings: `forge_paid_global_hourly` (600/h),+ `x402_verify_global_per_hour` (12000/h), `mcp3dGenerate` (30/h), `publicIp` (60/min).+- **Redis budget** — [api/_lib/redis-usage.js](../../api/_lib/redis-usage.js) —+ `REDIS_MONTHLY_BUDGET = 500_000` (Upstash free tier), warn 80% / crit 90%; daily ≈16,667.+- **x402 paid endpoint plumbing** — [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js).+- **Existing smokes (not load tests)** — [scripts/onchain-smoke.mjs](../../scripts/onchain-smoke.mjs)+ (`npm run smoke:onchain`), [scripts/smoke-mcp-remotes.mjs](../../scripts/smoke-mcp-remotes.mjs)+ (`npm run smoke:mcp`), [scripts/smoke-api-endpoints.mjs](../../scripts/smoke-api-endpoints.mjs).+- **Env** — [.env.example](../../.env.example) — `UPSTASH_REDIS_REST_URL/TOKEN`,+ `FORGE_PAID_GLOBAL_HOURLY`, `X402_VERIFY_GLOBAL_PER_HOUR` overrides.++> No load-test tooling exists yet — this is net-new. Add it under `scripts/` (or a+> new `loadtest/` dir) and an npm script; do not pollute the repo root.++## Do this++1. **Rank by cost and heat.** From the map, classify endpoints into GPU-bound+ (forge), money-path (x402 checkout/verify), and read-heavy (feeds, status,+ marketplace). Read `rate-limit.js` to record the exact ceiling for each so tests+ target the designed limit, not an arbitrary number.+2. **Pick the tool, add it cleanly.** Adopt k6 (preferred) or artillery as a+ dev/CI dependency. Create `loadtest/` (or `scripts/load/`) with one script per+ class: `forge.js`, `x402.js`, `feeds.js`. No scratch files in the repo root.+3. **Target a safe environment.** Run against a preview/staging deploy or a local+ `npm run dev`, NEVER production money paths. For x402, drive the 402 price-discovery+ and verify amplification path with synthetic/declined payments — never settle real+ funds, never use a non-`$THREE` mint.+4. **Prove the limiters hold.** Push each endpoint to and past its bucket ceiling;+ assert that critical money buckets fail CLOSED (reject, not melt) and read buckets+ fail OPEN/degrade. Confirm 429s are returned with correct `Retry-After`-style copy+ and no 5xx storms.+5. **Watch the Redis budget.** While a feeds/status load test runs, sample+ `redis-usage.js` accounting. Confirm high-frequency cheap reads use `local: true`+ buckets (per the June-2026 quota-burn incident) so a spike does not torch the+ 500k/month budget. Flag any hot read that hits Redis on every request.+6. **Find the breaking point.** Ramp concurrency until p95 latency or error rate+ crosses an SLO (define one, e.g. p95 < 1s for reads, generation queue bounded).+ Record the knee of the curve per endpoint — that is your capacity number.+7. **Verify autoscaling/queueing holds.** Confirm forge's global hourly circuit+ breaker queues/sheds rather than overrunning the shared GPU budget, and that+ serverless concurrency limits don't cascade into timeouts on dependent calls.+8. Document results: per-endpoint ceiling, observed p50/p95, breaking point, Redis+ cost/request, and recommended limits in a `loadtest/README.md`. Run+ `node scripts/smoke-api-endpoints.mjs` (or `npm run smoke:onchain`) as a sanity+ pass against the safe target. Add a+ `data/changelog.json` entry only if a user-visible limit/behavior changed; `npm run build:pages`.++## Must-not++- Never load-test production money paths or settle real funds; use staging + synthetic payments.+- Never use a non-`$THREE` mint in any test fixture or payload.+- Never leave load scripts or result files in the repo root — `loadtest/` or `scripts/`, gitignore artifacts.+- Do not weaken a working rate-limit just to "pass" a test — the limit is the answer.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror). No mocks/stubs/TODOs.++## Acceptance (all true before claiming done)++- [ ] Endpoints ranked by cost/heat with each target's exact rate-limit ceiling recorded.+- [ ] k6/artillery scripts exist for forge, x402, and feeds, run against staging/local (never prod).+- [ ] At ceiling: critical buckets fail CLOSED, read buckets degrade; 429s correct, no 5xx storms.+- [ ] Redis budget is not torched by a read spike; high-frequency reads use `local` buckets.+- [ ] Breaking point (knee) documented per endpoint against a stated SLO.+- [ ] `loadtest/README.md` records capacity numbers + recommended limits; no artifacts committed.+- [ ] A smoke pass succeeds; changelog updated only if user-visible.diff --git a/prompts/billion-dollar-program/31-solana-rpc-onchain-resilience.md b/prompts/billion-dollar-program/31-solana-rpc-onchain-resilience.mdnew file mode 100644index 000000000..e93d5f200--- /dev/null+++ b/prompts/billion-dollar-program/31-solana-rpc-onchain-resilience.md@@ -0,0 +1,97 @@+# 31 — Solana RPC & on-chain resilience++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++Solana is the platform default network — launches, trades, payments, skill licenses,+and $THREE all live on-chain. A single RPC provider throttling or going down must not+take the platform with it, and a charge must never settle twice or charge-then-silently-revert.+On-chain money is unforgiving: at $1B, RPC failover, idempotent settlement, and+provable address parity are the difference between a graceful degrade and an+irreversible loss of funds or trust.++## Mission++Guarantee RPC failover/retry across providers, idempotent on-chain operations,+revert-safe confirmations, verified address/program parity, and graceful degradation+(cached/null reads, clear UI) when RPC is impaired — never a charge into the void.++## Map (trust but verify — files move)++- **RPC connection (canonical)** — [api/_lib/solana/connection.js](../../api/_lib/solana/connection.js) —+ `solanaConnection()` (transparent failover), `solanaRpcEndpoints()` (priority chain:+ caller url → `SOLANA_RPC_URL` → Helius → Alchemy → dRPC → Ankr → operator fallbacks →+ PublicNode/Leo/Tatum keyless → public mainnet-beta last), `makeRotatingFetch()` with+ per-endpoint quota cooldown + body validation.+- **RPC fallback class** — [api/_lib/solana/rpc-fallback.js](../../api/_lib/solana/rpc-fallback.js)+ — `RpcFallback` (3 consecutive fails → rotate, 60s cooldown), `rpcFallbackFromEnv()`.+- **Resilience (cockatiel)** — [api/_lib/resilience.js](../../api/_lib/resilience.js) —+ `withBreaker(name, fn, opts)`, `isCircuitError()` (ConsecutiveBreaker, 5 fails, 30s half-open).+- **SDK bridge (graceful null)** — [api/_lib/solana/sdk-bridge.js](../../api/_lib/solana/sdk-bridge.js)+ — pump SDK reads return `null` on transient RPC errors instead of throwing.+- **Confirm guard** — [api/_lib/solana/confirm.js](../../api/_lib/solana/confirm.js) —+ `confirmOrThrow()` throws on reverted tx (catches silent `result.value.err`).+- **Idempotency** — [api/_lib/x402/idempotency-cache.js](../../api/_lib/x402/idempotency-cache.js),+ [api/_lib/migrations/20260504140000_create_payment_intents.sql](../../api/_lib/migrations/20260504140000_create_payment_intents.sql),+ [api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql](../../api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql).+- **Parity/smoke** — [scripts/verify-solana-parity.mjs](../../scripts/verify-solana-parity.mjs)+ (`verify:solana`), [scripts/verify-onchain-parity.mjs](../../scripts/verify-onchain-parity.mjs)+ (`verify:onchain`), [scripts/onchain-smoke.mjs](../../scripts/onchain-smoke.mjs) (`smoke:onchain`).+- **Tests** — [tests/solana-rpc-rotating-fetch.test.js](../../tests/solana-rpc-rotating-fetch.test.js),+ [tests/api/solana-rpc-endpoints.test.js](../../tests/api/solana-rpc-endpoints.test.js),+ [tests/solana-confirm.test.js](../../tests/solana-confirm.test.js).++## Do this++1. **Audit every RPC entry point.** Grep for `new Connection(` / direct RPC URL use+ across `api/` and `workers/`. Every Solana read/write must go through+ `solanaConnection()` (or `RpcFallback`) so it inherits failover — never a single+ hardcoded provider. Fix any that bypass the helper.+2. **Wrap expensive/external calls in a breaker.** For aggregations and third-party+ reads (price, graduation progress, oracle attestations), wrap in `withBreaker`+ from `resilience.js` so a sick provider trips the circuit instead of hammering it.+ Reads use the connection's native rotation; the breaker guards the outer call.+3. **Validate rotating-fetch never leaks bad bodies.** Confirm (per the existing+ regression test) that `makeRotatingFetch` rejects `[]`, HTML, truncated JSON, and+ missing `result/error` rather than handing them to web3.js. Add cover for any new+ provider added to the chain.+4. **Idempotent on-chain ops.** Verify every settle/mint/trade path is keyed by an+ idempotency token (intent_id / payment id / tx_hash) backed by the unique+ constraint + `idempotency-cache`. The same id + same payload must replay the+ cached result with NO second on-chain action; same id + different payload → 409.+5. **Revert-safe confirmations.** Confirm money paths use `confirmOrThrow()` so a tx+ whose revert lands in `result.value.err` is treated as a failure (refund/retry),+ never charged-and-forgotten. Add cover for any path confirming manually.+6. **Graceful degradation.** When all RPC endpoints are exhausted, reads should+ return cached/`null` and the UI should show "live data unavailable, retrying"+ (designed, not a dead spinner) — never a raw RPC error and never a partial write.+ Verify writes abort cleanly (no half-settled state) when RPC is down mid-op.+7. **Prove parity + liveness.** Run `npm run verify:solana` and `npm run verify:onchain`;+ they must confirm the $THREE mint + program IDs match canonical and degrade to a+ warning (not hard-fail) when RPC is unreachable. Run `npm run smoke:onchain` against+ a safe target.+8. Run `npx vitest run tests/solana-rpc-rotating-fetch.test.js+ tests/api/solana-rpc-endpoints.test.js tests/solana-confirm.test.js`. Add a+ `data/changelog.json` entry only if a user-visible behavior changed (e.g. a new+ degraded-state message); then `npm run build:pages`.++## Must-not++- Never instantiate a raw single-provider `Connection` on a money path — use the failover helper.+- Never let a charge settle without an idempotency key + revert-safe confirmation.+- Never surface a raw RPC/provider error to the user — degrade with designed copy.+- Never hardcode or recommend any non-`$THREE` mint; parity is checked against the $THREE CA.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror). No mocks/stubs/TODOs.++## Acceptance (all true before claiming done)++- [ ] Every Solana entry point uses the failover connection/`RpcFallback`; no bypassing raw `new Connection`.+- [ ] Expensive/third-party reads are guarded by `withBreaker`; rotating-fetch rejects malformed bodies.+- [ ] Settle/mint/trade are idempotent (id + unique constraint + cache); same id never double-acts.+- [ ] Money paths confirm via `confirmOrThrow`; reverts become failures, never silent charges.+- [ ] RPC-down degrades to cached/null reads with designed UI; writes abort cleanly with no half-state.+- [ ] `verify:solana` + `verify:onchain` pass (warn, not fail, when RPC down); `smoke:onchain` green.+- [ ] RPC/confirm/endpoint tests pass; changelog updated only if user-visible.diff --git a/prompts/billion-dollar-program/32-caching-cdn-r2.md b/prompts/billion-dollar-program/32-caching-cdn-r2.mdnew file mode 100644index 000000000..e916ac28f--- /dev/null+++ b/prompts/billion-dollar-program/32-caching-cdn-r2.md@@ -0,0 +1,96 @@+# 32 — Caching, CDN & R2 asset strategy++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++3D is heavy: GLBs, textures, animations, and HDRs are megabytes each, and every+uncached fetch is latency the user feels and bandwidth the platform pays for. At $1B+scale, correct `Cache-Control` + CDN edge caching turns a slow viewer into an instant+one and cuts origin egress dramatically. Meanwhile the 500k/month Upstash command+budget means a single hot read that hits Redis on every request can torch the entire+budget in days — so caching is also a cost-survival discipline, not just speed.++## Mission++Ensure static + GLB/3D assets carry correct immutable/long-cache headers, R2 has CORS++ a lifecycle for orphaned assets, expensive reads are Redis-cached within budget with+stampede protection, and CDN edge caching is used wherever the data allows.++## Map (trust but verify — files move)++- **Cache headers** — [vercel.json](../../vercel.json) `headers` — existing rules:+ versioned `agent-3d` → `max-age=31536000, immutable`; `/avatars/*.glb` &+ `/animations/*` → `max-age=604800, stale-while-revalidate=2592000`; `/assets/*` →+ immutable; generic media regex covers `glb|gltf|hdr|exr|ktx2|basis|bin|woff2|…`.+- **R2 client** — [api/_lib/r2.js](../../api/_lib/r2.js) — S3-compatible (AWS SDK v3):+ `putObject`, `getObject`, `deleteObject`, `headObject`, `copyObject`, presigned+ up/download, `publicUrl(key)`. Env: `S3_ENDPOINT/ACCESS_KEY_ID/SECRET_ACCESS_KEY/BUCKET/PUBLIC_DOMAIN`.+- **R2 CORS** — [scripts/set-r2-cors.mjs](../../scripts/set-r2-cors.mjs) (`npm run apply:r2-cors`)+ — `public-read` (GET/HEAD) + `browser-upload` (PUT) rules with three.ws/preview/codespace/localhost origins.+- **Redis cache primitives** — [api/_lib/cache.js](../../api/_lib/cache.js) —+ `cacheGet/cacheSet/cacheWrap` (TTL), 2s in-process memo, single-flight in-flight+ coalescing, `acquireLock` distributed lock for expensive recompute.+- **Redis budget** — [api/_lib/redis-usage.js](../../api/_lib/redis-usage.js) —+ `REDIS_MONTHLY_BUDGET = 500_000`, warn 80% / crit 90%; [api/admin/redis-health.js](../../api/admin/redis-health.js).+- **Generated GLB storage** — [api/_lib/forge-store.js](../../api/_lib/forge-store.js),+ [api/_lib/reconstruct-finalize.js](../../api/_lib/reconstruct-finalize.js) (put to R2 → `publicUrl`).+- **Tests** — [tests/api/forge-cache-headers.test.js](../../tests/api/forge-cache-headers.test.js),+ [tests/http-cache-control.test.js](../../tests/http-cache-control.test.js),+ [tests/api/redis-usage.test.js](../../tests/api/redis-usage.test.js),+ [tests/api/skill-price-cache.test.js](../../tests/api/skill-price-cache.test.js).++## Do this++1. **Audit asset cache coverage.** For every static + 3D asset type served (GLB,+ GLTF, HDR, EXR, KTX2, BASIS, BIN, fonts, images, versioned JS), confirm a+ `Cache-Control` rule in `vercel.json` matches it. Content-addressed/versioned+ assets get `max-age=31536000, immutable`; mutable-but-cacheable assets get a long+ `max-age` + `stale-while-revalidate`. Fill any gap the audit finds.+2. **Never long-cache mutable HTML/API.** Verify HTML pages and `api/*` responses+ default to `no-store` (via `http.js`) unless a route is explicitly safe to edge-cache;+ long-caching a stale dashboard or balance is a correctness bug. Add `s-maxage` ++ `stale-while-revalidate` only to read endpoints whose data tolerates it (e.g. feeds, changelog).+3. **R2 CORS is current.** Run `npm run apply:r2-cors` and confirm the allowed origins+ cover prod, `*.vercel.app` previews, codespaces, and localhost, with `ETag`/`Accept-Ranges`+ exposed for range requests (GLB streaming). Add any missing origin idempotently.+4. **R2 lifecycle for orphans.** There is no object lifecycle today — generated GLBs+ accumulate forever. Add a lifecycle/cleanup path: either an R2 lifecycle rule for a+ `tmp/`/`scratch/` prefix, or a cron that deletes orphaned/unreferenced objects+ (cross-checked against the DB so nothing live is removed). Never delete a referenced asset.+5. **Cache expensive reads within budget.** Identify hot, expensive reads (on-chain+ scans, snapshots, price/market aggregates). Wrap them in `cacheWrap` with a sane+ TTL. Confirm high-frequency cheap reads use `local`/in-process memo (not a Redis+ GET per request) so the 500k/month budget survives a spike.+6. **Stampede protection on cold cache.** For any expensive recompute, use+ `acquireLock` so a traffic spike against a cold key fans out into ONE recompute+ platform-wide, not N. Verify the in-flight GET coalescing path works under+ concurrent reads.+7. **CDN edge caching.** Ensure cacheable read endpoints set `s-maxage` so Vercel's+ edge serves them without hitting the function/origin, and that GLBs are served from+ the R2 public CDN domain (not proxied through a function). Watch `redis-health` /+ `redis-usage` while exercising to confirm budget headroom.+8. Run `npx vitest run tests/api/forge-cache-headers.test.js tests/http-cache-control.test.js+ tests/api/redis-usage.test.js tests/api/skill-price-cache.test.js`. Verify headers+ live in the browser Network tab (`npm run dev`). Add a `data/changelog.json` entry+ if a user-visible perf change shipped; `npm run build:pages`.++## Must-not++- Never apply `immutable`/long `max-age` to mutable HTML, dashboards, balances, or `api/*` writes.+- Never delete an R2 object that is still referenced — cross-check the DB before any lifecycle delete.+- Never add a hot read that issues a Redis command per request without memo/local bucketing — respect the 500k budget.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror). No mocks/stubs/TODOs.+- The only coin is `$THREE` — no other token in any cache key, fixture, or copy.++## Acceptance (all true before claiming done)++- [ ] Every static + 3D asset type has a correct `Cache-Control` rule (immutable for versioned, SWR for mutable).+- [ ] HTML/API stay `no-store` except explicitly edge-cacheable reads with `s-maxage` + SWR.+- [ ] `apply:r2-cors` run; CORS covers prod/preview/codespace/localhost with range headers exposed.+- [ ] An R2 lifecycle/cleanup removes orphaned assets only, cross-checked against the DB.+- [ ] Expensive reads use `cacheWrap`; hot cheap reads avoid per-request Redis; budget headroom confirmed.+- [ ] Stampede protection (lock + in-flight coalescing) verified on a cold expensive key.+- [ ] Cache-header tests pass; headers verified in the browser; changelog updated if user-visible.diff --git a/prompts/billion-dollar-program/33-onboarding-activation.md b/prompts/billion-dollar-program/33-onboarding-activation.mdnew file mode 100644index 000000000..c2b260ecf--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/34-home-landing-conversion.md b/prompts/billion-dollar-program/34-home-landing-conversion.mdnew file mode 100644index 000000000..07a9524aa--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/35-pricing-monetization.md b/prompts/billion-dollar-program/35-pricing-monetization.mdnew file mode 100644index 000000000..b6b1d701b--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/36-growth-analytics.md b/prompts/billion-dollar-program/36-growth-analytics.mdnew file mode 100644index 000000000..d676f2bf5--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/37-dx-docs-site.md b/prompts/billion-dollar-program/37-dx-docs-site.mdnew file mode 100644index 000000000..f462c63e4--- /dev/null+++ b/prompts/billion-dollar-program/37-dx-docs-site.md@@ -0,0 +1,91 @@+# 37 — Developer experience & docs site++> Part of the three.ws "Production → $1B" program. Run in a fresh chat. Read+> `/CLAUDE.md` first (its rules override everything) and `prompts/billion-dollar-program/00-README.md`+> for shared context.++## Why this matters for $1B++three.ws is a developer platform: SDKs, MCP servers, web components, and a paid+x402 API. Developers decide in the first five minutes whether to build on you, and+that decision is made on the docs. A quickstart that doesn't copy-paste-run, a stale+API reference, or `llms.txt` that contradicts the live endpoints loses every+integration before it starts. World-class docs are the cheapest, highest-leverage+acquisition channel a dev platform has.++## Mission++Make every doc accurate, every code example actually runnable, and the docs site+itself searchable, versioned, and self-consistent with the real API surface and the+machine-readable `llms.txt` / `llms-full.txt`.++## Map (trust but verify — files move)++- **Docs content** — [public/docs/](../../public/docs) (~40 `.md` files:+ `quick-start.md`, `api-reference.md`, `sdk.md`, `mcp.md`, `web-component.md`,+ `widget-api.md`, `embedding.md`, `authentication.md`, `examples.md`, …).+- **Tutorials** — [public/docs/tutorials/](../../public/docs/tutorials)+ (`getting-started.md`, `first-agent.md`, `embed-on-website.md`,+ `register-onchain.md`, `custom-skill.md`, `personal-ai-site.md`).+- **Walk docs (HTML)** — [public/docs/walk/](../../public/docs/walk)+ (`index.html`, `docs.js`, `getting-started.html`, `embed-sdk.html`, …).+- **Docs home + routing** — [docs/index.html](../../docs/index.html), routes in+ [vercel.json](../../vercel.json) (`/docs`, `/docs/walk`, `/docs/widgets` →+ [public/docs-widgets.html](../../public/docs-widgets.html)).+- **Machine-readable docs** — [public/llms.txt](../../public/llms.txt),+ [public/llms-full.txt](../../public/llms-full.txt) (regenerated from content;+ find the generator under [scripts/](../../scripts)).+- **API truth source** — handlers in [api/](../../api); web-component reference in+ [src/element.js](../../src/element.js) (the `<agent-3d>` element).+- **Embed snippet builders** — [src/share-panel-builders.js](../../src/share-panel-builders.js)+ (`buildIframeSnippet`, `buildWebComponentSnippet`) — docs snippets must match these.++## Do this++1. **Run every code example.** Open each doc and tutorial; copy each fenced code+ block and execute it (curl against the real API, `npm install` the SDK, mount the+ `<agent-3d>` element). Any block that errors, 404s, or references a renamed+ param/endpoint gets fixed against the live handler in `api/`.+2. **Reconcile the API reference** (`public/docs/api-reference.md`) with the actual+ handlers: every documented route, method, query param, and response shape must+ exist; remove documented-but-deleted endpoints; add shipped-but-undocumented ones.+3. **Fix the SDK / MCP quickstarts** (`sdk.md`, `mcp.md`, `quick-start.md`) so a cold+ developer goes from zero to a working call. Use the published package names and the+ free `forge_free` MCP lane for the zero-cost first call (no wallet/key required).+4. **Web-component / embed docs** (`web-component.md`, `widget-api.md`,+ `embedding.md`) must produce the exact snippet `share-panel-builders.js` emits —+ same tag, attributes, and origin. Test the snippet in a blank HTML file.+5. **Regenerate and validate `llms.txt` / `llms-full.txt`** with the existing+ generator script; confirm they list real, live page paths and the current API+ surface — no dangling routes.+6. **Docs search + navigation**: ensure the docs home is searchable (verify+ `public/docs/walk/docs.js` search works; if the main `/docs` index lacks search,+ add a client-side filter over the doc list). Every doc must be reachable from the+ index — no orphans.+7. **Versioning + freshness signal**: each doc shows a "last updated" / version marker+ sourced from real data (git date or front-matter), not a hardcoded string. Stale+ docs are worse than missing ones.+8. Run `npm run build:pages`, `npm run audit:pages`, and `npm run seo:meta`. Add a+ `data/changelog.json` entry (tag `docs`) for the doc refresh; rebuild pages.++## Must-not++- Do not ship a code example you have not run — no aspirational snippets.+- Do not document any endpoint, package, or coin that doesn't exist; the only coin is+ `$THREE`.+- Do not break working docs routes in `vercel.json`; verify each redirect resolves.+- Do not leave `llms.txt`/`llms-full.txt` contradicting the live docs after edits.+- No mocks, stubs, TODOs, or "coming soon" placeholders in published docs.++## Acceptance (all true before claiming done)++- [ ] Every fenced code block in `public/docs/**` and `public/docs/tutorials/**` runs+ against real APIs/SDKs with no errors.+- [ ] `api-reference.md` matches the handlers in `api/` (no phantom or missing routes).+- [ ] SDK + MCP quickstarts take a cold developer to a successful call; free lane works.+- [ ] Embed/web-component docs emit the same snippet as `share-panel-builders.js`,+ verified in a blank page.+- [ ] `llms.txt` and `llms-full.txt` regenerated and consistent with live docs/API.+- [ ] Docs are searchable, every doc is reachable from the index, freshness markers+ are real (not hardcoded).+- [ ] `npm run build:pages`, `audit:pages`, `seo:meta` clean; changelog entry added.diff --git a/prompts/billion-dollar-program/38-referral-virality.md b/prompts/billion-dollar-program/38-referral-virality.mdnew file mode 100644index 000000000..7c2dabc56--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/39-trust-safety-moderation.md b/prompts/billion-dollar-program/39-trust-safety-moderation.mdnew file mode 100644index 000000000..061eb7851--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/40-legal-compliance-tos-privacy.md b/prompts/billion-dollar-program/40-legal-compliance-tos-privacy.mdnew file mode 100644index 000000000..ade8fdae6--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/41-i18n-completion.md b/prompts/billion-dollar-program/41-i18n-completion.mdnew file mode 100644index 000000000..4b93b0e2d--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/42-pwa-offline-notifications.md b/prompts/billion-dollar-program/42-pwa-offline-notifications.mdnew file mode 100644index 000000000..263526ee2--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/43-brand-press-social-proof.md b/prompts/billion-dollar-program/43-brand-press-social-proof.mdnew file mode 100644index 000000000..f7948880e--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/billion-dollar-program/44-launch-readiness-review.md b/prompts/billion-dollar-program/44-launch-readiness-review.mdnew file mode 100644index 000000000..ba5905461--- /dev/null+++ b/prompts/billion-dollar-program/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/billion-dollar-program/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/market/A-reliability/00-README.md b/prompts/market/A-reliability/00-README.mddeleted file mode 100644index 4776850b6..000000000--- a/prompts/market/A-reliability/00-README.md+++ /dev/null@@ -1,64 +0,0 @@-# 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/market/A-reliability/A1-observability-backbone.md b/prompts/market/A-reliability/A1-observability-backbone.mddeleted file mode 100644index a428da34e..000000000--- a/prompts/market/A-reliability/A1-observability-backbone.md+++ /dev/null@@ -1,93 +0,0 @@-# 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/market/A-reliability/A2-api-hardening.md b/prompts/market/A-reliability/A2-api-hardening.mddeleted file mode 100644index fc03a6558..000000000--- a/prompts/market/A-reliability/A2-api-hardening.md+++ /dev/null@@ -1,90 +0,0 @@-# 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/market/A-reliability/A3-payment-correctness.md b/prompts/market/A-reliability/A3-payment-correctness.mddeleted file mode 100644index 04d96d5b8..000000000--- a/prompts/market/A-reliability/A3-payment-correctness.md+++ /dev/null@@ -1,102 +0,0 @@-# 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/market/A-reliability/A4-security-hardening.md b/prompts/market/A-reliability/A4-security-hardening.mddeleted file mode 100644index b9ea31ec1..000000000--- a/prompts/market/A-reliability/A4-security-hardening.md+++ /dev/null@@ -1,92 +0,0 @@-# 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/market/A-reliability/A5-test-coverage-ci-gate.md b/prompts/market/A-reliability/A5-test-coverage-ci-gate.mddeleted file mode 100644index 91084ba47..000000000--- a/prompts/market/A-reliability/A5-test-coverage-ci-gate.md+++ /dev/null@@ -1,89 +0,0 @@-# 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/market/A-reliability/A6-performance-web-vitals.md b/prompts/market/A-reliability/A6-performance-web-vitals.mddeleted file mode 100644index eb68635bb..000000000--- a/prompts/market/A-reliability/A6-performance-web-vitals.md+++ /dev/null@@ -1,85 +0,0 @@-# 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/market/D-monetization/00-README.md b/prompts/market/D-monetization/00-README.mddeleted file mode 100644index 14bbe9980..000000000--- a/prompts/market/D-monetization/00-README.md+++ /dev/null@@ -1,58 +0,0 @@-# 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/market/D-monetization/D1-three-holder-value-system.md b/prompts/market/D-monetization/D1-three-holder-value-system.mddeleted file mode 100644index cf2c64f20..000000000--- a/prompts/market/D-monetization/D1-three-holder-value-system.md+++ /dev/null@@ -1,107 +0,0 @@-# 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/market/D-monetization/D2-billing-pricing-metering.md b/prompts/market/D-monetization/D2-billing-pricing-metering.mddeleted file mode 100644index 41beb2194..000000000--- a/prompts/market/D-monetization/D2-billing-pricing-metering.md+++ /dev/null@@ -1,112 +0,0 @@-# 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/market/D-monetization/D3-x402-paid-endpoints-network.md b/prompts/market/D-monetization/D3-x402-paid-endpoints-network.mddeleted file mode 100644index 91ab3f5e1..000000000--- a/prompts/market/D-monetization/D3-x402-paid-endpoints-network.md+++ /dev/null@@ -1,114 +0,0 @@-# 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/market/D-monetization/D4-marketplace-economics.md b/prompts/market/D-monetization/D4-marketplace-economics.mddeleted file mode 100644index abd91c8d9..000000000--- a/prompts/market/D-monetization/D4-marketplace-economics.md+++ /dev/null@@ -1,117 +0,0 @@-# 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-1b/00-README.md b/prompts/production-1b/00-README.mdnew file mode 100644index 000000000..81439625d--- /dev/null+++ b/prompts/production-1b/00-README.md@@ -0,0 +1,138 @@+# three.ws — Production → $1B Program++A complete, ordered set of self-contained prompts. **Run each one in a fresh chat.**+Every prompt is written to stand alone: it names the real files involved, the current+state, exactly what to build, and a hard definition of done. No prompt assumes context+from another chat.++The goal is not "more features." It is to make every surface that already exists+**real, reliable, and revenue-generating** — the bar set in [CLAUDE.md](../../CLAUDE.md):+no mocks, no stubs, no dead paths, every state designed, every integration wired to a+real API, and work you would demo to a room of senior engineers.++---++## How to run++1. Open a new chat in this repo.+2. Paste the full contents of one prompt file (or say "run prompts/production-1b/A01-….md").+3. Let it finish to its definition of done — including tests, a real browser/API check,+ and a changelog entry — before moving on.+4. Commit + push to **both** remotes (`threeD` and `threews`) per CLAUDE.md.+5. Tick the box in the tracker below and start the next.++Each prompt header declares:+- **Phase** — which track it belongs to.+- **Depends on** — prompts that should land first (most are independent).+- **Parallel-safe** — whether two agents can run it alongside others without colliding.++Concurrent agents share this worktree. Stage explicit paths only — never `git add -A`.++---++## The thesis (why these, in this order)++A $1B platform on a token economy needs three things to be true at once, and the phases+map to them:++1. **The money is provably real.** The $THREE buyback, reflections, tiers, and x402+ payments must execute on-chain, be auditable, and be enforced everywhere — not+ aspirational. → **Phase A**+2. **Every surface that touches money is world-class.** The token page, onboarding,+ checkout/swap, marketplace, forge, studio, agent pages. → **Phase B**, then the+ discovery and 3D surfaces that feed them → **Phase C, D**.+3. **It never falls over and it compounds.** Observability, resilience, security, the+ developer ecosystem (network effects), and the growth/quality loops. → **Phase E, F, G**++Recommended execution order: **A → B → E → C → D → F → G**, but Phase E (infra) prompts+are safe to interleave early, and Phase G (quality) prompts are safe to run anytime.++---++## Phases & prompts++### Phase A — Make the money provably real (highest leverage)+- [ ] `A01` — $THREE buyback engine: scheduled, on-chain, audited, public proof+- [ ] `A02` — $THREE reflections/rewards: complete on-chain distribution + receipts+- [ ] `A03` — Hold-to-access tiers enforced across every paid endpoint+- [ ] `A04` — Holder snapshot freshness, reconciliation & alerting+- [ ] `A05` — On-chain token-config validation + public token-economy & trust dashboard+- [ ] `A06` — Treasury/buyback custody hardening (vault + approval gate + audit)+- [ ] `A07` — x402 pricing: single source of truth + discoverable service catalog+- [ ] `A08` — x402 per-wallet metering, rate-limit headers & usage endpoint+- [ ] `A09` — x402 facilitator failover + self-hosted fallback + admin health/metrics+- [ ] `A10` — Agent-to-agent payments: dispute/refund + on-chain reputation+- [ ] `A11` — Inline "Payment Required" (402) pay modal everywhere++### Phase B — World-class revenue surfaces+- [ ] `B01` — $THREE token page production pass+- [ ] `B02` — Onboarding / Get Started wizard production pass+- [ ] `B03` — Payment modal + Jupiter swap production pass+- [ ] `B04` — Marketplace + detail + creator profiles production pass+- [ ] `B05` — Forge (text/image → 3D) end-to-end production pass+- [ ] `B06` — Auth (sign-in/up, session, wallet) production pass+- [ ] `B07` — Dashboard hub + account + analytics + API keys production pass+- [ ] `B08` — Agent Studio (brain/memory/body/money/skills) production pass+- [ ] `B09` — Agent profile pages + embeddable widget production pass+- [ ] `B10` — Launch-a-coin + launches feed production pass++### Phase C — Discovery, social & intelligence+- [ ] `C01` — Oracle conviction engine + Arm automation production pass+- [ ] `C02` — Activity + Trending + Feed + Community production pass+- [ ] `C03` — Leaderboards + Smart Money + Radar production pass+- [ ] `C04` — Galleries (avatars, animations, agent discovery) production pass++### Phase D — 3D / AR / world experiences+- [ ] `D01` — Avatar pipeline reliability (forge → auto-rig → animate) hardening+- [ ] `D02` — Walk companion + playground + leaderboard + embed production pass+- [ ] `D03` — IRL (AR placement) + Play (coin worlds, multiplayer) production pass+- [ ] `D04` — Creator tools (Scene Studio, Compose, Pose, Voice, Scan) production pass++### Phase E — Platform infrastructure & reliability+- [ ] `E01` — Structured logging + request correlation + tracing+- [ ] `E02` — Error telemetry dashboard + tiered alerting & escalation+- [ ] `E03` — Health/readiness endpoint + dependency checks + status page+- [ ] `E04` — Circuit breakers + adaptive retry for all external dependencies+- [ ] `E05` — Redis quota: proactive monitoring + degraded-feature signaling+- [ ] `E06` — Migrations: remove CREATE TABLE from handlers, add versioning & rollback+- [ ] `E07` — Cron + worker health: execution history, SLA, dashboard+- [ ] `E08` — SSRF + input sanitization + secret-scanning hardening+- [ ] `E09` — Data layer: read-replica routing, partitioning, backup/restore drills+- [ ] `E10` — CI/CD: test gate, e2e on money paths, publish automation++### Phase F — Developer ecosystem (network effects)+- [ ] `F01` — Unified developer guide + runnable examples + quickstarts+- [ ] `F02` — SDK tests + versioning + release automation + changelogs+- [ ] `F03` — MCP servers: reconcile duplicates, e2e tests, registry & DX polish+- [ ] `F04` — x402 / Bazaar discoverability + indexing++### Phase G — Quality, trust & growth (escape velocity)+- [ ] `G01` — Accessibility (WCAG 2.2 AA) platform-wide+- [ ] `G02` — Performance budgets + Core Web Vitals + 3D runtime perf+- [ ] `G03` — Mobile / responsive audit platform-wide+- [ ] `G04` — SEO + structured data + OG + LLM discoverability+- [ ] `G05` — Security & payments/custody review pass+- [ ] `G06` — Conversion analytics + funnels + experimentation harness+- [ ] `G07` — Referral / affiliate + viral loops + creator incentives+- [ ] `G08` — Lifecycle comms: changelog + email/notifications + re-engagement++---++## The shared bar (every prompt inherits this)++Do not mark a prompt done until all are true (this is CLAUDE.md's Definition of Done):++- Code is wired into the UI / API and reachable by a real user — no dead paths.+- No mocks, no fake/sample data, no `TODO`, no `throw new Error("not implemented")`,+ no commented-out code, no fake `setTimeout` loading.+- Every state is designed: loading (skeletons), empty (actionable), error (recoverable),+ populated, overflow.+- Real network calls succeed against real APIs; errors handled at the boundary.+- Existing tests pass (`npx vitest run`) and you added tests for new logic.+- Accessible (semantic HTML, ARIA, keyboard, focus, contrast) and responsive (320/768/1440).+- `$THREE` is the only coin referenced anywhere (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+- A holder-readable entry appended to `data/changelog.json` for any user-visible change;+ `npm run build:pages` passes.+- `git diff` self-reviewed; committed and pushed to **both** remotes.++If you cannot verify a step, say so explicitly. Do not claim done.diff --git a/prompts/production-1b/19-walk-page-agent-tour.md b/prompts/production-1b/19-walk-page-agent-tour.mdnew file mode 100644index 000000000..24bee8660--- /dev/null+++ b/prompts/production-1b/19-walk-page-agent-tour.md@@ -0,0 +1,133 @@+# 19 — Walk companion, Page-Agent & Feature Tour++> 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++These three surfaces are how three.ws makes a 3D agent *show up* on any page — the+corner mascot that strolls a site, the drop-in narrator that explains a product, and+the guided tour that walks a first-time visitor through the platform. They are the+embeddable, shareable, screenshot-worthy front of the funnel and the reason a+developer installs `@three-ws/walk` or `@three-ws/page-agent` instead of building+their own. If the companion janks, the narrator picks a T-posed avatar, or the tour+dead-ends, the "living 3D web" promise dies on first contact and so does virality.++## Mission++Take the Walk companion (mascot + full-page playground + diverse avatar picker), the+`<page-agent>` narrator, and the 3D Feature Tour to end-to-end production polish:+every state designed, every avatar rigged and animating, smooth at 60fps, and never a+broken hand-off between modes.++## Map (trust but verify — files move)++- **Walk SDK (`@three-ws/walk`)** — [walk-sdk/src/index.js](../../walk-sdk/src/index.js)+ (public API), [walk-sdk/src/companion.js](../../walk-sdk/src/companion.js) (corner+ mascot), [walk-sdk/src/playground.js](../../walk-sdk/src/playground.js) (full-page+ stroll/platformer), [walk-sdk/src/picker.js](../../walk-sdk/src/picker.js) ++ [walk-sdk/src/roster.js](../../walk-sdk/src/roster.js) (diverse avatar picker ++ `WALK_AVATARS`), [walk-sdk/src/config.js](../../walk-sdk/src/config.js),+ [walk-sdk/package.json](../../walk-sdk/package.json), [walk-sdk/README.md](../../walk-sdk/README.md).+- **Walk app entries** — [src/walk-companion.js](../../src/walk-companion.js) (on-demand+ platform inject), [src/walk-playground.js](../../src/walk-playground.js). Pages:+ [pages/walk-landing.html](../../pages/walk-landing.html) (`/walk`),+ [pages/walk-embed.html](../../pages/walk-embed.html) (`/walk-embed` code generator),+ [pages/walk-leaderboard.html](../../pages/walk-leaderboard.html),+ [pages/walk-analytics.html](../../pages/walk-analytics.html).+- **Page-Agent SDK (`@three-ws/page-agent`)** — [page-agent-sdk/src/index.js](../../page-agent-sdk/src/index.js)+ (public API), [page-agent-sdk/src/element.js](../../page-agent-sdk/src/element.js)+ (`<page-agent>` custom element), [page-agent-sdk/src/page-agent.js](../../page-agent-sdk/src/page-agent.js)+ (controller), [page-agent-sdk/src/catalog.js](../../page-agent-sdk/src/catalog.js)+ (**rigged-only** catalog), [page-agent-sdk/src/picker.js](../../page-agent-sdk/src/picker.js),+ [page-agent-sdk/src/narrator.js](../../page-agent-sdk/src/narrator.js),+ [page-agent-sdk/src/lipsync.js](../../page-agent-sdk/src/lipsync.js),+ [page-agent-sdk/src/stage.js](../../page-agent-sdk/src/stage.js). Demos:+ [page-agent-sdk/examples/](../../page-agent-sdk/examples). Publish:+ [page-agent-sdk/PUBLISHING.md](../../page-agent-sdk/PUBLISHING.md).+- **Feature Tour** — [src/feature-tour/index.js](../../src/feature-tour/index.js)+ (`createFeatureTour`, `?tour=start` bootstrap), [src/feature-tour/director.js](../../src/feature-tour/director.js)+ (curriculum stepping/spotlight/pointing), [src/feature-tour/controls.js](../../src/feature-tour/controls.js)+ (playback bar), [src/feature-tour/free-roam.js](../../src/feature-tour/free-roam.js)+ (hand-off to click-to-walk), [src/feature-tour/guide-avatar.js](../../src/feature-tour/guide-avatar.js)+ (guide character), [src/feature-tour/narrator.js](../../src/feature-tour/narrator.js),+ [src/feature-tour/chapters.js](../../src/feature-tour/chapters.js),+ [src/feature-tour/curriculum.js](../../src/feature-tour/curriculum.js),+ [src/feature-tour/spotlight.js](../../src/feature-tour/spotlight.js). App entry:+ [src/feature-tour.js](../../src/feature-tour.js). Page: [pages/tour.html](../../pages/tour.html) (`/tour`).+- **Universal rig pipeline (do not bypass)** — [src/glb-canonicalize.js](../../src/glb-canonicalize.js),+ [src/animation-retarget.js](../../src/animation-retarget.js), gate in+ [src/animation-manager.js](../../src/animation-manager.js) (`supportsCanonicalClips()`).+- **Tests** — [tests/walk-gestures.test.js](../../tests/walk-gestures.test.js),+ [page-agent-sdk/test/catalog.test.js](../../page-agent-sdk/test/catalog.test.js),+ [tests/feature-tour-curriculum.test.js](../../tests/feature-tour-curriculum.test.js).++## Do this++1. **Exercise all three in a real browser** (`npm run dev`, port 3000): load `/walk`,+ click the corner companion to detach into the full-page playground, open the avatar+ picker; load a page with `<page-agent>` (use `page-agent-sdk/examples/index.html`)+ and let it narrate; launch the Feature Tour via `?tour=start` and run it to free-roam+ hand-off. Watch the console and Network tab the whole time — zero errors/warnings.+2. **Every avatar is rigged and animates.** Confirm the Walk roster and the Page-Agent+ catalog only surface rigged GLBs that drive the canonical clip library (idle/walk+ legs included), never a bind-pose T-pose. If a humanoid won't animate, it's a+ bone-name gap — extend [src/glb-canonicalize.js](../../src/glb-canonicalize.js) and+ add a case in `tests/glb-canonicalize.test.js`. Do not hardcode a rig allowlist.+3. **Avatar picker diversity.** Audit `WALK_AVATARS` (roster.js) and the page-agent+ catalog for a genuinely diverse set (skin tones, body types, styles, presentation) —+ not five variants of one model. Make the picker keyboard-navigable, focus-trapped,+ with hover/active/focus states and a designed empty/loading state if a GLB fails.+4. **Every state designed for each surface:** companion loading (skeleton, not a dead+ sprite), playground empty/first-run hint, picker loading/error, narrator+ caption-while-speaking + muted state, tour loading/paused/finished/exit-confirm.+ No fake `setTimeout` progress bars — real asset-load progress only.+5. **Mode hand-offs never break.** Companion → playground detach, playground → page+ navigation persistence ([src/walk-companion.js] transitions), Tour director →+ `free-roam.js` click-to-walk and back. Verify each transition leaves no orphaned+ canvas, listener, or animation loop (check for leaked `requestAnimationFrame`).+6. **Performance.** Lazy-load three.js and avatar GLBs; cap the playground/companion+ frame budget; pause render loops when the tab is hidden or the element is offscreen+ (IntersectionObserver). Confirm no layout thrash and a smooth 60fps on a mid-range+ device profile (DevTools Performance trace).+7. **Embed integrity.** The `/walk-embed` code generator and the `<page-agent>` script+ tag must produce working, copy-pasteable snippets that load from the published+ package paths — exercise the generated snippet in a blank HTML file.+8. **Accessibility & resilience.** ARIA labels on companion/picker/tour controls,+ `prefers-reduced-motion` respected (reduce idle sway, no auto-walk), and a missing+ avatar/manifest falls back gracefully (next roster entry) instead of a blank canvas.+9. **Run the tests:** `npx vitest run tests/walk-gestures.test.js+ tests/feature-tour-curriculum.test.js page-agent-sdk/test/catalog.test.js`. Add+ cover for any failure mode you fixed (GLB load failure, picker empty, tour exit).+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` bone maps for any new+ skeleton instead, and never ship a T-posed humanoid.+- Do not break the existing companion/playground/tour code paths while polishing — add+ to unprotected paths, don't refactor working logic for its own sake.+- Do not ship a fake progress bar, a render loop that runs while the tab is hidden, or+ a picker that lists unrigged/missing avatars.+- Do not leave a broken mode hand-off, orphaned canvas, or leaked animation loop.+- Do not reference any coin other than `$THREE` in copy, narration, or sample data.++## Acceptance (all true before claiming done)++- [ ] `/walk` companion, full-page playground, and avatar picker all work in a real+ browser with no console errors/warnings; detach + page-navigation persistence work.+- [ ] `<page-agent>` mounts from the example, narrates with live captions and a muted+ state, and offers a rigged-only, diverse, keyboard-navigable picker.+- [ ] Feature Tour runs end-to-end (`?tour=start` → chapters → free-roam hand-off →+ exit), with loading/paused/finished/exit-confirm states designed.+- [ ] Every surfaced avatar is rigged and animates (no unjustified T-pose); any new+ skeleton convention added to `glb-canonicalize.js` with a test case.+- [ ] Loading/empty/error states designed across all three; no fake progress bars;+ render loops pause when hidden/offscreen; 60fps on a mid-range profile.+- [ ] The `/walk-embed` snippet and the `<page-agent>` script tag work pasted into a+ blank page.+- [ ] `prefers-reduced-motion` and ARIA/keyboard support verified.+- [ ] Listed tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/production-1b/20-scene-animation-studio.md b/prompts/production-1b/20-scene-animation-studio.mdnew file mode 100644index 000000000..d882886d6--- /dev/null+++ b/prompts/production-1b/20-scene-animation-studio.md@@ -0,0 +1,124 @@+# 20 — Scene Studio & Animation Studio++> 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++Creators don't just want an avatar — they want to *stage* it and *make it move*. Scene+Studio (import GLBs, compose a scene, edit materials/lights, export) and Animation+Studio (pose with IK, keyframe a timeline, export an animated GLB you can sell) are+the surfaces that turn three.ws from a generator into a creation tool — the moment a+user makes something they own and can list for USDC. A pro-grade editor that imports+cleanly, never loses work, and exports a sellable artifact is what makes three.ws a+platform creators return to, not a one-shot toy.++## Mission++Make Scene Studio and Animation Studio production-grade: clean GLB import, real+material/light editing, IK posing and a keyframe timeline that exports a valid+animated GLB, every state designed, and a working path from "animate" to "list for+sale" — all on the universal canonical-rig pipeline.++## Map (trust but verify — files move)++- **Scene Studio (`/scene`)** — [pages/scene.html](../../pages/scene.html) (host page),+ [src/scene-studio/main.js](../../src/scene-studio/main.js) (entry, mounts the editor),+ [src/scene-studio/studio.css](../../src/scene-studio/studio.css) (chrome).+ Vendored three.js r184 editor under [src/scene-studio/vendor/](../../src/scene-studio/vendor)+ — read [src/scene-studio/vendor/README.md](../../src/scene-studio/vendor/README.md)+ for the re-vendoring rules and local mods. Static decoder/lib assets ship under+ `public/scene-studio/` (draco, basis, libs, fonts, images).+- **Animation Studio (`/pose`)** — [pages/pose.html](../../pages/pose.html) (host),+ [src/pose-studio.js](../../src/pose-studio.js) (controller: FK gizmos, IK drag,+ timeline, export UI), [src/pose-animation.js](../../src/pose-animation.js) (keyframe+ document + interpolation, bakes `THREE.AnimationClip`), [src/pose-rig.js](../../src/pose-rig.js)+ (rig abstraction + `solveIK()` / `IK_CHAINS`), [src/pose-presets.js](../../src/pose-presets.js).+- **Animation data** — [public/animations/manifest.json](../../public/animations/manifest.json)+ (clip index), [public/animations/clips/](../../public/animations/clips) (retargeted+ JSON clips). Build pipeline: [scripts/build-animations.mjs](../../scripts/build-animations.mjs)+ (Mixamo FBX → retarget → canonical clips), [scripts/fbx-to-glb.mjs](../../scripts/fbx-to-glb.mjs).+- **Animation gallery + selling** — [pages/animations.html](../../pages/animations.html),+ [src/animations-gallery.js](../../src/animations-gallery.js),+ [api/animations/sell.js](../../api/animations/sell.js) (list/delist for sale),+ [api/animations/clips.js](../../api/animations/clips.js) (save/list clips),+ [api/animations/presign.js](../../api/animations/presign.js) (R2 upload),+ [api/x402/animation-download.js](../../api/x402/animation-download.js) (paid download).+- **Universal rig pipeline (the spine of both)** — [src/glb-canonicalize.js](../../src/glb-canonicalize.js)+ (bone-name + up-axis normalization on import), [src/animation-retarget.js](../../src/animation-retarget.js)+ (rebind canonical clips onto any rig).+- **Tests** — [tests/pose-animation.test.js](../../tests/pose-animation.test.js),+ [tests/animation-upright-invariant.test.js](../../tests/animation-upright-invariant.test.js),+ [tests/glb-canonicalize.test.js](../../tests/glb-canonicalize.test.js),+ [tests/animation-retarget.test.js](../../tests/animation-retarget.test.js).++## Do this++1. **Exercise Scene Studio in a real browser** (`npm run dev`): open `/scene`, import a+ GLB (Add → Model), select a mesh, edit a material (color/metalness/roughness) and a+ light, then export the scene as GLB. Re-import the exported file to prove it round-trips+ (meshes, materials, lights survive). Watch console/Network — zero errors/warnings.+2. **Exercise Animation Studio in a real browser:** open `/pose`, load the built-in+ mannequin and a user avatar GLB, pose with FK gizmos and IK drag (grab a hand/foot,+ confirm the chain solves), add timeline keyframes, scrub, then export an animated+ GLB. Re-open the exported GLB in the viewer to confirm it plays.+3. **Import is bulletproof.** Every imported GLB runs through+ [src/glb-canonicalize.js](../../src/glb-canonicalize.js) so arbitrary skeletons+ (Mixamo/Avaturn/VRM/Daz/Blender, etc.) normalize to the canonical set. A humanoid+ that won't pose/retarget is a bone-name gap — extend `glb-canonicalize.js` and add a+ `tests/glb-canonicalize.test.js` case. Never hardcode a rig allowlist; a genuinely+ non-humanoid prop falls back gracefully, not to a broken editor.+4. **Every state designed** for both studios: loading (skeleton/progress on GLB load,+ real bytes not a fake bar), empty (no model yet → "import a GLB to start" with a+ sample), error (bad/corrupt file → actionable message, not a stack trace), and+ overflow (large scene/long timeline stays responsive). Mask any vendor/decoder error.+5. **No lost work.** Confirm the timeline and scene state survive a tab refresh+ (autosave/local persistence) or, if not present, add it. Warn on unload with unsaved+ changes. Undo/redo must work for pose + scene edits.+6. **Export quality.** The exported animated GLB must have a valid `AnimationClip` with+ canonical bone tracks, play upright (no flipped/tilted root — see+ `animation-upright-invariant.test.js`), and carry a real name. The scene export must+ be self-contained (embedded textures/materials/lights).+7. **"Animate → sell" path works end-to-end.** From Animation Studio, save the clip+ ([api/animations/clips.js]), presign + upload the artifact ([api/animations/presign.js]),+ list it for sale ([api/animations/sell.js]) with a USDC price, and confirm it shows+ in the gallery ([pages/animations.html]) with a working preview and an x402 paid+ download ([api/x402/animation-download.js]). No mocks — real R2 + real listing.+8. **Performance & accessibility.** Lazy-load heavy editor modules and decoders; pause+ the render loop when the tab is hidden; keyboard shortcuts for play/pause/keyframe;+ ARIA on timeline controls; `prefers-reduced-motion` respected in previews.+9. **Run the tests:** `npx vitest run tests/pose-animation.test.js+ tests/animation-upright-invariant.test.js tests/glb-canonicalize.test.js+ tests/animation-retarget.test.js`. Cover any failure mode you fixed (bad-GLB import,+ export of an unrigged mesh, IK chain with a missing bone).+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` for new skeletons so+ IK/posing/export work on any humanoid.+- Do not edit the vendored three.js editor upstream files without recording the change+ per `src/scene-studio/vendor/README.md` (the re-vendor must stay reproducible).+- Do not ship a fake progress bar, an export that produces an invalid/upright-flipped+ GLB, or a "sell" flow backed by mocks.+- Do not let a corrupt import or decoder failure surface a raw stack trace or vendor URL.+- Do not reference any coin other than `$THREE` (prices/payments are USDC; never name+ another token).++## Acceptance (all true before claiming done)++- [ ] Scene Studio imports a GLB, edits a material + light, exports a self-contained+ scene GLB that round-trips on re-import — no console errors/warnings.+- [ ] Animation Studio poses with FK + IK, keyframes a timeline, and exports a valid+ animated GLB that plays upright in the viewer.+- [ ] Arbitrary skeletons normalize via `glb-canonicalize.js`; any new convention added+ with a test case; no rig allowlist, no unjustified T-pose.+- [ ] Loading/empty/error/overflow states designed in both studios; vendor/decoder+ errors masked; no fake progress bars.+- [ ] Unsaved-work protection (autosave or unload warning) and undo/redo work.+- [ ] "Animate → save → upload → list for sale → gallery → x402 download" works+ end-to-end with real R2 and real listings.+- [ ] Listed tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/production-1b/21-avatar-creator-character-studio.md b/prompts/production-1b/21-avatar-creator-character-studio.mdnew file mode 100644index 000000000..0cbb145b6--- /dev/null+++ b/prompts/production-1b/21-avatar-creator-character-studio.md@@ -0,0 +1,130 @@+# 21 — Avatar creator / Character Studio / Selfie→avatar++> 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++"Make *me* a 3D avatar" is the most personal thing a user does on three.ws — sculpt a+character from scratch, turn a selfie into a rigged avatar, or describe one in words —+and it's the asset they carry into Walk, Worlds, the marketplace, and their agent+profile. If the creator is clumsy, the selfie pipeline dead-ends, or the result lands+as a frozen T-pose, the user never gets to the "wow, that's me, and it moves"+screenshot that drives sharing. This surface must feel like a real character creator+and always produce a rigged avatar that animates.++## Mission++Make the three avatar-creation paths — Character Studio (sculpt face+body), selfie→avatar,+and prompt→avatar — correct, resilient, and beautifully stated, each producing a+canonical-rigged GLB the user can export and publish to the gallery, all on the+universal rig pipeline (no allowlist).++## Map (trust but verify — files move)++- **Character Studio (full builder)** — [character-studio/](../../character-studio)+ (React/Vite app, MIT fork of m3-org/CharacterStudio — see+ [character-studio/LICENSE](../../character-studio/LICENSE)).+ [character-studio/package.json](../../character-studio/package.json) (`@m3-org/characterstudio`,+ builds to `/avatar-studio/` base), [character-studio/index.html](../../character-studio/index.html).+ Sculpting/body engine under `character-studio/src/library/` (e.g.+ `characterManager.js`, `VRMExporter*.js`). Wrapper page that iframes the studio:+ [pages/avatar-studio.html](../../pages/avatar-studio.html). Routes: `/avatar-studio`,+ `/create/studio` → `avatar-studio.html` (see [vercel.json](../../vercel.json)).+- **Avatar SDK (`@three-ws/avatar`)** — [avatar-sdk/package.json](../../avatar-sdk/package.json)+ (web component `<agent-3d>`; `./creator`, `./viewer`, `./react` subpaths),+ [avatar-sdk/src/creator.js](../../avatar-sdk/src/creator.js) (modal iframe controller ++ presigned upload), [avatar-sdk/src/viewer.js](../../avatar-sdk/src/viewer.js),+ [avatar-sdk/README.md](../../avatar-sdk/README.md).+- **Selfie→avatar / prompt→avatar (UI)** — [pages/create-selfie.html](../../pages/create-selfie.html)+ (`/create/selfie`), [src/selfie-pipeline.js](../../src/selfie-pipeline.js),+ [src/selfie-capture.js](../../src/selfie-capture.js); [pages/create-prompt.html](../../pages/create-prompt.html)+ (`/create/prompt`), [src/create-prompt.js](../../src/create-prompt.js).+- **Reconstruct + auto-rig (backend)** — [api/avatars/_actions.js](../../api/avatars/_actions.js)+ (`reconstruct`, `upload`, `upload-proxy`), [api/avatars/index.js](../../api/avatars/index.js)+ (list/create metadata), [api/avatars/from-forge.js](../../api/avatars/from-forge.js),+ [api/_lib/reconstruct-finalize.js](../../api/_lib/reconstruct-finalize.js) (shared+ tail: canonicalize → rig gate → materialize), [api/_lib/auto-rig.js](../../api/_lib/auto-rig.js),+ [api/_lib/regen-provider.js](../../api/_lib/regen-provider.js).+- **Gallery (publish target)** — [public/gallery/index.html](../../public/gallery/index.html),+ [public/gallery/gallery.js](../../public/gallery/gallery.js),+ [pages/gallery-picker.html](../../pages/gallery-picker.html).+- **Universal rig pipeline (must respect)** — [src/glb-canonicalize.js](../../src/glb-canonicalize.js)+ (bone-name + up-axis normalize at ingest), [src/animation-retarget.js](../../src/animation-retarget.js),+ gate in [src/animation-manager.js](../../src/animation-manager.js)+ (`supportsCanonicalClips()`).+- **Tests** — [tests/api/reconstruct-finalize.test.js](../../tests/api/reconstruct-finalize.test.js),+ [tests/api/avatars-from-forge.test.js](../../tests/api/avatars-from-forge.test.js),+ [tests/glb-canonicalize.test.js](../../tests/glb-canonicalize.test.js).++## Do this++1. **Exercise all three creation paths in a real browser** (`npm run dev`): Character+ Studio at `/avatar-studio` (sculpt a face, adjust body, change an outfit, export+ GLB); `/create/selfie` (capture/upload a photo → rigged avatar); `/create/prompt`+ (describe an avatar → rigged avatar). Watch console/Network — zero errors/warnings.+2. **Every result is canonical-rigged and animates.** Confirm `reconstruct-finalize.js`+ canonicalizes every GLB and the auto-rig gate ([api/_lib/auto-rig.js]) produces a+ skeleton that drives idle/walk (legs included). A humanoid that lands T-posed is a+ bug — fix the bone map in `glb-canonicalize.js` (+ a `tests/glb-canonicalize.test.js`+ case), never hardcode a rig allowlist. Only a genuinely non-humanoid mesh may fall+ back to the default rig via `supportsCanonicalClips()`.+3. **No provider internals reach the user.** Audit every error path in+ [api/avatars/_actions.js], [api/_lib/reconstruct-finalize.js],+ [api/_lib/regen-provider.js], and the selfie/prompt UIs: provider quota/billing,+ raw stack traces, vendor URLs, NSFW/no-face/OOM responses must become neutral,+ actionable copy. Keep raw detail in server logs only.+4. **Every phase is designed.** Selfie capture (camera permission prompt, face-not-found+ hint, retake), reconstruct, and rig each show a live label + real elapsed time ++ progress affordance (not a fake `setTimeout` bar). Empty state tells the user what to+ do; error state says how to recover; Character Studio loading uses a skeleton, not a+ blank canvas.+5. **Resilience.** A hung/throttled provider must time out and either retry or hand off+ (reuse the existing `regen-provider` chain / cockatiel helper), never stall a spinner+ forever. Verify the cascade and add cover for uncovered failure modes (402/429/+ timeout/NSFW/no-face/OOM/unconfigured).+6. **Export + publish path works end-to-end.** From any creation path, export the GLB+ and publish it to the gallery: confirm the avatar appears in+ [public/gallery/index.html](../../public/gallery/index.html) with the correct+ `visibility`, a real thumbnail (not a 1px snapshot), correct rigged/static tagging,+ and an owner-scoped storage key (you can't claim someone else's GLB).+7. **Right input → right path.** Make affordances obvious so a "humanoid" prompt goes+ to the avatar flow (not a box on a non-humanoid pipeline), and the selfie flow guides+ the user to a clear, face-forward photo.+8. **Accessibility, mobile, performance.** Camera/selfie flow works on mobile (320px),+ ARIA on creator controls and the picker, keyboard navigation, lazy-load the heavy+ `<agent-3d>` runtime and Character Studio bundle, and respect `prefers-reduced-motion`+ in previews. Confirm Character Studio's iframe wrapper sizing is responsive.+9. **Run the tests:** `npx vitest run tests/api/reconstruct-finalize.test.js+ tests/api/avatars-from-forge.test.js tests/glb-canonicalize.test.js`. Add cover for+ any failure mode or new bone mapping you fixed.+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not hardcode a rig allowlist — extend `glb-canonicalize.js` bone maps so every+ humanoid animates; never ship a bind-pose T-pose for a riggable humanoid.+- Do not surface any provider's billing page, credit balance, quota, or raw error to the+ user — mask to neutral, actionable copy.+- Do not ship a fake progress bar, a spinner with no timeout, or a "publish" backed by+ mocks/sample arrays.+- Do not let a user claim or overwrite another user's avatar/storage key.+- Do not reference any coin other than `$THREE` in copy, metadata, or sample data.++## Acceptance (all true before claiming done)++- [ ] Character Studio (sculpt), selfie→avatar, and prompt→avatar all complete in a real+ browser with no console errors/warnings; each exports a GLB.+- [ ] Every produced humanoid is canonical-rigged and animates (no unjustified T-pose);+ any new skeleton convention added to `glb-canonicalize.js` with a test case.+- [ ] Every failure mode (402/429/timeout/NSFW/no-face/OOM/unconfigured) yields a+ neutral, actionable message — no vendor internals, verified by tests.+- [ ] Loading/empty/error states designed for all three paths; elapsed time is real; no+ fake progress bars.+- [ ] Export → publish-to-gallery works with a real thumbnail, correct visibility ++ rigged/static tag, and owner-scoped storage.+- [ ] Mobile (320px) selfie flow, ARIA/keyboard support, and lazy-loading verified.+- [ ] Listed tests pass; new failure modes covered.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/production-1b/22-pump-oracle-trading-three.md b/prompts/production-1b/22-pump-oracle-trading-three.mdnew file mode 100644index 000000000..bfb03d373--- /dev/null+++ b/prompts/production-1b/22-pump-oracle-trading-three.md@@ -0,0 +1,145 @@+# 22 — Pump.fun launch, Oracle, trading & $THREE++> 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 token surfaces are where three.ws meets real money and real on-chain stakes:+launch-a-coin, the Launchpad Studio, Coin Intelligence/Radar, the Oracle conviction+engine, the Trader Leaderboard, Smart Money, Arm-your-agent, the Strategy Lab, and the+`$THREE` token page. These pages must show real Solana data, never stall on a flaky+RPC, never leak a provider error — and they must be **flawless on $THREE-only+compliance**, because a single stray ticker in code, copy, or sample data is a+credibility (and legal) failure for the platform's own token.++## Mission++Harden every pump/oracle/trading surface to production: real-data feeds with resilient+RPC, every state designed, no leaked provider internals — and run a strict $THREE-only+compliance audit that confirms the only coin promoted anywhere is `$THREE`+(CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).++## Map (trust but verify — files move)++- **Launch-a-coin** — [pages/launch.html](../../pages/launch.html) (`/launch`),+ [src/pump/launch-token-modal.js](../../src/pump/launch-token-modal.js) (launcher modal).+ Pump backend dispatch: [api/pump/[action].js](../../api/pump/%5Baction%5D.js)+ (`launches`, `snapshot`, etc.), [api/pump/safety.js](../../api/pump/safety.js),+ [api/pump/trending.js](../../api/pump/trending.js).+- **Launchpad Studio (page-builder + CMS)** — [pages/launchpad.html](../../pages/launchpad.html)+ (`/launchpad`), [src/editor/launchpad-studio.js](../../src/editor/launchpad-studio.js)+ (template → live preview → publish to `/p/<slug>`).+- **Platform launch directory (runtime exception — keep)** — [pages/launches.html](../../pages/launches.html)+ (`/launches`, renders coins launched through three.ws over `pump_agent_mints`),+ [pages/launch-detail.html](../../pages/launch-detail.html) (`/launches/<mint>`,+ runtime user-supplied mint).+- **Coin Intelligence / Radar** — [pages/coin-intel.html](../../pages/coin-intel.html)+ (`/coin-intel`), [pages/radar.html](../../pages/radar.html) (`/radar`),+ [src/radar.js](../../src/radar.js), [api/pump/coin-intel.js](../../api/pump/coin-intel.js).+- **Oracle (conviction)** — [pages/oracle.html](../../pages/oracle.html) (`/oracle`),+ [src/oracle.js](../../src/oracle.js), [api/oracle/feed.js](../../api/oracle/feed.js),+ [api/oracle/coin.js](../../api/oracle/coin.js), conviction engine in+ [api/_lib/oracle/conviction.js](../../api/_lib/oracle/conviction.js) (+ `narrative.js`,+ `archetype.js`, `known-wallets.js`, `settle.js` in [api/_lib/oracle/](../../api/_lib/oracle)).+- **Arm-your-agent (trading automation)** — [pages/arm.html](../../pages/arm.html)+ (`/arm`, `/oracle/arm`), [src/arm.js](../../src/arm.js) (reuses `/api/agents`,+ `/api/oracle/watch`, `/api/oracle/test-alert`).+- **Strategy Lab** — [public/strategy-lab.html](../../public/strategy-lab.html)+ (`/strategy-lab`). Sniper dashboard: [src/dashboard-next/pages/sniper.js](../../src/dashboard-next/pages/sniper.js).+- **Trader Leaderboard / Smart Money** — [pages/leaderboard.html](../../pages/leaderboard.html)+ (`/leaderboard`), [src/leaderboard.js](../../src/leaderboard.js),+ [api/_lib/trader-stats.js](../../api/_lib/trader-stats.js);+ [pages/smart-money.html](../../pages/smart-money.html) (`/smart-money`),+ [api/pump/smart-money.js](../../api/pump/smart-money.js).+- **$THREE token page** — [pages/three-token.html](../../pages/three-token.html)+ (`/three-token`), [src/three-token-page.js](../../src/three-token-page.js),+ [api/three-token/[action].js](../../api/three-token/%5Baction%5D.js),+ [src/pump/three-token-data.js](../../src/pump/three-token-data.js) (canonical mint),+ [api/_lib/token/config.js](../../api/_lib/token/config.js).+- **Tests** — [tests/api/granite-oracle.test.js](../../tests/api/granite-oracle.test.js),+ [tests/smart-money.test.js](../../tests/smart-money.test.js),+ [tests/api/pump-curve.test.js](../../tests/api/pump-curve.test.js).++## Do this++1. **Exercise every surface in a real browser** (`npm run dev`): `/launch`, `/launchpad`,+ `/launches` + a `/launches/<mint>` detail, `/coin-intel`, `/radar`, `/oracle`, `/arm`,+ `/strategy-lab`, `/leaderboard`, `/smart-money`, `/three-token`. Watch console/Network+ — zero errors/warnings; every page renders real Solana/pump data, not a placeholder.+2. **Run the $THREE-only compliance audit.** Grep the codebase for any non-`$THREE`+ ticker/symbol or hardcoded mint in code, comments, copy, fixtures, and sample data:+ ```+ grep -rniE '\$[A-Z]{2,6}\b' pages/ src/ api/ public/ | grep -v 'THREE'+ grep -rnoE '[1-9A-HJ-NP-Za-km-z]{32,44}' api/pump api/oracle src/pump src/kol+ ```+ Confirm every hit is one of: the `$THREE` CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`;+ a clearly-synthetic placeholder (`THREEsynthetic1111…`); a Solana utility mint (wSOL+ `So111…112`, USDC `EPjF…Dt1v`); a platform fee / wallet / EVM factory address (not a+ coin); a **runtime user-supplied** mint (launcher input, `/launches/<mint>`); or the+ **platform launch directory** over `pump_agent_mints`. Remove or fix anything that+ markets/recommends/hardcodes another coin. Treat a stray ticker like a leaked secret.+3. **No provider/RPC internals reach the user.** Audit error paths in `api/pump/*`,+ `api/oracle/*`, and `api/_lib/oracle/*`: Helius/RPC/DEX errors, rate-limit bodies,+ raw stack traces, and vendor URLs must become neutral, actionable copy. Keep raw+ detail in server logs only.+4. **Resilient on-chain reads.** Every Solana RPC / pump / Helius call must time out and+ retry/fall back via the existing cockatiel resilience helper — never stall a feed.+ Verify the trending/coin-intel/oracle feeds degrade gracefully when RPC is slow or a+ provider 429s (designed stale/partial state, not a dead spinner).+5. **Every state designed** on each surface: loading (skeleton rows, not spinners),+ empty (e.g. no launches yet, no conviction signals yet → tell the user what's next),+ error (RPC down → "data delayed, retrying" with a retry), and overflow (long lists+ paginated/virtualized; long names truncated). Designed for 0 / 1 / 1000 items.+6. **Launch + arm flows are real and safe.** Confirm `/launch` produces a real pump.fun+ launch (the launcher accepts the runtime mint/params — generic plumbing exception),+ `/launches` lists it, and `/arm` wires conviction-threshold automation through+ `/api/oracle/watch` with real agent state. No fake fills, no mock PnL on the+ leaderboard — `trader-stats.js` must compute from real on-chain history.+7. **$THREE token page integrity.** `/three-token` must read live price/holders/activity+ from real APIs, reference only the canonical mint+ (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`), and degrade gracefully if a feed is+ down. Any "buy/swap" affordance routes to a legitimate runtime-mint swap, never names+ another token.+8. **Accessibility, mobile, performance.** ARIA on tables/controls, keyboard nav,+ responsive at 320/768/1440, lazy-load charts/3D, debounce search inputs, paginate+ large feeds. No layout thrash on live-updating tables.+9. **Run the tests:** `npx vitest run tests/api/granite-oracle.test.js+ tests/smart-money.test.js tests/api/pump-curve.test.js`. Add cover for any RPC-failure+ or error-masking path you fixed; add a test asserting no non-`$THREE` ticker appears+ in shipped copy/fixtures if a gap exists.+10. Add a `data/changelog.json` entry for any user-visible change and run+ `npm run build:pages`.++## Must-not++- Do not mention, hardcode, link, render, or recommend any coin other than `$THREE`+ anywhere — code, comments, copy, fixtures, sample data, or commit message. The only+ two exceptions are runtime user-supplied mints (launcher input, `/launches/<mint>`)+ and the platform launch directory over `pump_agent_mints`. Never paste a real+ non-`$THREE` mint/creator/holder address into tests or fixtures.+- Do not surface a raw RPC/Helius/DEX/provider error, rate-limit body, or vendor URL to+ the user.+- Do not ship a feed with no timeout/fallback, a fake-loading bar, or mock PnL/fills.+- Do not break the working pump/oracle data paths while hardening — add to unprotected+ paths, prefer the existing cockatiel helper over hand-rolled retries.++## Acceptance (all true before claiming done)++- [ ] All token surfaces render real Solana/pump data in a real browser with no console+ errors/warnings: `/launch`, `/launchpad`, `/launches`(+detail), `/coin-intel`,+ `/radar`, `/oracle`, `/arm`, `/strategy-lab`, `/leaderboard`, `/smart-money`,+ `/three-token`.+- [ ] $THREE-only audit clean: every ticker/mint in code, copy, and fixtures is `$THREE`,+ a synthetic placeholder, a utility mint/wallet, a runtime user-supplied mint, or+ the `pump_agent_mints` launch directory. No other coin promoted anywhere.+- [ ] Every provider/RPC failure yields neutral, actionable copy — no internals leaked.+- [ ] Feeds are resilient (timeout + retry/fallback via cockatiel) and degrade gracefully+ under slow/429 RPC.+- [ ] Loading/empty/error/overflow states designed across all surfaces (0/1/1000 items).+- [ ] Launch, arm, leaderboard, and $THREE token data are real (no mock fills/PnL); the+ $THREE page references only the canonical mint.+- [ ] ARIA/keyboard, responsive 320/768/1440, and lazy-loading verified.+- [ ] Listed tests pass; new RPC-failure / compliance coverage added where there was a gap.+- [ ] Changelog updated and `npm run build:pages` is clean.diff --git a/prompts/production-1b/26-observability.md b/prompts/production-1b/26-observability.mdnew file mode 100644index 000000000..51667ed9d--- /dev/null+++ b/prompts/production-1b/26-observability.md@@ -0,0 +1,96 @@+# 26 — Observability (logging, metrics, error tracking)++> 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 scale what you cannot see. When the Forge hangs, a payment silently+fails, or a cron stops firing at 3am, the difference between a five-minute fix and+a five-hour outage is whether the right structured log, metric, and alert already+exist. At $1B scale every minute of operator blindness is revenue, trust, and+$THREE-holder confidence bleeding out. Observability is the nervous system that lets+a small team run a large platform.++## Mission++Make every hot path emit structured, correlated, PII-free logs; record metrics on+generation/payment/RPC paths; and ensure every server error reaches Sentry + a+deduped ops alert with a traceable ref — without leaking secrets or vendor internals.++## Map (trust but verify — files move)++- **Client logger** — [src/shared/log.js](../../src/shared/log.js) — gated logger+ (`error` always emits; `warn/info/debug` gated by DEV / `?debug` / `localStorage['tws:debug']`),+ exports `log` + `createLogger(tag)`.+- **HTTP boundary + correlation IDs** — [api/_lib/http.js](../../api/_lib/http.js) —+ `correlationId()`, `serverError()` (emits `[server-error <ref>]`, calls Sentry + alert),+ `wrap()`, and `redactUrl()` which strips `lat/lng/token/devicetoken` before logging.+- **Generation metrics** — [api/_lib/forge-events.js](../../api/_lib/forge-events.js) —+ `recordGenerationEvent()` (JSON line `evt:"forge_gen"` + Redis hourly rolling counters),+ `readGenerationMetrics()`; consumed by [api/_lib/forge-health.js](../../api/_lib/forge-health.js).+- **Payment/business metrics** — [api/_lib/axiom.js](../../api/_lib/axiom.js) —+ `recordPaymentMetric()`, `ingestEvent()` (no-op when `AXIOM_TOKEN`/`AXIOM_DATASET` unset).+- **Error tracking** — [api/_lib/sentry.js](../../api/_lib/sentry.js) —+ `captureException()`, `captureMessage()` (fetch-based envelope, 2.5s abort, no-op without `SENTRY_DSN`).+- **Ops alerts** — [api/_lib/alerts.js](../../api/_lib/alerts.js) — `sendOpsAlert(title, detail, opts)`,+ per-signature dedup (1h) + 20/hr global ceiling (Telegram).+- **x402 audit trail** — [api/_lib/x402/audit-log.js](../../api/_lib/x402/audit-log.js).+- **Tests** — [tests/api/healthz.test.js](../../tests/api/healthz.test.js),+ [tests/api/forge-health.test.js](../../tests/api/forge-health.test.js),+ [tests/api/audit-log.test.js](../../tests/api/audit-log.test.js).++## Do this++1. **Inventory the boundaries.** Read `http.js` end-to-end. Confirm every `api/`+ handler that can 5xx routes through `serverError()`/`wrap()` so it gets a `ref`,+ a Sentry capture, and an alert. Grep for raw `res.status(500)` /+ `console.error` that bypass the boundary and route them through `http.js`.+2. **Standardize log levels.** Audit `console.*` calls across `api/` and `src/`.+ Client code must use `src/shared/log.js` (no raw `console.log` shipping to prod);+ server code emits one structured JSON line per significant event with a stable+ `evt` key (mirror `forge_gen`). No free-text-only logs on hot paths.+3. **PII/secret redaction is non-negotiable.** Extend `redactUrl()` and any log+ payload builder to strip wallet secrets, bearer tokens, API keys, email, and+ precise geo. Add a test asserting a crafted error with a token in the URL ++ body never appears verbatim in the logged/captured payload.+4. **Metrics on hot paths.** Confirm `recordGenerationEvent()` fires on every forge+ lifecycle phase (start/done/failed). Wire `recordPaymentMetric()` (Axiom) on+ every x402 settle/verify/refund outcome if any path is missing it. These must be+ fail-open (a metrics hiccup never blocks the request).+5. **Correlation end to end.** Ensure the `ref` from `serverError()` is returned in+ the JSON error body AND attached to the Sentry/alert context, so a support ref+ maps to one log line. Add `ref` to the user-facing error copy where surfaced.+6. **Alert hygiene.** Verify `sendOpsAlert` dedup + 20/hr ceiling work (read+ `alerts.js`); confirm health crons (`world-health`, `redis-health`, `llm/health`)+ alert on degradation, not on every probe. No alert storms.+7. **Verify graceful no-op.** With `SENTRY_DSN`, `AXIOM_TOKEN`, and+ `TELEGRAM_*` unset locally, the whole stack must stay silent and non-throwing.+ Run the relevant tests and a local request to confirm.+8. Run `npx vitest run tests/api/healthz.test.js tests/api/forge-health.test.js+ tests/api/audit-log.test.js` plus any new redaction test. Add a `data/changelog.json`+ entry only if a user-visible surface changed (e.g. a `ref` shown on error pages),+ then `npm run build:pages`.++## Must-not++- Never log secrets, private keys, bearer tokens, raw wallet payloads, full emails,+ or precise geo — redact at the boundary.+- Never surface a vendor's billing/credit/quota message or raw stack to an end user;+ raw detail lives in server logs and Sentry only.+- Never make a request block on a metrics/alert/Sentry call — all are fire-and-forget.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror).+- No mocks, stubs, or TODOs; finish every path you touch. The only coin is `$THREE`.++## Acceptance (all true before claiming done)++- [ ] Every 5xx in `api/` produces a correlation `ref`, a Sentry capture, and a+ deduped ops alert; the same `ref` is in the response body and the log line.+- [ ] Hot paths (forge phases, x402 settle/verify/refund) emit structured metrics;+ all metric/alert/Sentry calls are fail-open and non-blocking.+- [ ] A redaction test proves tokens/secrets/PII never appear in logged or captured+ payloads (URL and body).+- [ ] With all observability env vars unset, the stack is silent and never throws.+- [ ] `tests/api/healthz`, `forge-health`, `audit-log` and any new test pass.+- [ ] Changelog updated only if user-visible; `npm run build:pages` is clean.diff --git a/prompts/production-1b/27-database-integrity-migrations.md b/prompts/production-1b/27-database-integrity-migrations.mdnew file mode 100644index 000000000..216ce0efb--- /dev/null+++ b/prompts/production-1b/27-database-integrity-migrations.md@@ -0,0 +1,94 @@+# 27 — Database integrity & migrations++> 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 database holds money truth: payment intents, agent revenue, skill licenses,+launch records. One non-idempotent migration that half-applies, one missing unique+index that lets a payment double-settle, or one unindexed hot query that table-scans+under load can corrupt balances or take the platform down during the exact traffic+spike you wanted. At $1B, schema discipline is the floor that everything else stands+on — it must be boringly safe, forward-only, and reversible.++## Mission++Guarantee every migration is idempotent and forward-safe, every hot query is indexed+and constrained, money paths are protected by unique/FK constraints, and no+destructive change ships without a backup — with retry and timeouts on the Neon client.++## Map (trust but verify — files move)++- **Migrations** — [api/_lib/migrations/](../../api/_lib/migrations) — ~134 `.sql`+ files (mixed `001_`, dated, and `YYYYMMDDHHMMSS_` naming). Idempotency via+ `CREATE TABLE/INDEX IF NOT EXISTS` and `DO $$ … EXCEPTION WHEN duplicate_object`.+- **Base schema** — [api/_lib/schema.sql](../../api/_lib/schema.sql) — ~1900 lines,+ `pgcrypto`/`citext`, fully idempotent (`IF NOT EXISTS` everywhere).+- **Neon client** — [api/_lib/db.js](../../api/_lib/db.js) — `@neondatabase/serverless`+ HTTP driver, lazy init, composable SQL fragments with placeholder renumbering.+- **Retry helper** — [api/_lib/db-retry.js](../../api/_lib/db-retry.js) — `withDbRetry`,+ 3 attempts, retries transient connection errors only (never SQLSTATE constraint errors).+- **Migration runner** — [scripts/apply-migrations.mjs](../../scripts/apply-migrations.mjs) —+ dry-run by default (`--apply` to write), `schema_migrations` ledger (filename + SHA-256),+ drift detection (refuses if a hash changed), `Pool` for multi-statement files.+ Scripts: `npm run db:status` (dry) / `npm run db:migrate` (apply).+- **Money-path examples** —+ [api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql](../../api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql)+ (anti-replay unique tx_hash),+ [api/_lib/migrations/20260621120000_revenue-integrity.sql](../../api/_lib/migrations/20260621120000_revenue-integrity.sql)+ (partial unique index + CHECK via DO/EXCEPTION).+- **Tests** — [tests/db-sql-compose.test.js](../../tests/db-sql-compose.test.js)+ (fragment placeholder renumbering), [tests/db-retry.test.js](../../tests/db-retry.test.js).++## Do this++1. **Establish the truth.** Run `npm run db:status` to see applied vs pending and+ confirm the `schema_migrations` ledger + drift detection work. Never edit a+ migration that has already applied (it breaks the SHA-256 drift guard) — add a+ new forward migration instead.+2. **Idempotency sweep.** Grep every file under `api/_lib/migrations/` for+ `CREATE TABLE`/`CREATE INDEX`/`ADD CONSTRAINT`/`ADD COLUMN` lacking+ `IF NOT EXISTS` or a `DO $$ … EXCEPTION` guard. Each must be safe to re-run on a+ DB that already has the object. Fix any that aren't (new migration if already applied).+3. **Hot-query indexes.** Identify the most-read tables (payments/intents, agent+ revenue, launches, marketplace, feeds). For each frequent `WHERE`/`ORDER BY`/`JOIN`,+ confirm a supporting index exists; add `CREATE INDEX IF NOT EXISTS` (use partial+ indexes where a column is nullable, mirroring the revenue-integrity pattern).+4. **Constraints on money paths.** Verify unique constraints prevent double-settle+ (e.g. one intent per on-chain tx_hash) and that foreign keys tie child rows to+ their owners. Add missing UNIQUE/FK/CHECK via the `DO $$ … EXCEPTION WHEN+ duplicate_object THEN NULL; END $$;` idempotent pattern.+5. **No destructive change without a backup.** Audit migrations for `DROP TABLE`,+ `DROP COLUMN`, `TRUNCATE`. For any new destructive op, require an explicit Neon+ branch/snapshot first and document the rollback; prefer additive deprecation+ (rename-then-drop in a later release) over in-place drops.+6. **Client safety.** Confirm money/critical reads/writes go through `withDbRetry`.+ Add a request-level query timeout (`Promise.race` against a bounded deadline)+ around long DB calls so a stalled Neon connection can't hang a serverless+ function past its limit. Keep retry classification (transient vs constraint) intact.+7. **Split-safety.** The runner splits multi-statement files on bare `;` at line+ ends — verify any new migration with `DO $$`/dollar-quoted bodies still parses+ (test against `db:status`), and that statements are individually idempotent.+8. Run `npx vitest run tests/db-sql-compose.test.js tests/db-retry.test.js`, then+ `npm run db:status` to confirm a clean, applied-or-pending state. Add a+ `data/changelog.json` entry only if a user-visible behavior changed; `npm run build:pages`.++## Must-not++- Never edit an already-applied migration — it trips the drift guard; add a forward one.+- Never ship `DROP`/`TRUNCATE`/`DROP COLUMN` without a Neon snapshot + documented rollback.+- Never make a migration non-idempotent; assume it may re-run on a partially-applied DB.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror).+- No mocks, stubs, or TODOs. The only coin is `$THREE` — no other mint in fixtures/seeds.++## Acceptance (all true before claiming done)++- [ ] `npm run db:status` shows a clean ledger; drift detection verified working.+- [ ] Every migration is idempotent (`IF NOT EXISTS` / `DO $$ … EXCEPTION`), safe to re-run.+- [ ] Hot tables have indexes covering their frequent `WHERE`/`ORDER BY`/`JOIN`.+- [ ] Money paths carry unique + FK + CHECK constraints (e.g. no double-settle per tx).+- [ ] No destructive migration lacks a backup/rollback plan; additive deprecation preferred.+- [ ] Critical DB calls use `withDbRetry` and a bounded query timeout.+- [ ] `db-sql-compose` and `db-retry` tests pass; changelog updated only if user-visible.diff --git a/prompts/production-1b/28-deploy-pipeline-rollback.md b/prompts/production-1b/28-deploy-pipeline-rollback.mdnew file mode 100644index 000000000..6e5e89328--- /dev/null+++ b/prompts/production-1b/28-deploy-pipeline-rollback.md@@ -0,0 +1,92 @@+# 28 — Deploy pipeline & rollback safety++> 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 handling real money and real assets must be able to ship safely and undo+instantly. The single worst footgun in this repo is `npx vercel build` rewriting+`api/*.js` source files in place with esbuild bundles — committing one corrupts the+backend silently. Add a missed cron registration, a desync between the two git+remotes, or a deploy with no fast rollback, and a routine push becomes an outage.+At $1B, deploys must be a non-event: gated, verified, mirrored, and reversible.++## Mission++Harden the deploy path so a bundled `api/` file can never reach `main`, the deploy+audit + build gates always run, crons stay in sync with their handlers, both git+remotes stay aligned, and rollback is one documented command away.++## Map (trust but verify — files move)++- **Bundle guard** — [scripts/check-api-not-bundled.mjs](../../scripts/check-api-not-bundled.mjs) —+ scans first 4096 bytes of every `api/**/*.js` for `__defProp`, `createRequire(`,+ `__toESM(`, `__toCommonJS(`; exits non-zero with `git restore -- api/ public/` recovery hint.+- **Deploy artifact audit** — [scripts/audit-deploy-artifacts.mjs](../../scripts/audit-deploy-artifacts.mjs) —+ catches committed symlinks + unsatisfied peers + undeclared `api/` imports. Run `npm run audit:deploy`.+- **Build orchestrator** — [scripts/build-vercel.mjs](../../scripts/build-vercel.mjs) —+ 5-phase build; phase 1 gates on `audit:deploy`, `test:gate`, `verify:solana`,+ `verify:onchain`, `audit:mcp`. Run `npm run build:vercel`.+- **Vercel config** — [vercel.json](../../vercel.json) — `routes`, `functions`, `headers`,+ `env`, and `crons` (~46 cron entries). Cron handlers live in [api/cron/](../../api/cron).+- **CI** — [.github/workflows/ci.yml](../../.github/workflows/ci.yml) — jobs: **lint**+ (`eslint .`), **test** (`vitest run`), **guards** (`check-api-not-bundled.mjs`,+ `check:images`, `build:pages`), **typecheck** (advisory, continue-on-error).+- **Tests** — [tests/deploy-artifacts.test.js](../../tests/deploy-artifacts.test.js).+- **Git remotes** — `origin` → `nirholas/three.ws` (canonical), `threeD` →+ `nirholas/3D-Agent` (push-only mirror). Per `/CLAUDE.md`, every push goes to BOTH.++## Do this++1. **Prove the bundle guard.** Read `check-api-not-bundled.mjs`. Confirm it runs in+ CI (guards job) and as a build gate. Before any large `api/` commit, run+ `node scripts/check-api-not-bundled.mjs` and `head -1` changed files for+ `__defProp`/`createRequire`; recover with `git restore -- api/ public/`. Add a+ `pre-commit`/local check note if not already enforced.+2. **Run the deploy audit.** `npm run audit:deploy` — fix any symlink, peer-dep, or+ undeclared-import finding it reports. This is the gate that caught the 2026-06-11+ outage class; it must pass clean.+3. **Cron registration sanity.** There is no validator that `vercel.json` crons map+ 1:1 to `api/cron/*` handlers (the counts differ because some handlers serve+ multiple schedules). Write/extend a script that, for every `crons[].path` in+ `vercel.json`, asserts a resolvable handler exists under `api/`, and flags any+ `api/cron/*` handler with no schedule. Wire it into the guards CI job.+4. **Verify the build gates fire.** Run `npm run build:vercel` (or inspect phase 1)+ and confirm `audit:deploy`, `test:gate`, `verify:solana`, `verify:onchain`,+ `audit:mcp` all run and that RPC-dependent verifies degrade to warnings (never+ hard-fail) when an RPC is down — a flaky RPC must not block a deploy.+5. **Dual-remote discipline.** Document and (where possible) script that every push+ goes to `origin` AND `threeD` in the same step; never force-push without explicit+ request; NEVER pull/fetch/merge from `threeD`. Surface an error if the two+ remotes' `main` diverge rather than silently leaving them out of sync.+6. **Rollback runbook.** Document the fast rollback: `vercel rollback` (or promote a+ prior production deployment in the Vercel dashboard) plus `git revert` using a+ NEUTRAL commit message (never echo the reverted title, per `/CLAUDE.md`). Capture+ how to re-point both remotes after a revert.+7. **Preview deploys.** Confirm preview/PR deployments are isolated from production+ data (no prod writes, no prod crons). If any preview can touch prod money/DB,+ gate it behind env separation.+8. Run `npx vitest run tests/deploy-artifacts.test.js`, `npm run audit:deploy`, and+ `node scripts/check-api-not-bundled.mjs`. Add a `data/changelog.json` entry only+ if a user-visible surface changed (deploy hardening is usually internal); if so,+ `npm run build:pages`.++## Must-not++- Never commit a bundled `api/*.js` (esbuild markers in the first bytes) — guard + recover.+- Never pull/fetch/merge from `threeD`; it is a push-only mirror. Push to BOTH remotes.+- Never force-push to either remote without an explicit request.+- Never let an RPC outage hard-block a deploy — verify steps degrade to warnings.+- No mocks, stubs, or TODOs in the pipeline scripts. The only coin is `$THREE`.++## Acceptance (all true before claiming done)++- [ ] `check-api-not-bundled.mjs` passes; documented recovery is `git restore -- api/ public/`.+- [ ] `npm run audit:deploy` passes clean (no symlink/peer/undeclared-import findings).+- [ ] A cron-sync check asserts every `vercel.json` cron has a handler (and flags orphans), wired into CI.+- [ ] Build gates run and RPC-dependent verifies degrade to warnings when RPC is down.+- [ ] Dual-remote push discipline is documented/scripted; divergence is surfaced, not hidden.+- [ ] A fast rollback runbook exists (Vercel promote/rollback + neutral-message revert).+- [ ] `deploy-artifacts` test passes; changelog updated only if user-visible.diff --git a/prompts/production-1b/29-uptime-status-page.md b/prompts/production-1b/29-uptime-status-page.mdnew file mode 100644index 000000000..12d949612--- /dev/null+++ b/prompts/production-1b/29-uptime-status-page.md@@ -0,0 +1,90 @@+# 29 — Uptime monitoring & public status page++> 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 currency of a money-moving platform. When something breaks, users and+$THREE holders need a single honest place that tells them what's up, what's degraded,+and that the team already knows — before they tweet. A polished public status page+with real uptime history converts incidents from credibility losses into proof of+operational maturity. And external monitoring is the smoke detector that pages the+team even when the platform is too down to alert itself.++## Mission++Aggregate every health probe into one `/api/status` feed backing a public `/status`+page with real 90-day uptime history, wire external (off-box) uptime monitoring, and+ensure degradation pages the team via the existing ops-alert channel.++## Map (trust but verify — files move)++- **Public status page** — [pages/status.html](../../pages/status.html) — live+ dashboard, 90-day uptime bars, auto-polls `/api/status` every 5 min. Registered in+ [data/pages.json](../../data/pages.json) (`/status`, section "learn").+- **Status feed** — `api/status.js` (powers the page; verify path under [api/](../../api)).+- **Aggregate health** — [api/healthz.js](../../api/healthz.js) — probes Resend,+ x402 facilitator, SIWX payments table, bot heartbeat, alert watches.+- **Forge health** — [api/_lib/forge-health.js](../../api/_lib/forge-health.js)+ (served via `GET /api/forge?health`) — probes generation backends + Redis + world.+- **Admin probes** — [api/admin/redis-health.js](../../api/admin/redis-health.js),+ [api/admin/pump-cron-health.js](../../api/admin/pump-cron-health.js).+- **Health crons** — [api/cron/world-health.js](../../api/cron/world-health.js),+ `api/cron/uptime-check.js`, [api/llm/health.js](../../api/llm/health.js).+- **Ops alerts** — [api/_lib/alerts.js](../../api/_lib/alerts.js) — `sendOpsAlert()`,+ deduped + 20/hr ceiling (Telegram).+- **Nav** — [public/nav-data.js](../../public/nav-data.js) (`NAV_GROUPS`, single+ source of truth for menu items), [public/nav.js](../../public/nav.js).+- **Tests** — [tests/api/healthz.test.js](../../tests/api/healthz.test.js),+ [tests/api/forge-health.test.js](../../tests/api/forge-health.test.js).++## Do this++1. **Exercise what exists.** Open `/status` in a real browser (`npm run dev`) and+ hit `/api/status`. Confirm the page polls every 5 min, renders per-service dots,+ 90-day bars, and the "warming-up" first-deploy state. Note any probe missing.+2. **Make the feed complete.** Ensure `/api/status` aggregates ALL subsystems:+ `healthz` (Resend/x402/DB/heartbeat/watches), `forge?health` (gen backends + Redis+ + world), redis-health, pump-cron-health, world-health, llm/health. Add any+ probe that the public page should reflect; admin-gated probes feed status via the+ server (the public response must never leak admin detail or secrets).+3. **Real history, not synthetic.** Verify the 90-day uptime data is recorded from+ actual probe results (a cron writing samples to Redis/DB), not faked. If history+ storage is thin, persist each `uptime-check` result with a retention window so the+ bars reflect truth. No `setTimeout` fake data.+4. **Every state designed.** Confirm `/status` has designed loading, warming-up+ (no history yet), all-operational, degraded, and down states — accessible,+ responsive at 320/768/1440, with hover/focus on interactive elements.+5. **External monitoring.** Wire an off-box uptime monitor (e.g. an+ UptimeRobot/BetterStack/Checkly HTTP check, or a free cron-job.org ping) against+ `/api/healthz` and `/api/status` that pages the team independently of Vercel.+ Document the config and the alert destination. Do not invent a fake integration —+ set up a real one or document the exact steps + env to enable it.+6. **Degradation pages the team.** Confirm the health crons call `sendOpsAlert` on+ degradation only (not every probe), respecting dedup + the 20/hr ceiling — no+ alert storms. Add alerting for any subsystem currently probed-but-silent.+7. **Discoverability.** Add `/status` to `public/nav-data.js` (footer/utility group)+ and link it from error pages and the footer so users can find it when things break.+8. Run `npx vitest run tests/api/healthz.test.js tests/api/forge-health.test.js`,+ exercise `/status` in the browser (no console errors), then add a+ `data/changelog.json` entry (status page improvements are user-visible) and+ `npm run build:pages`.++## Must-not++- Never expose admin-only health detail, internal URLs, or secrets in the public `/api/status`.+- Never fake uptime history with `setTimeout` or hardcoded bars — record real samples.+- Never let the public page flip top-level "operational" to red on a single flaky probe — debounce.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror).+- No mocks, stubs, or TODOs. The only coin is `$THREE`.++## Acceptance (all true before claiming done)++- [ ] `/api/status` aggregates all subsystem probes; the public response leaks no admin detail/secrets.+- [ ] `/status` renders real 90-day history from recorded samples; loading/warming/degraded/down states designed.+- [ ] An external, off-box uptime monitor pings `/api/healthz` + `/api/status` and pages the team (real config documented).+- [ ] Health crons alert via `sendOpsAlert` on degradation only, respecting dedup + ceiling.+- [ ] `/status` is reachable from nav + footer + error pages; no console errors; responsive + accessible.+- [ ] `healthz` and `forge-health` tests pass; changelog updated and `npm run build:pages` clean.diff --git a/prompts/production-1b/30-load-stress-testing.md b/prompts/production-1b/30-load-stress-testing.mdnew file mode 100644index 000000000..139efd142--- /dev/null+++ b/prompts/production-1b/30-load-stress-testing.md@@ -0,0 +1,95 @@+# 30 — Load & stress testing++> 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 day a launch goes viral is the day you find out whether the platform holds. If+the Forge GPU budget, the x402 verify path, or the public feeds buckle under a+traffic spike — or worse, if a spike silently burns the entire monthly Redis command+budget in a day — the moment you waited for becomes the outage that defines you. You+cannot guess capacity at $1B; you measure it, find the breaking point on purpose in a+safe lane, and prove the rate-limits and budgets hold before real users arrive.++## Mission++Identify the hottest and most-expensive endpoints, script realistic load tests+(k6/artillery) against a non-production target, prove the rate-limits and Redis+budget hold at their designed ceilings, find the breaking points, and document capacity.++## Map (trust but verify — files move)++- **Hottest endpoints** — [api/forge.js](../../api/forge.js) (text→3D, GPU-bound),+ [api/x402-checkout.js](../../api/x402-checkout.js) + [api/x402/forge.js](../../api/x402/forge.js)+ (payment prepare/verify), [api/feed.js](../../api/feed.js) ++ [api/feed-stream.js](../../api/feed-stream.js) + [api/trades/feed.js](../../api/trades/feed.js)+ (read-heavy, polled).+- **Rate limiting** — [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js) — Upstash+ sliding-window (in-memory fallback for dev/tests); ~80+ named buckets; critical+ (money) buckets fail CLOSED, non-critical reads fail OPEN; `local: true` buckets+ never consume Redis. Key ceilings: `forge_paid_global_hourly` (600/h),+ `x402_verify_global_per_hour` (12000/h), `mcp3dGenerate` (30/h), `publicIp` (60/min).+- **Redis budget** — [api/_lib/redis-usage.js](../../api/_lib/redis-usage.js) —+ `REDIS_MONTHLY_BUDGET = 500_000` (Upstash free tier), warn 80% / crit 90%; daily ≈16,667.+- **x402 paid endpoint plumbing** — [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js).+- **Existing smokes (not load tests)** — [scripts/onchain-smoke.mjs](../../scripts/onchain-smoke.mjs)+ (`npm run smoke:onchain`), [scripts/smoke-mcp-remotes.mjs](../../scripts/smoke-mcp-remotes.mjs)+ (`npm run smoke:mcp`), [scripts/smoke-api-endpoints.mjs](../../scripts/smoke-api-endpoints.mjs).+- **Env** — [.env.example](../../.env.example) — `UPSTASH_REDIS_REST_URL/TOKEN`,+ `FORGE_PAID_GLOBAL_HOURLY`, `X402_VERIFY_GLOBAL_PER_HOUR` overrides.++> No load-test tooling exists yet — this is net-new. Add it under `scripts/` (or a+> new `loadtest/` dir) and an npm script; do not pollute the repo root.++## Do this++1. **Rank by cost and heat.** From the map, classify endpoints into GPU-bound+ (forge), money-path (x402 checkout/verify), and read-heavy (feeds, status,+ marketplace). Read `rate-limit.js` to record the exact ceiling for each so tests+ target the designed limit, not an arbitrary number.+2. **Pick the tool, add it cleanly.** Adopt k6 (preferred) or artillery as a+ dev/CI dependency. Create `loadtest/` (or `scripts/load/`) with one script per+ class: `forge.js`, `x402.js`, `feeds.js`. No scratch files in the repo root.+3. **Target a safe environment.** Run against a preview/staging deploy or a local+ `npm run dev`, NEVER production money paths. For x402, drive the 402 price-discovery+ and verify amplification path with synthetic/declined payments — never settle real+ funds, never use a non-`$THREE` mint.+4. **Prove the limiters hold.** Push each endpoint to and past its bucket ceiling;+ assert that critical money buckets fail CLOSED (reject, not melt) and read buckets+ fail OPEN/degrade. Confirm 429s are returned with correct `Retry-After`-style copy+ and no 5xx storms.+5. **Watch the Redis budget.** While a feeds/status load test runs, sample+ `redis-usage.js` accounting. Confirm high-frequency cheap reads use `local: true`+ buckets (per the June-2026 quota-burn incident) so a spike does not torch the+ 500k/month budget. Flag any hot read that hits Redis on every request.+6. **Find the breaking point.** Ramp concurrency until p95 latency or error rate+ crosses an SLO (define one, e.g. p95 < 1s for reads, generation queue bounded).+ Record the knee of the curve per endpoint — that is your capacity number.+7. **Verify autoscaling/queueing holds.** Confirm forge's global hourly circuit+ breaker queues/sheds rather than overrunning the shared GPU budget, and that+ serverless concurrency limits don't cascade into timeouts on dependent calls.+8. Document results: per-endpoint ceiling, observed p50/p95, breaking point, Redis+ cost/request, and recommended limits in a `loadtest/README.md`. Run+ `node scripts/smoke-api-endpoints.mjs` (or `npm run smoke:onchain`) as a sanity+ pass against the safe target. Add a+ `data/changelog.json` entry only if a user-visible limit/behavior changed; `npm run build:pages`.++## Must-not++- Never load-test production money paths or settle real funds; use staging + synthetic payments.+- Never use a non-`$THREE` mint in any test fixture or payload.+- Never leave load scripts or result files in the repo root — `loadtest/` or `scripts/`, gitignore artifacts.+- Do not weaken a working rate-limit just to "pass" a test — the limit is the answer.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror). No mocks/stubs/TODOs.++## Acceptance (all true before claiming done)++- [ ] Endpoints ranked by cost/heat with each target's exact rate-limit ceiling recorded.+- [ ] k6/artillery scripts exist for forge, x402, and feeds, run against staging/local (never prod).+- [ ] At ceiling: critical buckets fail CLOSED, read buckets degrade; 429s correct, no 5xx storms.+- [ ] Redis budget is not torched by a read spike; high-frequency reads use `local` buckets.+- [ ] Breaking point (knee) documented per endpoint against a stated SLO.+- [ ] `loadtest/README.md` records capacity numbers + recommended limits; no artifacts committed.+- [ ] A smoke pass succeeds; changelog updated only if user-visible.diff --git a/prompts/production-1b/31-solana-rpc-onchain-resilience.md b/prompts/production-1b/31-solana-rpc-onchain-resilience.mdnew file mode 100644index 000000000..3f019fff3--- /dev/null+++ b/prompts/production-1b/31-solana-rpc-onchain-resilience.md@@ -0,0 +1,97 @@+# 31 — Solana RPC & on-chain resilience++> 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++Solana is the platform default network — launches, trades, payments, skill licenses,+and $THREE all live on-chain. A single RPC provider throttling or going down must not+take the platform with it, and a charge must never settle twice or charge-then-silently-revert.+On-chain money is unforgiving: at $1B, RPC failover, idempotent settlement, and+provable address parity are the difference between a graceful degrade and an+irreversible loss of funds or trust.++## Mission++Guarantee RPC failover/retry across providers, idempotent on-chain operations,+revert-safe confirmations, verified address/program parity, and graceful degradation+(cached/null reads, clear UI) when RPC is impaired — never a charge into the void.++## Map (trust but verify — files move)++- **RPC connection (canonical)** — [api/_lib/solana/connection.js](../../api/_lib/solana/connection.js) —+ `solanaConnection()` (transparent failover), `solanaRpcEndpoints()` (priority chain:+ caller url → `SOLANA_RPC_URL` → Helius → Alchemy → dRPC → Ankr → operator fallbacks →+ PublicNode/Leo/Tatum keyless → public mainnet-beta last), `makeRotatingFetch()` with+ per-endpoint quota cooldown + body validation.+- **RPC fallback class** — [api/_lib/solana/rpc-fallback.js](../../api/_lib/solana/rpc-fallback.js)+ — `RpcFallback` (3 consecutive fails → rotate, 60s cooldown), `rpcFallbackFromEnv()`.+- **Resilience (cockatiel)** — [api/_lib/resilience.js](../../api/_lib/resilience.js) —+ `withBreaker(name, fn, opts)`, `isCircuitError()` (ConsecutiveBreaker, 5 fails, 30s half-open).+- **SDK bridge (graceful null)** — [api/_lib/solana/sdk-bridge.js](../../api/_lib/solana/sdk-bridge.js)+ — pump SDK reads return `null` on transient RPC errors instead of throwing.+- **Confirm guard** — [api/_lib/solana/confirm.js](../../api/_lib/solana/confirm.js) —+ `confirmOrThrow()` throws on reverted tx (catches silent `result.value.err`).+- **Idempotency** — [api/_lib/x402/idempotency-cache.js](../../api/_lib/x402/idempotency-cache.js),+ [api/_lib/migrations/20260504140000_create_payment_intents.sql](../../api/_lib/migrations/20260504140000_create_payment_intents.sql),+ [api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql](../../api/_lib/migrations/20260603120000_payment_intents_tx_hash_unique.sql).+- **Parity/smoke** — [scripts/verify-solana-parity.mjs](../../scripts/verify-solana-parity.mjs)+ (`verify:solana`), [scripts/verify-onchain-parity.mjs](../../scripts/verify-onchain-parity.mjs)+ (`verify:onchain`), [scripts/onchain-smoke.mjs](../../scripts/onchain-smoke.mjs) (`smoke:onchain`).+- **Tests** — [tests/solana-rpc-rotating-fetch.test.js](../../tests/solana-rpc-rotating-fetch.test.js),+ [tests/api/solana-rpc-endpoints.test.js](../../tests/api/solana-rpc-endpoints.test.js),+ [tests/solana-confirm.test.js](../../tests/solana-confirm.test.js).++## Do this++1. **Audit every RPC entry point.** Grep for `new Connection(` / direct RPC URL use+ across `api/` and `workers/`. Every Solana read/write must go through+ `solanaConnection()` (or `RpcFallback`) so it inherits failover — never a single+ hardcoded provider. Fix any that bypass the helper.+2. **Wrap expensive/external calls in a breaker.** For aggregations and third-party+ reads (price, graduation progress, oracle attestations), wrap in `withBreaker`+ from `resilience.js` so a sick provider trips the circuit instead of hammering it.+ Reads use the connection's native rotation; the breaker guards the outer call.+3. **Validate rotating-fetch never leaks bad bodies.** Confirm (per the existing+ regression test) that `makeRotatingFetch` rejects `[]`, HTML, truncated JSON, and+ missing `result/error` rather than handing them to web3.js. Add cover for any new+ provider added to the chain.+4. **Idempotent on-chain ops.** Verify every settle/mint/trade path is keyed by an+ idempotency token (intent_id / payment id / tx_hash) backed by the unique+ constraint + `idempotency-cache`. The same id + same payload must replay the+ cached result with NO second on-chain action; same id + different payload → 409.+5. **Revert-safe confirmations.** Confirm money paths use `confirmOrThrow()` so a tx+ whose revert lands in `result.value.err` is treated as a failure (refund/retry),+ never charged-and-forgotten. Add cover for any path confirming manually.+6. **Graceful degradation.** When all RPC endpoints are exhausted, reads should+ return cached/`null` and the UI should show "live data unavailable, retrying"+ (designed, not a dead spinner) — never a raw RPC error and never a partial write.+ Verify writes abort cleanly (no half-settled state) when RPC is down mid-op.+7. **Prove parity + liveness.** Run `npm run verify:solana` and `npm run verify:onchain`;+ they must confirm the $THREE mint + program IDs match canonical and degrade to a+ warning (not hard-fail) when RPC is unreachable. Run `npm run smoke:onchain` against+ a safe target.+8. Run `npx vitest run tests/solana-rpc-rotating-fetch.test.js+ tests/api/solana-rpc-endpoints.test.js tests/solana-confirm.test.js`. Add a+ `data/changelog.json` entry only if a user-visible behavior changed (e.g. a new+ degraded-state message); then `npm run build:pages`.++## Must-not++- Never instantiate a raw single-provider `Connection` on a money path — use the failover helper.+- Never let a charge settle without an idempotency key + revert-safe confirmation.+- Never surface a raw RPC/provider error to the user — degrade with designed copy.+- Never hardcode or recommend any non-`$THREE` mint; parity is checked against the $THREE CA.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror). No mocks/stubs/TODOs.++## Acceptance (all true before claiming done)++- [ ] Every Solana entry point uses the failover connection/`RpcFallback`; no bypassing raw `new Connection`.+- [ ] Expensive/third-party reads are guarded by `withBreaker`; rotating-fetch rejects malformed bodies.+- [ ] Settle/mint/trade are idempotent (id + unique constraint + cache); same id never double-acts.+- [ ] Money paths confirm via `confirmOrThrow`; reverts become failures, never silent charges.+- [ ] RPC-down degrades to cached/null reads with designed UI; writes abort cleanly with no half-state.+- [ ] `verify:solana` + `verify:onchain` pass (warn, not fail, when RPC down); `smoke:onchain` green.+- [ ] RPC/confirm/endpoint tests pass; changelog updated only if user-visible.diff --git a/prompts/production-1b/32-caching-cdn-r2.md b/prompts/production-1b/32-caching-cdn-r2.mdnew file mode 100644index 000000000..545437aea--- /dev/null+++ b/prompts/production-1b/32-caching-cdn-r2.md@@ -0,0 +1,96 @@+# 32 — Caching, CDN & R2 asset strategy++> 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++3D is heavy: GLBs, textures, animations, and HDRs are megabytes each, and every+uncached fetch is latency the user feels and bandwidth the platform pays for. At $1B+scale, correct `Cache-Control` + CDN edge caching turns a slow viewer into an instant+one and cuts origin egress dramatically. Meanwhile the 500k/month Upstash command+budget means a single hot read that hits Redis on every request can torch the entire+budget in days — so caching is also a cost-survival discipline, not just speed.++## Mission++Ensure static + GLB/3D assets carry correct immutable/long-cache headers, R2 has CORS++ a lifecycle for orphaned assets, expensive reads are Redis-cached within budget with+stampede protection, and CDN edge caching is used wherever the data allows.++## Map (trust but verify — files move)++- **Cache headers** — [vercel.json](../../vercel.json) `headers` — existing rules:+ versioned `agent-3d` → `max-age=31536000, immutable`; `/avatars/*.glb` &+ `/animations/*` → `max-age=604800, stale-while-revalidate=2592000`; `/assets/*` →+ immutable; generic media regex covers `glb|gltf|hdr|exr|ktx2|basis|bin|woff2|…`.+- **R2 client** — [api/_lib/r2.js](../../api/_lib/r2.js) — S3-compatible (AWS SDK v3):+ `putObject`, `getObject`, `deleteObject`, `headObject`, `copyObject`, presigned+ up/download, `publicUrl(key)`. Env: `S3_ENDPOINT/ACCESS_KEY_ID/SECRET_ACCESS_KEY/BUCKET/PUBLIC_DOMAIN`.+- **R2 CORS** — [scripts/set-r2-cors.mjs](../../scripts/set-r2-cors.mjs) (`npm run apply:r2-cors`)+ — `public-read` (GET/HEAD) + `browser-upload` (PUT) rules with three.ws/preview/codespace/localhost origins.+- **Redis cache primitives** — [api/_lib/cache.js](../../api/_lib/cache.js) —+ `cacheGet/cacheSet/cacheWrap` (TTL), 2s in-process memo, single-flight in-flight+ coalescing, `acquireLock` distributed lock for expensive recompute.+- **Redis budget** — [api/_lib/redis-usage.js](../../api/_lib/redis-usage.js) —+ `REDIS_MONTHLY_BUDGET = 500_000`, warn 80% / crit 90%; [api/admin/redis-health.js](../../api/admin/redis-health.js).+- **Generated GLB storage** — [api/_lib/forge-store.js](../../api/_lib/forge-store.js),+ [api/_lib/reconstruct-finalize.js](../../api/_lib/reconstruct-finalize.js) (put to R2 → `publicUrl`).+- **Tests** — [tests/api/forge-cache-headers.test.js](../../tests/api/forge-cache-headers.test.js),+ [tests/http-cache-control.test.js](../../tests/http-cache-control.test.js),+ [tests/api/redis-usage.test.js](../../tests/api/redis-usage.test.js),+ [tests/api/skill-price-cache.test.js](../../tests/api/skill-price-cache.test.js).++## Do this++1. **Audit asset cache coverage.** For every static + 3D asset type served (GLB,+ GLTF, HDR, EXR, KTX2, BASIS, BIN, fonts, images, versioned JS), confirm a+ `Cache-Control` rule in `vercel.json` matches it. Content-addressed/versioned+ assets get `max-age=31536000, immutable`; mutable-but-cacheable assets get a long+ `max-age` + `stale-while-revalidate`. Fill any gap the audit finds.+2. **Never long-cache mutable HTML/API.** Verify HTML pages and `api/*` responses+ default to `no-store` (via `http.js`) unless a route is explicitly safe to edge-cache;+ long-caching a stale dashboard or balance is a correctness bug. Add `s-maxage` ++ `stale-while-revalidate` only to read endpoints whose data tolerates it (e.g. feeds, changelog).+3. **R2 CORS is current.** Run `npm run apply:r2-cors` and confirm the allowed origins+ cover prod, `*.vercel.app` previews, codespaces, and localhost, with `ETag`/`Accept-Ranges`+ exposed for range requests (GLB streaming). Add any missing origin idempotently.+4. **R2 lifecycle for orphans.** There is no object lifecycle today — generated GLBs+ accumulate forever. Add a lifecycle/cleanup path: either an R2 lifecycle rule for a+ `tmp/`/`scratch/` prefix, or a cron that deletes orphaned/unreferenced objects+ (cross-checked against the DB so nothing live is removed). Never delete a referenced asset.+5. **Cache expensive reads within budget.** Identify hot, expensive reads (on-chain+ scans, snapshots, price/market aggregates). Wrap them in `cacheWrap` with a sane+ TTL. Confirm high-frequency cheap reads use `local`/in-process memo (not a Redis+ GET per request) so the 500k/month budget survives a spike.+6. **Stampede protection on cold cache.** For any expensive recompute, use+ `acquireLock` so a traffic spike against a cold key fans out into ONE recompute+ platform-wide, not N. Verify the in-flight GET coalescing path works under+ concurrent reads.+7. **CDN edge caching.** Ensure cacheable read endpoints set `s-maxage` so Vercel's+ edge serves them without hitting the function/origin, and that GLBs are served from+ the R2 public CDN domain (not proxied through a function). Watch `redis-health` /+ `redis-usage` while exercising to confirm budget headroom.+8. Run `npx vitest run tests/api/forge-cache-headers.test.js tests/http-cache-control.test.js+ tests/api/redis-usage.test.js tests/api/skill-price-cache.test.js`. Verify headers+ live in the browser Network tab (`npm run dev`). Add a `data/changelog.json` entry+ if a user-visible perf change shipped; `npm run build:pages`.++## Must-not++- Never apply `immutable`/long `max-age` to mutable HTML, dashboards, balances, or `api/*` writes.+- Never delete an R2 object that is still referenced — cross-check the DB before any lifecycle delete.+- Never add a hot read that issues a Redis command per request without memo/local bucketing — respect the 500k budget.+- Do not pull/fetch/merge from the `threeD` remote (push-only mirror). No mocks/stubs/TODOs.+- The only coin is `$THREE` — no other token in any cache key, fixture, or copy.++## Acceptance (all true before claiming done)++- [ ] Every static + 3D asset type has a correct `Cache-Control` rule (immutable for versioned, SWR for mutable).+- [ ] HTML/API stay `no-store` except explicitly edge-cacheable reads with `s-maxage` + SWR.+- [ ] `apply:r2-cors` run; CORS covers prod/preview/codespace/localhost with range headers exposed.+- [ ] An R2 lifecycle/cleanup removes orphaned assets only, cross-checked against the DB.+- [ ] Expensive reads use `cacheWrap`; hot cheap reads avoid per-request Redis; budget headroom confirmed.+- [ ] Stampede protection (lock + in-flight coalescing) verified on a cold expensive key.+- [ ] Cache-header tests pass; headers verified in the browser; changelog updated if user-visible.diff --git a/prompts/production-1b/A01-buyback-engine-provable.md b/prompts/production-1b/A01-buyback-engine-provable.mdnew file mode 100644index 000000000..1413e92df--- /dev/null+++ b/prompts/production-1b/A01-buyback-engine-provable.md@@ -0,0 +1,50 @@+# A01 — $THREE buyback engine: scheduled, on-chain, audited, public proof++> Phase A · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The headline promise on the $THREE token page is "50% of all platform revenue buys+$THREE on the open market and routes it to the treasury — on-chain, verifiable." Today+that is wired but not *proven*: the public stats endpoint already reports buyback runs,+but the execution path is opt-in and there is no scheduled job that actually runs buys,+logs them, and exposes a verifiable, on-chain receipt trail. A $1B token economy lives or+dies on this being true and auditable. Make it real, automatic, and provable.++## Where this lives (real files)+- `api/_lib/token/buyback.js` — market-buy engine (Jupiter swap), `buybackStats()` public summary, spend caps/slippage, signer load.+- `api/_lib/token/config.js` — split policies (treasury/rewards), commit bps, fail-closed wallet guards.+- `api/three-token/[action].js` — `GET /stats` returns `buyback` summary; `three_buyback_runs` table is referenced here.+- `api/cron/[name].js` — Vercel cron dispatcher with constant-time secret auth (add the new cron here or as its own file).+- `api/_lib/migrations/` — add a migration for the audit table if not present.+- `vercel.json` — cron schedule registration.++## Current state & gaps+- `buybackStats()` aggregates from `three_buyback_runs` but no scheduled job writes to it on a cadence.+- Execution is gated behind `isEnabled()` + signer presence; when off it's a silent no-op with no operator signal.+- No public, per-run verifiable trail (Solscan tx per buy) beyond what `buybackStats()` can show.+- "Revenue earned so far" is currently $0 — confirm the revenue source (`agent_revenue_events`) is the real, complete ledger and that the commitment math is correct.++## Build this+1. **Scheduled buyback cron** (`api/cron/three-buyback.js` or a `[name].js` branch): runs every 6–12h. Computes `committed = revenue_since_last_run × commit_bps`, fetches a Jupiter quote (USDC→$THREE), submits + confirms the swap on mainnet, routes bought $THREE to the treasury, and writes a row to `three_buyback_runs` (usdc_spent, three_bought, price, tx signature, slippage, status, ran_at). Register it in `vercel.json`.+2. **Idempotency & caps:** never double-spend the same revenue window (cursor/high-water mark in DB); enforce per-run and daily USD caps and max slippage; on quote/slippage failure, record a `skipped` run with reason — never a silent exit.+3. **Resilience:** use the existing Solana RPC failover (`api/_lib/solana/`); retry with backoff; alert ops (`api/_lib/alerts.js`) on hard failure; record partial fills correctly.+4. **Public proof endpoint:** ensure `GET /api/three-token/stats` (and/or a dedicated `GET /api/three-token/buybacks`) returns: total revenue, committed, deployed on-chain, $THREE bought, run count, and the last N runs each with a Solscan tx link. The token page already renders `recent_runs` — make sure the shape matches and links resolve.+5. **Dry-run safety:** when the signer/env is unset (dev/preview), the cron computes and logs a *plan* (no on-chain send) and records nothing destructive — exactly like a real run minus the transaction.++## Out of scope+- Changing the commitment percentage or token split policy (governance decision).+- The rewards/reflections distribution (that is **A02**).++## Definition of done+- [ ] Cron is registered, runs on schedule, and on a funded staging/preview signer executes a real buy you can open on Solscan.+- [ ] Every run (success, skipped, failed) is persisted with a reason; no silent exits.+- [ ] `buybackStats()` / the public endpoint reflects real runs with working Solscan links; the token page "Programmatic buybacks" panel shows them.+- [ ] Caps, slippage, and idempotency are enforced and unit-tested (`tests/`); RPC failover + alerting covered.+- [ ] Dry-run mode proven safe with the signer unset.+- [ ] Changelog entry; committed + pushed to both remotes.++## Verify+- Trigger the cron locally with the cron secret; confirm a row in `three_buyback_runs` and a `plan` in dry-run.+- `curl https://three.ws/api/three-token/stats` (or your preview) and confirm the `buyback` block is populated and links resolve.+- `npx vitest run` green, including new buyback tests.diff --git a/prompts/production-1b/A02-reflections-distribution.md b/prompts/production-1b/A02-reflections-distribution.mdnew file mode 100644index 000000000..6a791fde4--- /dev/null+++ b/prompts/production-1b/A02-reflections-distribution.md@@ -0,0 +1,47 @@+# A02 — $THREE reflections/rewards: complete on-chain distribution + receipts++> Phase A · Depends on: A04 (snapshot freshness) ideally first · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+"Every paid action reflects $THREE back to holders pro-rata — deflation-free yield, no+burn" is a core reason to hold. The pro-rata math exists and a distribution cron exists,+but it computes a *plan* and does not reliably execute the on-chain transfers or record+receipts. Holders need to see real SOL/$THREE land in their wallets with a verifiable tx.+Finish the execution path and make every distribution auditable.++## Where this lives (real files)+- `api/cron/rewards-distribute.js` — reflections loop; currently produces a payout plan, dust-floor filtering, DRY-run when distributor key unset.+- `api/_lib/token/rewards.js` — pure pro-rata math (pool → per-holder amounts).+- `api/_lib/coin/three-holders.js`, `api/_lib/coin/payouts.js`, `api/_lib/coin/treasury.js` — holder balances + payout helpers.+- `api/_lib/token/config.js` — `REVENUE_SHARE_POOL_PCT`, rewards wallet guards.+- `api/_lib/migrations/` — add `three_rewards_distributions` if absent.++## Current state & gaps+- The execute branch loads the distributor key but does not complete batched on-chain transfers + confirmation.+- No durable `three_rewards_distributions` record (cycle, holder count, total paid, per-batch tx signatures, status).+- No public read for "last reflection, amount, when, tx" to back the holder-rewards claim.+- Risk of fan-out DDoS if transfers are sent serially per holder without batching.++## Build this+1. **Complete execution:** in `rewards-distribute.js`, when the distributor secret is set, build batched SPL transfers to holder ATAs (chunked, with compute-budget priority fees), submit, confirm, and handle partial/failed batches with retry. Use the existing RPC failover.+2. **Receipts:** write a `three_rewards_distributions` row per cycle (snapshot age used, eligible holders, total_pool_usd, total_paid, asset, batch tx signatures[], status, started_at/finished_at). Make it idempotent per cycle so a re-run resumes rather than double-pays.+3. **Eligibility & dust:** enforce the min-payout dust floor and the holder min-USD floor already in code; exclude the treasury/LP/AMM pool wallets from payouts (the AMM vault is a top "holder" — never reflect to it).+4. **Public proof:** add `GET /api/three-token/reflections` (or extend `/stats`) returning last cycle + recent cycles with Solscan links and 7d/30d totals. Wire it into the token page and the holder leaderboard.+5. **Dry-run parity:** with the secret unset, log a full plan and persist nothing destructive.++## Out of scope+- The buyback engine (**A01**).+- Changing the pool percentage (governance).++## Definition of done+- [ ] On a funded preview distributor, a cycle executes real batched transfers you can verify on Solscan, with a `three_rewards_distributions` receipt.+- [ ] AMM/treasury wallets excluded; dust floors enforced; idempotent re-run resumes safely.+- [ ] Public reflections endpoint populated and surfaced on the token page + holder leaderboard.+- [ ] Unit tests for pro-rata math, exclusion, batching, idempotency; `npx vitest run` green.+- [ ] Changelog entry; committed + pushed to both remotes.++## Verify+- Run the cron in dry-run; confirm the plan and zero writes.+- Run against a funded preview wallet with 2–3 test holders; confirm transfers land + receipt row.+- `curl …/api/three-token/reflections` returns real, link-resolving data.diff --git a/prompts/production-1b/A03-tier-gating-enforced.md b/prompts/production-1b/A03-tier-gating-enforced.mdnew file mode 100644index 000000000..83f59d1ae--- /dev/null+++ b/prompts/production-1b/A03-tier-gating-enforced.md@@ -0,0 +1,46 @@+# A03 — Hold-to-access tiers enforced across every paid endpoint++> Phase A · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+"Hold $THREE to unlock fee discounts, higher quotas, and pro perks." The tier ladder is+computed correctly, but the discount and rate multipliers are only *applied* on some+surfaces (forge). If a Gold holder still pays full price on most paid endpoints, the+single biggest reason to accumulate $THREE is hollow. Enforce tiers everywhere money or+quota is spent, and make the benefit visible.++## Where this lives (real files)+- `api/_lib/three-tier.js` — 5-tier ladder (Member→Bronze→Silver→Gold→Genesis), USD-value gating, fee discount bps + rate multipliers.+- `api/_lib/forge-tiers.js` — reads tier for forge (the one surface that honors it today).+- `api/_lib/holder-pass.js` — HMAC tier pass for gated worlds.+- `api/x402/*.js` — ~27 paid endpoints using a `paidEndpoint()` helper; most do **not** apply tier discounts.+- `api/_lib/rate-limit.js` — per-user/per-IP limiters whose thresholds should scale by tier.++## Current state & gaps+- Tier discount/multiplier computed in `three-tier.js` but applied inconsistently; only forge reads `forge-tiers.js`.+- No single chokepoint: each paid endpoint prices independently, so discounts drift.+- Rate-limit quotas don't scale by tier, so "higher quotas" is unproven.+- No user-facing "your tier saved you $X" feedback or upgrade nudge.++## Build this+1. **Single pricing chokepoint:** add a helper (e.g. `api/_lib/token/apply-tier-pricing.js`) that, given a wallet + base price + base quota, returns the tier-adjusted price and quota. Route every `api/x402/*` endpoint and `paidEndpoint()` through it so discounts are computed in exactly one place.+2. **Audit & wire all paid endpoints:** enumerate every paid surface (`api/x402/*.js`, forge, cosmetics, marketplace sales, mint-to-mesh, tutor, skill-call, vanity, etc.). For each, fetch the caller's tier and apply the discount before quoting. List any endpoint that intentionally has no discount and say why.+3. **Tier-scaled quotas:** make the relevant `rate-limit.js` buckets multiply their threshold by the tier's rate multiplier so higher tiers genuinely get higher quotas. Return the effective quota in response headers.+4. **Make it visible:** in the payment/checkout UI and forge, show "Tier: Gold — 20% off (you saved $X)" and, when a user is close to the next tier, a "hold N more $THREE to reach Silver" nudge linking to the swap.+5. **Server-trust:** tier must be resolved server-side from on-chain balance (never trusted from the client).++## Out of scope+- The buyback (**A01**) and reflections (**A02**).+- Designing new tiers or thresholds (governance).++## Definition of done+- [ ] Every paid endpoint routes pricing through the single chokepoint; an audit list shows each endpoint's discount status.+- [ ] A test proves a Bronze/Silver/Gold holder is charged the correctly reduced price on ≥3 representative endpoints, and Member pays full.+- [ ] Tier-scaled quotas applied to the key limiter buckets, with effective quota in headers.+- [ ] UI shows tier savings + an upgrade nudge near a tier boundary.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Unit test: same endpoint, four tiers, assert four prices.+- Hit a paid endpoint as a known-tier wallet; confirm the charged amount and headers.diff --git a/prompts/production-1b/A04-holder-snapshot-freshness.md b/prompts/production-1b/A04-holder-snapshot-freshness.mdnew file mode 100644index 000000000..6eff83164--- /dev/null+++ b/prompts/production-1b/A04-holder-snapshot-freshness.md@@ -0,0 +1,43 @@+# A04 — Holder snapshot freshness, reconciliation & alerting++> Phase A · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Holder counts, tiers, reflections eligibility, the leaderboard, and the OG share card all+read from one $THREE holder snapshot. If that snapshot goes stale (Helius/DAS rate-limited+or the cron stalls), every downstream number silently drifts and reflections could pay the+wrong set. Make the snapshot self-healing, observable, and never silently stale.++## Where this lives (real files)+- `api/_lib/coin/three-holders.js` — cached read/write layer; `threeHolderBalances()`, `threeHolderCount()`, `readThreeHolderSnapshot()` (30-min staleness gate), cold-fallback scan with cross-instance lock.+- `api/cron/three-holders-snapshot.js` — the 5-minute refresh cron (single DAS scan).+- `api/_lib/coin/holders.js` — full Helius DAS walk.+- `api/three-token/[action].js` — `/stats` (holders) and `/leaderboard` consume the snapshot.++## Current state & gaps+- A single DAS scan per cron tick; if it fails or is throttled, the snapshot stales with no alert.+- Public reads fall back to a cold scan (expensive) but nothing signals that the snapshot is degraded.+- No public freshness signal (age of snapshot) and no operator alert past the 30-min gate.+- Reconciliation between `holder_count` (meta) and actual ranked rows is assumed, not verified.++## Build this+1. **Resilient cron:** wrap the DAS scan in retry-with-backoff; on a zero/short result, refuse to overwrite a good snapshot (the code already guards the wipe — keep and test it) and alert ops.+2. **Freshness signal:** add `GET /api/three-token/holder-snapshot-status` returning snapshot age, holder_count, and `fresh|stale|cold`. Surface a subtle "holders as of Xm ago" on the leaderboard.+3. **Alerting:** if the snapshot exceeds the staleness threshold (e.g. >30m) or the cron fails N times, fire an ops alert (`api/_lib/alerts.js`) once per incident with recovery announcement.+4. **Reconciliation check:** a lightweight assertion (in the cron and a test) that `meta.holder_count` equals the count of rows with balance > 0, and that treasury/AMM/LP wallets are flagged so A02/A03 can exclude them.+5. **Cost control:** confirm the cold-fallback stampede guard (cross-instance lock + in-process single-flight) holds under concurrent reads; add a test.++## Out of scope+- Reflections execution (**A02**) and tier logic (**A03**) — this only guarantees the data they read.++## Definition of done+- [ ] Snapshot cron retries, never wipes on a bad scan, and alerts on failure + recovery.+- [ ] Freshness endpoint live; leaderboard shows snapshot age.+- [ ] Reconciliation assertion passes; treasury/AMM wallets flagged for exclusion.+- [ ] Stampede guard tested under concurrency; `npx vitest run` green.+- [ ] Changelog entry; committed + pushed to both remotes.++## Verify+- Simulate a failed scan (mock DAS error) → snapshot preserved + alert fired.+- `curl …/api/three-token/holder-snapshot-status` returns a sane age + count.diff --git a/prompts/production-1b/A05-token-config-validation-and-trust-dashboard.md b/prompts/production-1b/A05-token-config-validation-and-trust-dashboard.mdnew file mode 100644index 000000000..7ad094e28--- /dev/null+++ b/prompts/production-1b/A05-token-config-validation-and-trust-dashboard.md@@ -0,0 +1,42 @@+# A05 — On-chain token-config validation + public token-economy & trust dashboard++> Phase A · Depends on: A01, A02 (their data feeds the dashboard) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Two things compound trust in a $1B token: (1) the platform can *prove* it is configured to+move funds to the right on-chain addresses, and (2) anyone can see the whole economy at a+glance — supply, treasury, buybacks, reflections, holders, tiers — with on-chain links. A+silent misconfiguration (wrong mint/treasury) would route real money to the wrong place;+a great public dashboard turns the economy into marketing.++## Where this lives (real files)+- `api/_lib/token/config.js` — mint, decimals, treasury, rewards, burn wallets from env; fail-closed guards.+- `api/three-token/[action].js` — existing `/stats`, `/leaderboard`, `/burns`, `/activity`.+- `pages/three-token.html` + `src/three-token-page.js` — public token page.+- `pages/` + `data/pages.json` — add a `/three-token/proof` or `/three/trust` page if warranted.++## Current state & gaps+- Token config is env-only; no runtime check that env matches the real on-chain mint/treasury.+- The "Programmatic buybacks" panel exists but there's no single, comprehensive economy view.+- Holders, buybacks, reflections, tiers, burns live across endpoints with no unified proof surface.++## Build this+1. **Startup/boot validation:** add `validateTokenConfig()` that fetches the live mint (supply, decimals) and verifies it matches `TOKEN_MINT`/decimals; verifies the treasury & rewards wallets exist and (optionally) that recent transfers land there. Run it in a boot/health path and fail loudly on divergence. Add a test that pins the expected mint = `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.+2. **Unified economy endpoint:** `GET /api/three-token/economy` returning on-chain supply + circulating, treasury address + balance, rewards pool balance, last buyback (amount, tx, when) + 7d/30d totals, last reflection + 7d/30d totals, holder count + tier distribution, total burned. All numbers link to Solscan.+3. **Public trust dashboard:** a polished page (live 3D optional, reuse existing widgets) that renders the economy endpoint: every claim on the token page backed by a clickable on-chain receipt. Designed loading/empty/error states. Mobile-first.+4. **Tier distribution:** show how many holders sit in each tier and the $THREE needed to climb — doubles as an upgrade funnel.+5. **No other coin** anywhere (CLAUDE.md). Only `$THREE`.++## Out of scope+- Building the buyback/reflection *execution* (A01/A02) — this consumes their outputs.++## Definition of done+- [ ] `validateTokenConfig()` runs at boot/health, fails on mismatch, and a test pins the canonical mint.+- [ ] `/api/three-token/economy` returns real, link-resolving figures.+- [ ] Trust dashboard page is live, reachable from the token page + nav, with all states designed and responsive.+- [ ] `npx vitest run` green; `npm run build:pages` passes (new page → changelog auto-entry); committed + pushed to both remotes.++## Verify+- Temporarily set a wrong treasury env locally → boot/health fails clearly; restore.+- Open the trust page in a browser; click receipts → they resolve on Solscan.diff --git a/prompts/production-1b/A06-treasury-custody-hardening.md b/prompts/production-1b/A06-treasury-custody-hardening.mdnew file mode 100644index 000000000..106daa717--- /dev/null+++ b/prompts/production-1b/A06-treasury-custody-hardening.md@@ -0,0 +1,42 @@+# A06 — Treasury/buyback custody hardening (vault + approval gate + audit)++> Phase A · Depends on: A01, A02 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The buyback and reflections signers are the keys to real money. Today they load from an+env var as a raw secret — a single compromised env leaks the ability to drain the+treasury. Before this economy scales, harden custody so that even a leaked key cannot move+funds without an independent approval, and every signing event is audited.++## Where this lives (real files)+- `api/_lib/token/buyback.js` — `loadBuybackSigner()` / keypair-from-env.+- `api/cron/rewards-distribute.js` — distributor key load.+- `api/_lib/agent-wallet.js`, `api/_lib/avatar-wallet.js` — existing custodial-key decryption patterns to mirror.+- `api/_lib/env.js` — centralized secret access.+- `api/_lib/alerts.js`, `api/_lib/audit.js` (if present) — alerting/audit hooks.++## Current state & gaps+- Signer secret is a base64 env var; no rotation, no HSM/vault, no independent approval, no signing audit trail.+- A compromised deploy env = unilateral spend authority over treasury operations.++## Build this+1. **Vaulted secret:** move signer secrets out of plain env into an encrypted-at-rest path consistent with `agent-wallet.js`/`avatar-wallet.js` (decrypt only in memory at sign time). Document that the raw secret must live in a vault (Vercel encrypted env at minimum; KMS/secrets-manager preferred), never in `.env` committed anywhere.+2. **Approval gate:** require an independent approval before any on-chain spend above a configurable threshold — e.g. a multisig/squads approval address, or a second signer, or a per-run approved-amount record that the cron checks before sending. A leaked single key alone must not be able to spend.+3. **Spend policy:** enforce per-run, daily, and monthly USD ceilings server-side; reject and alert on anything over policy.+4. **Signing audit log:** every buyback/reflection signature writes an audit record (who/what/amount/tx/policy-decision/approver) that is queryable; alert on any spend outside policy.+5. **Rotation runbook:** document how to rotate signer keys without downtime, and how to revoke a compromised key immediately (kill switch env that hard-disables spends).++## Out of scope+- The execution logic itself (A01/A02) — this wraps it in custody controls.++## Definition of done+- [ ] Signer secrets are vaulted/encrypted, decrypted only at sign time; no raw key in plain env or repo.+- [ ] An approval gate + spend ceilings block any spend that lacks approval or exceeds policy, with a test proving a leaked-key-alone spend is rejected.+- [ ] Every signing event is audited and queryable; out-of-policy attempts alert ops.+- [ ] A kill switch hard-disables spends; rotation runbook written in `docs/`.+- [ ] `npx vitest run` green; changelog entry (security tag); committed + pushed to both remotes.++## Verify+- Attempt a spend above the ceiling / without approval → rejected + alert.+- Flip the kill switch → all spends refuse; audit records the refusal.diff --git a/prompts/production-1b/A07-x402-pricing-and-catalog.md b/prompts/production-1b/A07-x402-pricing-and-catalog.mdnew file mode 100644index 000000000..5a8314d92--- /dev/null+++ b/prompts/production-1b/A07-x402-pricing-and-catalog.md@@ -0,0 +1,44 @@+# A07 — x402 pricing: single source of truth + discoverable service catalog++> Phase A · Depends on: none (pairs with A03) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+three.ws sells ~27 paid endpoints to agents over x402, plus paid MCP tools. But prices are+hardcoded per endpoint in two places (web + MCP), and a caller discovering a service via+the Bazaar can't see the price or rate budget until they call it. For agents to *shop* for+services — the network-effect that grows GMV — pricing must be one source of truth and the+catalog must be browsable by price and quota.++## Where this lives (real files)+- `api/x402/*.js` — ~27 paid endpoints using `paidEndpoint()` (prices embedded in code).+- `mcp-server/src/` — MCP tools that embed their own prices.+- `api/_lib/x402/bazaar-client.js` — multi-facilitator discovery (PayAI + CDP), normalizes v1/v2.+- `api/_lib/x402/access-control.js` — subscriber bypass, tier limits, API-key auth.+- `api/_lib/migrations/2026-06-19-x402_merchant.sql` — service registry + pricing metadata.++## Current state & gaps+- Prices duplicated across web endpoints and MCP tools; changing one risks drift.+- No queryable catalog with price + rate-limit metadata; Bazaar gives name+schema only.+- No `x-x402-price` style metadata on schemas for price-range browsing.++## Build this+1. **Single price config:** create one source of truth (e.g. `api/_lib/x402/prices.config.js` or the `marketplace_services` table) holding `{ service, price_usd, asset_mint, rate_per_min, rate_per_month, min_charge_usd }`. Refactor every `api/x402/*` endpoint and every MCP tool to read price from it. Keep a `pricing_version` for backward-compat.+2. **Service catalog endpoint:** `GET /api/x402/service-catalog` returning every paid service with live price, asset, quota, and schema link — queryable by price range and category. Include tier-adjusted price hints (ties into A03).+3. **Schema price metadata:** emit the price in each endpoint's 402 challenge and discovery schema (x402 v2 extension) so a Bazaar consumer sees the price without calling.+4. **MCP/web parity test:** a test that asserts a given service's price is identical across the web endpoint and the MCP tool (no drift).+5. **Catalog UI:** a simple, polished `/bazaar`-adjacent view (or extend the existing bazaar surface) that lists three.ws's own paid services with price + "try it" — designed empty/error/loading states.++## Out of scope+- Per-wallet metering and usage headers (**A08**).+- Facilitator failover (**A09**).++## Definition of done+- [ ] All paid prices come from one config; a test proves web↔MCP parity.+- [ ] `/api/x402/service-catalog` returns real, queryable pricing; 402 challenges carry price metadata.+- [ ] Catalog UI lists services with price + try-it and all states designed.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Change a price in the config → both the web endpoint quote and the MCP tool reflect it.+- `curl …/api/x402/service-catalog` returns priced, link-resolving services.diff --git a/prompts/production-1b/A08-x402-metering-and-usage.md b/prompts/production-1b/A08-x402-metering-and-usage.mdnew file mode 100644index 000000000..a31211e2b--- /dev/null+++ b/prompts/production-1b/A08-x402-metering-and-usage.md@@ -0,0 +1,44 @@+# A08 — x402 per-wallet metering, rate-limit headers & usage endpoint++> Phase A · Depends on: A07 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Paid endpoints today share coarse quotas but don't meter usage per paying wallet. That+means a single caller can exhaust an expensive pipeline (forge, mesh), there's no+`x-ratelimit-*` feedback for well-behaved agents, and a wallet can't see what it spent.+Metering is how you protect capacity, price fairly, and give agents the predictability+that makes them build on you.++## Where this lives (real files)+- `api/_lib/x402/access-control.js` — subscriber bypass, tier-based limits, API-key auth (extend here).+- `api/_lib/x402/audit-log.js` — settlement ledger (per-settlement records exist).+- `api/_lib/rate-limit.js` — Redis sliding-window limiters.+- `api/x402/*.js` — paid endpoints to instrument.+- `api/_lib/migrations/` — add `agent_x402_usage` if a durable rollup is needed.++## Current state & gaps+- No per-wallet calls/min, calls/day, or spend/month meter.+- No `x-ratelimit-limit/remaining/reset` headers on paid responses.+- No "your usage this month" read for a wallet.++## Build this+1. **Per-wallet meter:** in `access-control.js`, track calls and USD spend per wallet per minute/day/month (Redis counters; roll up to `agent_x402_usage` for durability). Tie the per-minute/day ceilings to tier (from A03).+2. **Standard headers:** return `x-ratelimit-limit`, `x-ratelimit-remaining`, `x-ratelimit-reset`, and a `x-x402-spend-month` header on every paid response so agents can self-throttle.+3. **Usage endpoint:** `GET /api/x402/usage` (auth or signed by the wallet) returning calls + spend this minute/day/month and remaining quota per service.+4. **Min-charge / dust guard:** enforce a per-service `min_charge_usd` (from A07's config) so sub-cent endpoints can't be hammered for free; add per-IP limits on the cheapest routes.+5. **Graceful 429:** when metered out, return a clean 429 with `Retry-After` and a body explaining the limit + upgrade path (tier), never a generic error.++## Out of scope+- Pricing config (**A07**) and facilitator failover (**A09**).++## Definition of done+- [ ] Per-wallet metering enforced with tier-scaled ceilings; `agent_x402_usage` rollup persisted.+- [ ] All paid responses carry `x-ratelimit-*` + spend headers; 429s are clean with `Retry-After`.+- [ ] `/api/x402/usage` returns accurate per-wallet figures.+- [ ] Min-charge + per-IP guard on cheap endpoints; tests cover meter math + 429 path.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Hammer a paid endpoint past the limit → 429 + `Retry-After` + headers decrement correctly.+- `curl …/api/x402/usage` reflects the calls just made.diff --git a/prompts/production-1b/A09-x402-facilitator-failover.md b/prompts/production-1b/A09-x402-facilitator-failover.mdnew file mode 100644index 000000000..e7bc98d9d--- /dev/null+++ b/prompts/production-1b/A09-x402-facilitator-failover.md@@ -0,0 +1,41 @@+# A09 — x402 facilitator failover + self-hosted fallback + admin health/metrics++> Phase A · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Every paid call settles through an external x402 facilitator. Today there's a facilitator+list but no failover: if the primary (PayAI) is down, settlements 5xx and revenue stops.+Add ordered failover, a self-hosted fallback so three.ws never fully depends on a third+party, and the health/metrics to see settlement reliability.++## Where this lives (real files)+- `api/_lib/x402/bazaar-client.js` — `DEFAULT_FACILITATORS` list, discovery, schema normalization.+- `api/_lib/x402/a2a-server.js` / `a2a-client.js` — payment verify/settle.+- `api/_lib/x402/audit-log.js` — settlement ledger.+- `api/x402/*.js` — paid endpoints.++## Current state & gaps+- `verifyPayment()`/settlement targets a single facilitator with no fallback.+- No facilitator health check; a facilitator outage looks like a platform outage.+- No self-hosted `/verify` `/settle` `/supported` path as a last resort.++## Build this+1. **Ordered failover:** in the verify/settle path, try facilitators in priority order with a bounded timeout each; on failure, fall through to the next and log which failed. Never block revenue on one provider.+2. **Self-hosted facilitator fallback:** deploy a minimal in-repo `/api/x402/facilitator/{verify,settle,supported}` that can verify + settle the `exact` scheme on Solana mainnet directly via our RPC, used as the final fallback. Guard it behind the same caps/audit as everything else.+3. **Health + metrics:** `GET /api/admin/x402-health` (auth) checks every configured facilitator's `/supported`; `GET /api/admin/x402-metrics` shows settlement success rate, volume (daily/weekly/monthly), top endpoints, top payers, and facilitator error counts.+4. **Alerting:** if settlement success rate drops below a threshold or a facilitator is down, alert ops once per incident.+5. **Idempotency preserved:** failover must not double-settle — reuse the existing `idempotency-cache.js` keyed on payment identifier across providers.++## Out of scope+- Pricing (**A07**) and metering (**A08**).++## Definition of done+- [ ] Settlement fails over across facilitators and finally to the self-hosted path; proven by forcing the primary to fail.+- [ ] Self-hosted facilitator verifies + settles a real Solana `exact` payment.+- [ ] `/api/admin/x402-health` + `/api/admin/x402-metrics` return real data; low-success alert fires.+- [ ] Idempotency holds across failover (no double-settle) — tested.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Point the primary facilitator at a dead URL → settlements still succeed via fallback; health shows the primary down.diff --git a/prompts/production-1b/A10-a2a-dispute-and-reputation.md b/prompts/production-1b/A10-a2a-dispute-and-reputation.mdnew file mode 100644index 000000000..1faab897c--- /dev/null+++ b/prompts/production-1b/A10-a2a-dispute-and-reputation.md@@ -0,0 +1,41 @@+# A10 — Agent-to-agent payments: dispute/refund + on-chain reputation++> Phase A · Depends on: A07–A09 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Agents paying agents is the flywheel of an agent economy. Right now an agent can be paid,+do the work badly (or not at all), and the buyer has no recourse and the seller no+reputation cost. Without trust, agents won't transact at scale. Add an optional dispute+window with refunds and tie settlement outcomes to on-chain reputation (ERC-8004) so good+actors compound and bad actors are priced out.++## Where this lives (real files)+- `api/_lib/x402/a2a-server.js` / `a2a-client.js` — A2A payment verify/settle, delegation.+- `api/_lib/x402/audit-log.js` — settlement ledger.+- `contracts/` + `agent-protocol-sdk/` — ERC-8004 identity/reputation, agent-invocation program.+- `mcp__3d-agent-local__agent_reputation` (MCP) — existing reputation read surface.++## Current state & gaps+- A2A settlement verifies payment but records no outcome and offers no dispute/refund.+- No link between settlement quality and the ERC-8004 ReputationRegistry.++## Build this+1. **Dispute window:** add an optional, per-service `disputePeriod` (e.g. 24h). The buyer can open `POST /api/x402/a2a-dispute` with evidence; if upheld (rule or human/automated check), refund from the seller's escrowed/holdback balance.+2. **Hold-back/escrow:** for disputable services, hold a configurable share of the payment until the dispute window closes, then release to the seller. Never let funds be both refundable and already spent.+3. **Reputation integration:** on settlement complete (and on dispute outcome), write a reputation signal to the ERC-8004 ReputationRegistry (via `agent-protocol-sdk`/`contracts`) — successful, disputed, refunded. Surface the score on agent profiles (ties into B09).+4. **Buyer protection UX:** the A2A client + any UI shows the seller's reputation before paying and the dispute path after.+5. **Abuse guards:** rate-limit disputes per buyer; penalize frivolous disputes; require evidence.++## Out of scope+- Pricing/metering/failover (A07–A09).+- Designing the reputation scoring formula beyond success/dispute/refund signals.++## Definition of done+- [ ] Disputable services hold back funds and honor a working dispute → refund path.+- [ ] Settlement + dispute outcomes write real reputation signals on-chain; profiles show the score.+- [ ] Dispute abuse guards in place; tests cover happy path, refund, frivolous-dispute rejection.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Run a paid A2A call, open a dispute, see the refund + reputation decrement; run a clean call, see reputation increment.diff --git a/prompts/production-1b/A11-inline-402-pay-modal.md b/prompts/production-1b/A11-inline-402-pay-modal.mdnew file mode 100644index 000000000..9037f65cb--- /dev/null+++ b/prompts/production-1b/A11-inline-402-pay-modal.md@@ -0,0 +1,41 @@+# A11 — Inline "Payment Required" (402) pay modal everywhere++> Phase A · Depends on: A07 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+When a human (not an agent) hits a paid action, the experience must be a one-tap pay — not+a dead 402 or a redirect. A frictionless inline checkout is the difference between a curious+visitor and a paying user. Wire a single, reusable "Payment Required" modal that any surface+can invoke, backed by the real x402 flow and the Jupiter/USDC rails already in the app.++## Where this lives (real files)+- `x402-payment-modal/`, `x402-modal-sdk/` — existing payment-modal SDK/UI.+- `src/payment-modal.js` — in-app skill-purchase modal (wallet connect, USDC balance, settle).+- `src/swap-jupiter.js` — swap/funding flow (top-up if balance is short).+- `api/x402/*.js` + `api/_lib/x402/` — 402 challenge + settlement.+- Surfaces that gate on payment: forge high tiers, marketplace skills, cosmetics, mint-to-mesh, etc.++## Current state & gaps+- `payment-modal.js` exists but isn't a universal, drop-in handler for any 402; some surfaces redirect or error.+- Insufficient-balance flows aren't consistently wired to the funding/swap path across wallets.++## Build this+1. **Universal handler:** a single `openPaymentRequired({ challenge | endpoint, onPaid })` that: reads the 402 challenge (price from A07), connects the wallet, checks USDC balance, settles, and resolves with the unlocked result. Reuse `payment-modal.js`/`x402-modal-sdk`.+2. **Top-up path:** if the balance is short, route into `swap-jupiter.js`/the fund flow, then resume the payment — no dead end.+3. **Tier-aware price:** show the tier-adjusted price (A03) and any "hold more $THREE to save" nudge.+4. **All states designed:** connecting, quoting, insufficient funds (with top-up), confirming, success (with receipt/Solscan link), error (retry / switch wallet). Accessible + mobile.+5. **Adopt everywhere:** replace ad-hoc 402 handling on every paid human-facing surface with this handler. Audit and list the surfaces converted.++## Out of scope+- The agent (machine) payment path — that's the raw x402 + SDK, not this modal.++## Definition of done+- [ ] One reusable handler powers 402 checkout across all paid human surfaces (audit list provided).+- [ ] Insufficient balance flows seamlessly into top-up and resumes the purchase.+- [ ] Every state designed, accessible, responsive; success shows a verifiable receipt.+- [ ] Works on Phantom + Solflare; `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Trigger a paid action with an empty wallet → top-up → pay → unlock, all inline.+- Repeat on mobile width and with the keyboard only.diff --git a/prompts/production-1b/B01-token-page-production-pass.md b/prompts/production-1b/B01-token-page-production-pass.mdnew file mode 100644index 000000000..47f06d6a0--- /dev/null+++ b/prompts/production-1b/B01-token-page-production-pass.md@@ -0,0 +1,43 @@+# B01 — $THREE token page production pass++> Phase B · Depends on: A01, A02, A05 (their data enriches it) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+`/three-token` is the single most important conversion page on the platform — it's where a+visitor decides to buy and hold $THREE. It must be flawless: live, honest, fast, and+screenshot-worthy. A recent fix made the graduated bonding-curve panel, holders, and the+live DEX trade tape work; this pass takes the whole page to a world-class bar.++## Where this lives (real files)+- `pages/three-token.html` + `src/three-token-page.js` — the page.+- `src/widgets/bonding-curve.js` — graduated/bonding curve widget.+- `src/pump/three-token-data.js` — shared $THREE data store.+- `api/three-token/[action].js` — `/stats`, `/leaderboard`, `/burns`, `/activity`.+- `api/pump/dex-trades.js` — live DEX trade feed (graduated coin).+- `src/swap-jupiter.js` — buy flow.++## Current state & gaps+- Core data now renders, but: loading states are thin; the buyback panel needs A01's real run data + Solscan links; the live tape should reconnect cleanly; mobile polish and microinteractions can go further.+- The "Why hold" pillars should each deep-link to live proof (buybacks, reflections, tiers, economy dashboard from A05).++## Build this+1. **Every state designed:** skeletons for header stats, curve, tape, and buyback panel; recoverable error states with a real retry; empty states that tell the user what's next.+2. **Live integrity:** the DEX trade tape polls/streams reliably with reconnect + "Live/Reconnecting" status; header price/mcap/volume/holders refresh without layout shift; numbers never show `NaN`/`$0` when real data exists.+3. **Proof links:** buyback panel shows real runs (A01) with Solscan links; "Why hold" pillars link to the economy/trust dashboard (A05), reflections, and tiers.+4. **Buy conversion:** prominent, fast buy via `swap-jupiter.js` with tier-aware messaging; copy-CA microinteraction; "you'd be holder #N" social proof from the leaderboard.+5. **Performance & a11y:** lazy-load heavy widgets, debounce, `prefers-reduced-motion` respected; semantic landmarks, ARIA, keyboard, focus rings; perfect at 320/768/1440.+6. **SEO/OG:** accurate title/description, dynamic OG image with live price/mcap.++## Out of scope+- Building buyback/reflection execution (A01/A02) — consume their outputs.++## Definition of done+- [ ] All states designed; no console errors/warnings; no layout shift on data arrival.+- [ ] Live tape reconnects; header refreshes cleanly; buy flow works end-to-end on desktop + mobile.+- [ ] Proof links resolve to live on-chain receipts; "Why hold" pillars all link somewhere real.+- [ ] Lighthouse: a11y ≥95, perf ≥90 on mobile; `npx vitest run` green.+- [ ] Changelog entry; committed + pushed to both remotes.++## Verify+- Exercise the page in a real browser (desktop + 320px); Network tab shows real calls; click every link.diff --git a/prompts/production-1b/B02-onboarding-wizard.md b/prompts/production-1b/B02-onboarding-wizard.mdnew file mode 100644index 000000000..8682505f9--- /dev/null+++ b/prompts/production-1b/B02-onboarding-wizard.md@@ -0,0 +1,39 @@+# B02 — Onboarding / Get Started wizard production pass++> Phase B · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+`/start` is the funnel: avatar → name/brain → skills → deploy → earn. Every drop-off here+is a lost user and lost lifetime revenue. Make the wizard bulletproof, fast, and+confidence-inspiring so a first-time visitor reaches a deployed, earning agent without+hitting a single dead end.++## Where this lives (real files)+- `src/start.js` (~836 lines) — the 5-step wizard; persists to sessionStorage.+- `src/create-agent.js` — the fuller create flow (reconcile shared steps).+- Avatar sources: `src/forge.js`, scan, gallery; identity/deploy: `api/_lib/onchain-deploy.js`.+- Auth: `src/wallet-auth.js`; payment: `src/payment-modal.js`.++## Current state & gaps+- Thin loading states (only ~1), avatar upload/generation errors not explicitly handled, no skill-selection validation, no pre-deploy wallet check, no post-deploy next-step.++## Build this+1. **Resilient steps:** every step has loading/empty/error states; avatar generation/upload failures offer retry or an alternate source; skill selection validates dependencies/conflicts.+2. **Guard the deploy:** require a connected wallet (or guest-to-wallet upgrade) before the deploy step; show exactly what deploy costs and what the user gets.+3. **Resumable:** persist progress (already sessionStorage) and let a returning user resume; never lose entered data on reload or error.+4. **Post-deploy success:** a designed success state with the live agent link, embed snippet, "list on marketplace," and "fund/earn" next steps — turn completion into the next action.+5. **Instrumentation:** fire funnel events at each step (entered/completed/abandoned) so drop-off is measurable (ties into G06).+6. **A11y + mobile:** keyboard-navigable steps, focus management on step change, perfect at 320px.++## Out of scope+- Rebuilding the avatar generator (B05) or auth (B06) — wire to them.++## Definition of done+- [ ] Every step has all states; no path can dead-end; reload/resume preserves state.+- [ ] Deploy is gated on wallet + clear cost; success state offers real next actions.+- [ ] Funnel events fire; a11y + mobile verified; no console errors.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Complete the wizard end-to-end as a brand-new user on desktop + 320px; deploy a real agent; abandon mid-way and resume.diff --git a/prompts/production-1b/B03-payment-and-swap.md b/prompts/production-1b/B03-payment-and-swap.mdnew file mode 100644index 000000000..f6b2a7542--- /dev/null+++ b/prompts/production-1b/B03-payment-and-swap.md@@ -0,0 +1,39 @@+# B03 — Payment modal + Jupiter swap production pass++> Phase B · Depends on: A11 (shared modal) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+These two flows handle real money: the skill/asset payment modal and the token swap.+Any rough edge here is a direct revenue leak and a trust hit. Harden both to bank-grade+reliability and clarity across wallets, networks, and failure modes.++## Where this lives (real files)+- `src/payment-modal.js` (~728 lines) — skill purchase, wallet connect, USDC balance, settle.+- `src/swap-jupiter.js` (~962 lines) — one-click swap (USDC ↔ assets), multi-chain.+- `api/x402/` + `api/_lib/x402/` — settlement.+- `src/wallet-auth.js` — wallet/session.++## Current state & gaps+- Payment: wallet-connect errors are generic; no retry UI; insufficient-funds flow not validated across all wallets; no timeout handling for a hung payment.+- Swap: network-switch errors not surfaced; quote timeout/refresh missing; cross-chain bridge failures can show a blank state; slippage warnings missing on volatile pairs.++## Build this+1. **Payment modal:** specific, recoverable errors (network vs balance vs rejected); explicit retry / switch-wallet; insufficient-funds → top-up; bounded timeout with a clear "still pending / cancel" state; success shows a verifiable receipt.+2. **Swap:** quote freshness with auto + manual refresh and a countdown; explicit network-switch handling; bridge/cross-chain failures surface a real error + retry, never a blank; slippage + price-impact warnings; min-received shown.+3. **Wallet matrix:** verified on Phantom + Solflare (and document any wallet-specific quirks); graceful path when no wallet is installed.+4. **A11y + mobile:** focus trap, ESC to close, keyboard operable, amount entry usable at 320px.+5. **Telemetry:** record payment/swap attempts + outcomes (success/fail/reason) for G06.++## Out of scope+- The universal 402 handler structure (A11) — this hardens the modal internals it reuses.++## Definition of done+- [ ] Every error is specific + recoverable; timeouts handled; receipts verifiable.+- [ ] Swap shows fresh quotes, slippage/impact, min-received; bridge failures handled.+- [ ] Verified on Phantom + Solflare, desktop + 320px, keyboard-only.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Pay with: empty balance, rejected signature, network mismatch, and success — each shows the right state.+- Swap a volatile pair: see slippage warning + min-received; force a stale quote → refresh works.diff --git a/prompts/production-1b/B04-marketplace.md b/prompts/production-1b/B04-marketplace.mdnew file mode 100644index 000000000..346d8c309--- /dev/null+++ b/prompts/production-1b/B04-marketplace.md@@ -0,0 +1,39 @@+# B04 — Marketplace + detail + creator profiles production pass++> Phase B · Depends on: B03 (payment) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The marketplace is where supply (agents, skills, avatars) meets demand and where GMV — and+the platform's 50%-to-buyback revenue — is generated. It's already large and capable; this+pass closes the gaps that cost conversions and makes browsing → buying frictionless.++## Where this lives (real files)+- `src/marketplace.js` (~8.4k lines) + `src/marketplace-detail.js` — browse/search, fork, buy skills, creator profiles, live chat preview, ratings.+- `src/marketplace-analytics.js` (~197 lines) — stats (under-built).+- `src/payment-modal.js` — purchase.+- `api/` marketplace endpoints + `api/_lib/skill-license-onchain.js` — skill licenses.++## Current state & gaps+- Detail avatar can stay on an emoji placeholder if render fails; live chat preview (SSE) drops silently with no reconnect; creator-profile modal lacks a skeleton; mobile sidebar may not fully render <600px; skill-purchase → agent-chat handoff unverified; rating freshness/weighting undocumented.+- Analytics surface is thin (no clear chart lib, no "last updated," mobile axis overlap, generic error).++## Build this+1. **Detail integrity:** guarantee the 3D avatar renders or shows a designed fallback (never a stuck emoji); live chat preview reconnects with backoff + status; creator modal has a skeleton.+2. **Buy → use loop:** after purchasing a skill, the buyer lands in the agent with the skill active; show it in their collection (`/collection`). Verify the on-chain skill-license path end-to-end.+3. **Search/sort/filter:** URL-encode state so back/forward and sharing work; designed empty state for no results; pagination/infinite scroll without layout shift.+4. **Analytics rebuild:** real charts with a named lib, "updated Xm ago," CSV export, mobile-legible axes, and a fallback to cached history on API failure.+5. **Mobile + a11y:** sidebar/hamburger works <600px; cards keyboard-navigable; ratings accessible.++## Out of scope+- The payment modal internals (B03) — reuse them.++## Definition of done+- [ ] Detail avatar never stuck on placeholder; chat preview reconnects; creator modal skeleton.+- [ ] Purchase → skill active in agent → visible in collection, verified on-chain.+- [ ] Search/sort/filter state in the URL; empty state designed; no layout shift.+- [ ] Analytics shows real charts + last-updated + export, mobile-legible.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Buy a skill end-to-end; confirm it's usable + in `/collection`; share a filtered URL and reopen it.diff --git a/prompts/production-1b/B05-forge-end-to-end.md b/prompts/production-1b/B05-forge-end-to-end.mdnew file mode 100644index 000000000..1a738e34c--- /dev/null+++ b/prompts/production-1b/B05-forge-end-to-end.md@@ -0,0 +1,37 @@+# B05 — Forge (text/image → 3D) end-to-end production pass++> Phase B · Depends on: D01 (pipeline) ideally · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Forge is the platform's "wow" — text/photos → a real 3D model — and a primary paid surface+(quality tiers). The magic only converts if it's reliable and honest about progress,+failures, and cost. Take the whole generate → reveal → refine → pay loop to production.++## Where this lives (real files)+- `src/forge.js` (~2.5k lines) + `src/forge-pay.js`, `src/forge-enhance.js`, `src/forge-prompt-studio.js`, `src/forge-optimize.js`, `src/forge-reveal.js`, `src/forge-ar.js`.+- `api/forge.js`, `api/x402/forge.js`, `api/_lib/forge-health.js`, `api/_lib/forge-tiers.js`.+- Generation workers: `workers/model-*`, `workers/trellis`, etc.; free lane: NVIDIA NIM (TRELLIS).++## Current state & gaps+- 5-min poll can time out silently; engine failures don't say which engine or why; high-tier payment integration (`forge-pay.js`) handoff unclear; sketch-mode availability depends on a catalog health check with no clear fallback; multi-view fusion doesn't show which views were used; free-tier rate limits aren't surfaced; AR/download not validated on mobile.++## Build this+1. **Honest progress:** real per-stage progress; on timeout, a "taking longer than usual — keep waiting / retry / try another engine" state, never a silent stall.+2. **Engine transparency + fallback:** show the active engine + health; on failure, name it and auto-fall-back across the engine chain (free NIM/TRELLIS primary), surfacing what happened.+3. **Paid tiers wired:** Pro/High generation routes cleanly through `forge-pay.js` + the 402 modal (A11), tier discount applied (A03); show cost before charging; receipt after.+4. **Quotas surfaced:** show remaining free generations and the upgrade path when the free lane is exhausted.+5. **Result actions:** reliable download (GLB), AR (WebXR/Quick Look) tested on mobile, save-to-account, list-on-marketplace, and "rig + animate" handoff (D01).+6. **All states + a11y + mobile:** loading/empty/error designed; keyboard + screen-reader labels; usable at 320px.++## Out of scope+- The generation worker internals/pipeline reliability (**D01**) — wire to and surface them.++## Definition of done+- [ ] No silent timeouts; engine failures are explained and fall back; sketch/multi-view degrade gracefully.+- [ ] Paid tiers charge correctly (tier discount applied) with cost preview + receipt; free quota shown.+- [ ] Download + AR + save + list all work, verified on mobile.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Generate free + paid; force an engine failure → fallback + message; test AR + download on a phone.diff --git a/prompts/production-1b/B06-auth-and-session.md b/prompts/production-1b/B06-auth-and-session.mdnew file mode 100644index 000000000..92150cc84--- /dev/null+++ b/prompts/production-1b/B06-auth-and-session.md@@ -0,0 +1,37 @@+# B06 — Auth (sign-in/up, session, wallet) production pass++> Phase B · Depends on: none (foundational) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Auth is the foundation under every paid action and saved asset. Confusing sign-in, silent+session expiry, or wallet mismatches quietly destroy conversion and trust. Make the entire+identity layer obvious, resilient, and secure across email, social, and wallet.++## Where this lives (real files)+- `src/wallet-auth.js`, `pages/login.html` (+ register flow).+- `api/_lib/auth.js` — OAuth/JWT, refresh tokens, session rotation, CSRF, API keys, Privy.+- `api/_lib/agent-wallet.js` — custodial wallet binding.++## Current state & gaps+- Session timeout / expiry handling not surfaced to the user; "remember me" persistence unclear; social-login + wallet-connect error messaging basic; no clear re-auth on session/wallet mismatch.++## Build this+1. **Clear flows:** designed states for email, GitHub/social, and wallet sign-in + sign-up; specific errors (wrong creds, unverified email, popup blocked, wallet rejected) with recovery.+2. **Session lifecycle:** on expiry, a non-destructive "your session expired — sign in to continue" prompt that resumes the in-progress action; honor refresh-token rotation; "remember me" with a documented, secure persistence.+3. **Wallet ↔ account binding:** handle the case where the connected wallet differs from the signed-in account (prompt to switch/link, never silently act); make linking/unlinking wallets clear.+4. **Email verification + reset:** working verify + password-reset with sensible link expiry and duplicate-email handling.+5. **Security:** preserve CSRF + HttpOnly cookies; never expose tokens to JS; rate-limit auth attempts; (optionally) bind session to coarse device/IP signal with mobile tolerance.+6. **A11y + mobile:** labels, focus, keyboard, 320px.++## Out of scope+- Deep token-binding/replay hardening (that's **G05/E08**) beyond the basics here.++## Definition of done+- [ ] All sign-in/up paths work with specific, recoverable errors; verification + reset work.+- [ ] Session expiry prompts and resumes the user's action; wallet/account mismatch handled explicitly.+- [ ] Auth attempts rate-limited; tokens never exposed; a11y + mobile verified.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Sign in via each method; let a session expire mid-action and confirm resume; connect a wallet that differs from the account.diff --git a/prompts/production-1b/B07-dashboard-hub.md b/prompts/production-1b/B07-dashboard-hub.mdnew file mode 100644index 000000000..70ad00068--- /dev/null+++ b/prompts/production-1b/B07-dashboard-hub.md@@ -0,0 +1,37 @@+# B07 — Dashboard hub + account + analytics + API keys production pass++> Phase B · Depends on: B06 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The dashboard is where a user manages agents, avatars, payments, API keys, MCP servers,+and monetization — the cockpit that turns a casual user into a power user and a payer.+Make every panel real, actionable, and consistent.++## Where this lives (real files)+- `src/dashboard/` — dashboard shell + panels (account, analytics, API keys, MCP, monetization, billing).+- `pages/dashboard*.html`, `data/pages.json` — routes incl. `/dashboard/three-token`, `/dashboard/holders`, `/dashboard/account`, `/dashboard/analytics`.+- `api/` — keys, usage, billing, MCP registration endpoints.++## Current state & gaps+- Multi-tab/state sync unclear; API-key rotation UX; billing/usage export; MCP server registration wizard; mobile nested-tab navigation.++## Build this+1. **Every panel complete:** agents/avatars list with real actions (edit, delete-with-confirm, archive); each panel has loading/empty/error/populated states and a helpful empty state that drives the next action.+2. **API keys:** create/rotate/revoke with clear one-time-reveal, scopes, last-used, and copy affordance; never re-expose a secret.+3. **Analytics:** real API-call volume + x402 spend + per-agent breakdowns, with date range, CSV export, and "updated Xm ago."+4. **Monetization/billing:** show earnings (from skills/x402/reflections), payout history with Solscan links, and pricing controls; everything reconciles with the on-chain ledger.+5. **MCP registration:** a guided flow to register/list MCP servers tied to the account.+6. **Consistency + mobile + a11y:** shared layout/tokens; nested tabs navigable on mobile; keyboard + focus management.++## Out of scope+- The token economy dashboard (A05) — link to it.++## Definition of done+- [ ] Every panel has all states + real actions; destructive actions confirm.+- [ ] API keys rotate safely; analytics export works; billing reconciles with on-chain data.+- [ ] MCP registration works; mobile nav + a11y verified; no console errors.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Rotate an API key and confirm the old one stops working; export analytics CSV; register an MCP server; navigate every tab on mobile.diff --git a/prompts/production-1b/B08-agent-studio.md b/prompts/production-1b/B08-agent-studio.mdnew file mode 100644index 000000000..7cd719e51--- /dev/null+++ b/prompts/production-1b/B08-agent-studio.md@@ -0,0 +1,38 @@+# B08 — Agent Studio (brain/memory/body/money/skills) production pass++> Phase B · Depends on: B06 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Agent Studio is where users invest effort into their agents — the deeper the investment,+the higher the retention and the more they spend. It's a sophisticated multi-tab editor;+this pass closes the reliability gaps (concurrent edits, optimistic rollback, offline) that+erode trust in a tool people rely on.++## Where this lives (real files)+- `src/studio/studio-shell.js`, `src/studio/agent-studio-store.js` — shell + store (debounced PUT, optimistic UI, live preview).+- `src/studio/brain/`, `src/studio/memory/`, `src/studio/body/`, `src/studio/money/`, `src/studio/skills/` — sub-studios.+- `api/` agent update endpoints; `src/agent-presence.js` — live avatar presence.++## Current state & gaps+- Concurrent edits across tabs = last-write-wins with no conflict signal; optimistic rollback on PUT failure can flicker; sub-studio state is isolated so avatar updates can lag; offline/edit-queue behavior unclear.++## Build this+1. **Conflict handling:** detect a concurrent edit (version/updated_at check) and prompt to reload/merge instead of silently clobbering; show "saved / saving / failed" status clearly.+2. **Robust optimistic UI:** on PUT failure, roll back cleanly without flicker and surface a retry; never leave the UI showing an unsaved value as saved.+3. **Shared live preview:** brain/memory/body/money/skills changes reflect in the shared 3D preview promptly; presence updates don't flicker on large edits.+4. **Offline/queue:** detect offline, queue edits, and reconcile on reconnect (or clearly block with a message) — no lost work.+5. **Each sub-studio complete:** brain (LLM + prompt), memory (CRUD with the memory model), body (avatar + outfit), money (wallet + pricing), skills (install/configure/remove) each have all states and validate input.+6. **A11y + mobile:** tabs and editors keyboard-navigable; usable on tablet.++## Out of scope+- The avatar pipeline (D01) and payment internals (B03) — wire to them.++## Definition of done+- [ ] Concurrent edits are detected and never silently clobber; save status always accurate.+- [ ] Optimistic updates roll back cleanly; offline edits queue + reconcile or block clearly.+- [ ] Live preview reflects every sub-studio; each sub-studio has all states + validation.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Edit the same agent in two tabs → conflict surfaced; kill the network mid-edit → queued/blocked, no data loss; change body → preview updates.diff --git a/prompts/production-1b/B09-agent-profile-and-embed.md b/prompts/production-1b/B09-agent-profile-and-embed.mdnew file mode 100644index 000000000..4d4782dbe--- /dev/null+++ b/prompts/production-1b/B09-agent-profile-and-embed.md@@ -0,0 +1,37 @@+# B09 — Agent profile pages + embeddable widget production pass++> Phase B · Depends on: A10 (reputation) optional · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Agent profiles are the platform's shareable unit — the link that spreads on social, the+embed that lives on other sites. Every profile is a billboard and a storefront. Make them+load fast, render the 3D agent flawlessly, convert to chat/buy, and embed anywhere.++## Where this lives (real files)+- `src/agent-detail.js` (~2.1k lines), `src/agent-home.js`, `src/agent-detail-market.js`, `src/agent-embed-modal.js`.+- `avatar-sdk/` (`<agent-3d>` web component), `page-agent-sdk/`.+- OG: `api/agent-og.js`, `api/a-og.js`; identity: `contracts/`, ERC-8004/Solana badges.++## Current state & gaps+- On-chain identity badges load async and can show a placeholder; embed code needs cross-browser verification; fork semantics (does it copy memory/skills?) undocumented; private-agent access shows ambiguous 404 vs no-access.++## Build this+1. **Flawless render:** the 3D agent loads with a skeleton then renders, or a designed fallback — never a stuck placeholder; identity badges resolve without layout shift.+2. **Convert:** prominent chat + buy/fork CTAs; show reputation (A10) and launch history; "powered by three.ws" embed builder that produces a working snippet, tested on a real third-party page.+3. **Fork/remix clarity:** state exactly what a fork copies (body/brain/skills/memory) and complete the flow end-to-end.+4. **Access control:** private agents return a clear "no access / sign in" state, not a bare 404; public ones are crawlable.+5. **Dynamic OG:** per-agent OG image (avatar + name + stats) so shares look great.+6. **Perf + a11y + mobile:** lazy-load 3D, `prefers-reduced-motion`, semantic structure, 320px.++## Out of scope+- Reputation scoring (A10) — display it.++## Definition of done+- [ ] 3D render + badges never stick on placeholder; embed snippet works on an external page across Chrome/Safari/Firefox.+- [ ] Chat/buy/fork CTAs work; fork copies the documented set; private access state is clear.+- [ ] Dynamic OG renders; Lighthouse a11y ≥95; mobile verified.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Open a profile, chat, fork; paste the embed on a scratch HTML page and confirm it loads; share the URL and check the OG preview.diff --git a/prompts/production-1b/B10-launch-and-launches-feed.md b/prompts/production-1b/B10-launch-and-launches-feed.mdnew file mode 100644index 000000000..f53d6639e--- /dev/null+++ b/prompts/production-1b/B10-launch-and-launches-feed.md@@ -0,0 +1,37 @@+# B10 — Launch-a-coin + launches feed production pass++> Phase B · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Agents launching coins through three.ws — and the public feed of those launches — is both+a revenue surface and a core product loop. The feed is the proof that the platform is alive.+Make launching reliable and the feed beautiful, accurate, and never empty-looking.++## Where this lives (real files)+- `src/launches.js` (~907 lines) — live feed of agent-launched coins; `/api/pump/launches` over `pump_agent_mints`.+- Launch flow: `api/pump/*`, vanity mint (`scripts/pump-vanity-grind.mjs`, vanity grinder), `api/x402/pump-launch.js`.+- `src/pump/three-token-data.js` for shared market data.++## Current state & gaps+- Launches feed has **no empty state**; market data streams after registry rows so cards layout-shift; identicon fallback unclear; marquee built from page 1 (breaks if empty); cursor-light effect won't work on mobile; 60s refresh may prepend stale items.+- The launch flow (vanity mint, deploy, redirect) needs a confirmed-success path with no race.++## Build this+1. **Feed states:** designed empty state ("no launches yet — be the first") and error/loading skeletons; reserve card sizes so streaming market data never shifts layout.+2. **Launch flow:** progress through vanity-mint → deploy → confirm; guarantee the success state links to the live coin (and the in-platform coin world if applicable) with no redirect race; handle failure with a clear retry.+3. **Compliance:** these are platform launch records (allowed per CLAUDE.md's launch-directory exception) — render them as records, never hardcode/recommend any non-$THREE mint; `$THREE` remains the only coin promoted.+4. **Polish:** identicon fallback always renders; marquee handles empty/short pages; disable cursor-light on touch; refresh merges without duplicates or stale prepends.+5. **A11y + mobile + perf:** keyboard-navigable cards, lazy-loaded media, 320px.++## Out of scope+- The pump.fun launcher's generic mint input (leave coin-agnostic per CLAUDE.md).++## Definition of done+- [ ] Feed has empty/error/loading states; zero layout shift on market-data arrival.+- [ ] Launch flow confirms success with a working coin link and no race; failures recover.+- [ ] Compliance respected ($THREE only promoted); marquee/identicon/refresh robust.+- [ ] Mobile + a11y verified; `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Load the feed with zero results (mock) → empty state; launch a coin on a preview and confirm the success link; watch a refresh cycle for shifts/dupes.diff --git a/prompts/production-1b/C01-oracle-and-arm.md b/prompts/production-1b/C01-oracle-and-arm.mdnew file mode 100644index 000000000..05a3c087e--- /dev/null+++ b/prompts/production-1b/C01-oracle-and-arm.md@@ -0,0 +1,39 @@+# C01 — Oracle conviction engine + Arm automation production pass++> Phase C · Depends on: B03 (payment), B06 (auth) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The Oracle (AI conviction scoring for pump.fun launches) and "Arm" (let an agent trade on+that conviction automatically) are flagship intelligence features and a retention magnet+for traders. Arm in particular moves real money with thin instrumentation today — that's a+risk. Harden both to production and make the automation trustworthy.++## Where this lives (real files)+- `src/oracle.js` (~1.7k lines) — conviction score (pedigree/structure/narrative/momentum), watchlists, wallet leaderboard, force graph.+- `src/arm.js` (~333 lines) — configure agent trading (min conviction, sizing, caps, filters, Telegram alerts, simulate vs live).+- `workers/oracle/` — settle/agent/score loops; `api/cron/oracle-*`.+- `src/activity.js` — live feed of agent actions (pair with **C02**).++## Current state & gaps+- Oracle: graph failures show a generic message with no retry; wallet leaderboard has no pagination; force-graph load timeout unhandled.+- Arm: **under-instrumented for what it does** — only ~2 catch blocks for money-moving config; no loading states; wallet state not validated before enabling live trading; cap validation, Telegram health, and simulate→live safeguards unclear.++## Build this+1. **Arm safety first:** validate wallet + balance before enabling live mode; enforce + validate position/daily/open caps server-side; require a successful simulation (or explicit acknowledgement) before going live; a prominent live-vs-simulate indicator and a kill switch.+2. **Arm reliability:** loading/empty/error states for agent load + config save; verify the Telegram alert path actually delivers (health check) before promising alerts; record every automated trade with reasoning for the activity feed.+3. **Oracle resilience:** graph/score failures auto-retry with backoff + a manual retry; force-graph has a skeleton + timeout fallback; wallet leaderboard paginates; score methodology is explained in-UI (build trust).+4. **Honesty:** never imply a score is a recommendation to buy a non-$THREE coin — present it as analytics/intelligence (CLAUDE.md: $THREE is the only coin promoted; coin records/analytics are a product feature, not endorsement).+5. **A11y + mobile + perf:** keyboard, focus, lazy-load the graph, 320px.++## Out of scope+- The activity feed surface itself (**C02**) — emit to it.++## Definition of done+- [ ] Arm cannot enable live trading without a valid wallet + caps + simulation/ack; kill switch works; every auto-trade is logged with reasoning.+- [ ] Telegram alerts verified deliverable; Arm has all states.+- [ ] Oracle graph/leaderboard resilient (retry, pagination, skeleton); methodology explained.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Try to arm live with no wallet/over-cap → blocked with a clear reason; run a simulation; trigger a test alert and confirm delivery; fail the graph fetch → retry works.diff --git a/prompts/production-1b/C02-activity-trending-feed-community.md b/prompts/production-1b/C02-activity-trending-feed-community.mdnew file mode 100644index 000000000..2b1a2ddb3--- /dev/null+++ b/prompts/production-1b/C02-activity-trending-feed-community.md@@ -0,0 +1,39 @@+# C02 — Activity + Trending + Feed + Community production pass++> Phase C · Depends on: C01 (emits activity) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+These are the "the platform is alive" surfaces — live agent actions, what's hot, what your+network is doing, who's building. Vibrant, honest, real-time social proof drives sessions+and word-of-mouth. Make them real-time, accurate, and never look dead.++## Where this lives (real files)+- `src/activity.js` — live feed of autonomous agent actions (Oracle conviction), filterable by tier/mode, with outcomes.+- `src/trending.js` — top agents (by activity) + top Oracle coins (24h/7d/all-time).+- `src/feed.js` — activity from followed people/agents.+- `src/community.js` — featured creators/builds/conversations.+- Backing endpoints under `api/` (verify each exists and returns real data).++## Current state & gaps+- Some of these modules are thin or unverified; data freshness, follow/unfollow persistence, time-window switching (loses scroll), and activity-weighting definitions need to be real and documented.++## Build this+1. **Activity feed:** real-time stream (SSE/poll) of agent actions with outcome tracking; filters by tier/mode; designed empty/error states; reconnect with status; each item links to the agent and (where applicable) the on-chain tx.+2. **Trending:** real ranking with a documented metric; window switches (24h/7d/all) preserve scroll; "updated Xm ago"; empty/loading states.+3. **Feed:** durable follow/unfollow; chronological + (optional) ranked; mute/block; mobile-legible long content.+4. **Community:** real featured content (not hardcoded); curation source documented; links resolve.+5. **Honesty + compliance:** coins shown are records/analytics; $THREE remains the only promoted coin.+6. **A11y + mobile + perf:** keyboard, lazy media, 320px.++## Out of scope+- Oracle/Arm internals (**C01**).++## Definition of done+- [ ] Activity streams in real time with reconnect + outcomes; trending ranks by a documented metric and preserves scroll across windows.+- [ ] Follow/unfollow persists; community shows real featured content; all links resolve.+- [ ] All states designed; no module shows hardcoded/sample data; mobile + a11y verified.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Watch the activity feed update live; follow an agent and confirm it appears in your feed after reload; switch trending windows without losing place.diff --git a/prompts/production-1b/C03-leaderboards-smartmoney-radar.md b/prompts/production-1b/C03-leaderboards-smartmoney-radar.mdnew file mode 100644index 000000000..a3c5753f0--- /dev/null+++ b/prompts/production-1b/C03-leaderboards-smartmoney-radar.md@@ -0,0 +1,40 @@+# C03 — Leaderboards + Smart Money + Radar production pass++> Phase C · Depends on: A04 (holder snapshot) for holder board · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Provable track records (trader P&L), proven-money signals (smart money), risk intelligence+(radar), and the $THREE holder leaderboard are credibility surfaces — they make the+platform feel like a serious financial product. Make every number defensible and every+board fast and fair.++## Where this lives (real files)+- Trader: `src/leaderboard.js` / `src/kol/*`; on-chain P&L attestation `api/cron/trader-score-attest.js`.+- Walk: `src/walk-leaderboard.js`.+- Holders: `api/three-token/[action].js` `/leaderboard` + `api/_lib/coin/three-holders.js`.+- Smart money: `src/smart-money.js` + `api/cron/smart-money-*`.+- Radar: `src/radar.js` (bundle vs organic, wallet concentration, dev behavior, risk flags).++## Current state & gaps+- Data freshness, pagination for large boards, and methodology docs are inconsistent; P&L/score formulas undocumented; radar risk flags lack explanations + confidence; holder board should exclude treasury/AMM/LP wallets (from A04).++## Build this+1. **Methodology transparency:** document and surface how each metric is computed (P&L realized/unrealized, win rate, conviction, reputation, risk flags) with confidence where relevant — credibility comes from being checkable.+2. **Performance:** paginate/virtualize large boards; "updated Xm ago"; cache with sane TTL; no jank at thousands of rows.+3. **Holder board:** exclude treasury/AMM/LP wallets (flagged in A04); show % of supply, tier, and rank; link wallets to Solscan.+4. **Radar:** every risk flag has a plain-language explanation + confidence; never present as buy/sell advice for any non-$THREE coin (analytics only).+5. **Anti-gaming:** basic cheat detection (e.g. teleport detection on walk, wash-trade hints on trader) noted where feasible.+6. **A11y + mobile:** sortable tables keyboard-operable; legible at 320px.++## Out of scope+- Copy-trading execution (treat as a separate flow if present) beyond linking to it.++## Definition of done+- [ ] Each board documents + surfaces its methodology; large boards paginate without jank.+- [ ] Holder board excludes treasury/AMM/LP and links to Solscan; radar flags explained + confidence.+- [ ] All boards have freshness + all states; mobile + a11y verified.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Open each board; confirm methodology is visible, holder board excludes the AMM vault, and large boards scroll smoothly.diff --git a/prompts/production-1b/C04-galleries-and-discovery.md b/prompts/production-1b/C04-galleries-and-discovery.mdnew file mode 100644index 000000000..70bbd51c1--- /dev/null+++ b/prompts/production-1b/C04-galleries-and-discovery.md@@ -0,0 +1,37 @@+# C04 — Galleries (avatars, animations, agent discovery) production pass++> Phase C · Depends on: none · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+Discovery surfaces — the agent directory, avatar gallery, animation gallery — are how users+find what to use, fork, and buy. Rich, fast, filterable galleries with great 3D previews+turn browsing into creating and buying.++## Where this lives (real files)+- `src/agents-directory.js` (~619 lines) — agent discovery with on-chain identity badges.+- Avatar gallery + animation library (`src/animation-library.js` ~745 lines) and their pages in `data/pages.json`.+- `avatar-sdk/` viewer for 3D previews.++## Current state & gaps+- Badges load async (placeholder flash); search/sort state not URL-encoded (back button loses filters); pagination for large sets; mobile grid performance; avatar download permissions unclear; animation compatibility (humanoid-only) not enforced; preview load times for large assets.++## Build this+1. **Fast 3D previews:** lazy-load and virtualize grids; thumbnail/poster first, full 3D on interaction; skeletons; never block scroll on model loads.+2. **Filter/sort/search in the URL:** shareable, back-button-safe; designed empty state for no results.+3. **Identity badges:** resolve without layout shift; skeleton instead of placeholder flash.+4. **Permissions & compatibility:** clarify + enforce avatar download permissions; warn/guard when applying a non-humanoid-compatible animation (ties to the universal rig rules in CLAUDE.md).+5. **Apply/use loop:** "apply animation to my avatar" with an avatar picker; "use this avatar" handoff to studio/create.+6. **A11y + mobile + perf:** keyboard-navigable cards, contrast, 320px, smooth at 1000+ items.++## Out of scope+- The avatar generation/rig pipeline (**D01**) — link to it.++## Definition of done+- [ ] Grids are fast + virtualized with skeletons; filter/search/sort live in the URL; empty state designed.+- [ ] Badges resolve without flash; download permissions + animation compatibility enforced.+- [ ] Apply/use handoffs work; mobile + a11y verified; smooth at 1000+ items.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Filter a gallery, copy the URL, reopen → same filters; apply an animation to an avatar; scroll 1000+ items without jank.diff --git a/prompts/production-1b/D01-avatar-pipeline-reliability.md b/prompts/production-1b/D01-avatar-pipeline-reliability.mdnew file mode 100644index 000000000..cbf030d21--- /dev/null+++ b/prompts/production-1b/D01-avatar-pipeline-reliability.md@@ -0,0 +1,40 @@+# D01 — Avatar pipeline reliability (forge → auto-rig → animate) hardening++> Phase D · Depends on: none (foundational for B05, C04, D2–D4) · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The whole 3D product rests on one pipeline: generate a mesh → auto-rig it → retarget the+animation library onto it → render it everywhere. CLAUDE.md mandates universal animation+(no rig allowlist). When any stage silently fails, avatars T-pose, animations break, and+the magic dies. Make the pipeline observably reliable end-to-end.++## Where this lives (real files)+- `src/glb-canonicalize.js` — maps diverse rig bone names (Mixamo, Avaturn, Unreal, VRM/VRoid, Daz, MakeHuman, Blender `.L`, etc.) to the canonical set.+- `src/animation-retarget.js` — retargets idle/walk onto canonicalized rigs; `AnimationManager.supportsCanonicalClips()` gate.+- `tests/glb-canonicalize.test.js` — bone-mapping coverage.+- `api/_lib/auto-rig.js`, `api/cron/auto-rig-sweep.js` — auto-rig + backfill sweep.+- Workers: `workers/unirig`, `workers/model-*`, `workers/remesh`, `workers/rembg`, etc.++## Current state & gaps+- New skeleton conventions can slip through to a bind-pose T-pose instead of falling back to the default rig; auto-rig failures need clear surfacing + retry; the auto-rig sweep should backfill static avatars; `auto-rig.js` fetches user URLs without SSRF validation (overlaps E08).++## Build this+1. **No silent T-pose:** guarantee a rig that genuinely can't be skeleton-driven falls back to the default rig via `supportsCanonicalClips()` — never a bind-pose T-pose. Add a diagnostic that flags any avatar rendering un-animated.+2. **Bone-map coverage:** add a fixture-backed test for every supported convention in `glb-canonicalize.js`; when a new convention appears, the path to add a mapping (+ test case) is documented and easy.+3. **Auto-rig reliability:** surface rig job status (queued/running/failed) to the user with retry; the sweep cron backfills un-rigged static avatars and reports counts; alert on sustained failures.+4. **Worker health:** each generation/rig worker reports health; failures propagate to `forge-health.js` + ops, not just local logs.+5. **SSRF guard:** validate every user-supplied model URL (https only, no localhost/private ranges) before fetch (coordinate with **E08**).+6. **Golden tests:** a small set of real GLBs across conventions retarget correctly (legs included) in CI.++## Out of scope+- The Forge UI (**B05**) — this is the pipeline beneath it.++## Definition of done+- [ ] No avatar ever T-poses: unsupported rigs fall back to the default rig, proven by a test + a runtime diagnostic.+- [ ] Every bone convention in `glb-canonicalize.js` has a test case; golden GLBs retarget correctly in CI.+- [ ] Auto-rig status + retry surfaced; sweep backfills + reports; worker health propagates to ops.+- [ ] User model URLs SSRF-validated; `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Feed avatars from ≥3 rig conventions → all animate (legs included); feed a non-humanoid prop → default-rig fallback, not T-pose; fail a rig job → status + retry shown.diff --git a/prompts/production-1b/D02-walk-companion-and-playground.md b/prompts/production-1b/D02-walk-companion-and-playground.mdnew file mode 100644index 000000000..27e98fbc8--- /dev/null+++ b/prompts/production-1b/D02-walk-companion-and-playground.md@@ -0,0 +1,36 @@+# D02 — Walk companion + playground + leaderboard + embed production pass++> Phase D · Depends on: D01 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The walk companion is a viral embed — a 3D avatar that strolls across any website, with a+global distance leaderboard and a full playground. It's top-of-funnel reach: every embed is+a billboard. Make it rock-solid, reconnect reliably, and look great on any host and device.++## Where this lives (real files)+- `src/walk.js` (~5k lines), `src/walk-playground.js`, `src/walk-embed-preview.js`, `src/walk-leaderboard.js`, `src/walk-net.js` (networking).+- `walk-sdk/` → `@three-ws/walk`; `/walk`, `/temporary`, `/walk-leaderboard` routes.++## Current state & gaps+- AR passthrough camera-permission denial not clearly handled; `walk-net.js` reconnects only once then stalls; leaderboard sort/pagination state not URL-encoded; mobile joystick sizing not responsive; embed iframe can fail silently if a host blocks third-party frames; Chrome-extension install/permissions undocumented.++## Build this+1. **Resilient networking:** reconnect with exponential backoff (not single-attempt); clear "live/reconnecting/offline" status; no stuck state.+2. **AR + controls:** camera-permission denial → designed fallback (non-AR mode); responsive joystick sized to viewport/orientation; touch + keyboard parity.+3. **Embed robustness:** detect blocked-iframe/CORS and show a fallback message + link; document required embed headers; verify on a real third-party page.+4. **Leaderboard:** URL-encode sort/pagination; document the distance/time scoring; basic cheat detection (teleport); freshness + all states.+5. **Cross-surface avatar:** uses the same pipeline as D01 (no T-pose); diverse avatar picker works.+6. **Perf + a11y + mobile:** steady frame rate, `prefers-reduced-motion`, keyboard, 320px.++## Out of scope+- The avatar pipeline internals (**D01**).++## Definition of done+- [ ] Reconnect is resilient with clear status; AR denial + blocked-embed have designed fallbacks.+- [ ] Leaderboard state in URL with documented scoring + cheat guard; joystick responsive.+- [ ] Embed verified on an external site; `@three-ws/walk` builds; mobile + a11y verified.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Embed on a scratch site (and one that blocks frames → fallback); kill the network mid-walk → reconnects; deny camera → non-AR fallback; play on a phone.diff --git a/prompts/production-1b/D03-irl-and-play-worlds.md b/prompts/production-1b/D03-irl-and-play-worlds.mdnew file mode 100644index 000000000..3973111f0--- /dev/null+++ b/prompts/production-1b/D03-irl-and-play-worlds.md@@ -0,0 +1,39 @@+# D03 — IRL (AR placement) + Play (coin worlds, multiplayer) production pass++> Phase D · Depends on: D01 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+IRL (place 3D agents in your real environment via AR) and Play (a deterministic 3D world+per coin where holders gather, chat, and trade) are the differentiated, shareable+experiences that make three.ws more than a tool. They're also the hardest to make+reliable. Get them to a stable, joinable, no-crash baseline.++## Where this lives (real files)+- `src/irl.js` — AR passthrough, joystick, tap-to-place, location-aware nearby agents; `api/cron/irl-reap.js` (expiry).+- `src/game/boot-avatar.js`, `src/game/coincommunities.js`, `src/game/ambient-crowd.js` — coin worlds.+- `multiplayer/` (`@three-ws/multiplayer`) — position sync, presence; `api/cron/world-health.js`.++## Current state & gaps+- IRL: GPS/compass permission denial handling, placed-agent persistence (local vs server), privacy mode (nearby-only visibility), compass-less device fallback.+- Play: world-generation determinism (seed), multiplayer position-sync reliability, chat delivery under low bandwidth, in-world trade latency, mobile frame rate, exit/save state.++## Build this+1. **IRL permissions + fallback:** graceful handling when GPS/compass denied or absent (heading from GPS, or a manual-orient fallback); placed agents persist with a documented strategy; privacy mode keeps placements nearby-only.+2. **Play determinism:** same seed → same world, verified; reserve a clear loading state while the world boots.+3. **Multiplayer stability:** reliable presence + position sync with interpolation; reconnect on drop; cap concurrent entities for frame rate; `world-health.js` reports degradation.+4. **In-world economy:** chat delivery with a queue indicator on slow links; trades route through the real path with clear pending/success/fail; $THREE-only promotion rules respected (coin worlds render records, not endorsements).+5. **Exit/save:** state persists or is explicitly ephemeral (told to the user); no silent data loss.+6. **Mobile perf:** target ≥30fps on mid-range mobile; reduce draw calls; `prefers-reduced-motion`.++## Out of scope+- The avatar pipeline (**D01**); deep netcode rewrites beyond reliable sync + reconnect.++## Definition of done+- [ ] IRL handles denied/absent sensors with a usable fallback; placements persist per the documented strategy; privacy honored.+- [ ] Play worlds are deterministic; multiplayer syncs reliably with reconnect; degradation reported.+- [ ] In-world chat + trades work with clear states; exit/save behavior is explicit; ≥30fps on mid mobile.+- [ ] `npx vitest run` green; changelog entry; committed + pushed to both remotes.++## Verify+- Enter a coin world twice with the same seed → identical; join from two devices → see each other; deny compass in IRL → fallback; throttle network → chat queue + reconnect.diff --git a/prompts/production-1b/D04-creator-tools.md b/prompts/production-1b/D04-creator-tools.mdnew file mode 100644index 000000000..4bbb61ada--- /dev/null+++ b/prompts/production-1b/D04-creator-tools.md@@ -0,0 +1,42 @@+# D04 — Creator tools (Scene Studio, Compose, Pose, Voice, Scan) production pass++> Phase D · Depends on: D01 · Parallel-safe: yes+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.++## Mission+The creator tools — Scene Studio (3D scene editor), Compose (attach items to avatars), Pose+(animation studio), Voice (voice cloning), Scan (selfie → rigged avatar) — are what turn+consumers into creators, and creators into sellers. Each is powerful but uneven. Bring them+to a dependable, no-lost-work, monetizable baseline.++## Where this lives (real files)+- `src/scene-studio/` (`/scene`, vendored three.js editor), Compose (`/compose`), Pose (`/pose`), Voice (`/voice`), Scan (`/scan`) — confirm exact module paths via `data/pages.json`.+- `avatar-sdk/`, `character-studio/` for shared 3D; `api/` for save/monetize.++## Current state & gaps+- Scene Studio: no autosave (unsaved-work loss), unclear lighting bake vs real-time, no scene-size limits, no mobile path.+- Compose: item-to-bone attachment can be wrong, scale constraints, outfit save/load, export formats.+- Pose: IK convergence errors, timeline scrubbing perf, GLB export validity, monetization not integrated, no mobile posing.+- Voice: recording-quality validation, cloning confidence, privacy/storage policy, cross-agent assignment persistence.+- Scan: camera-permission failures, lighting requirements, face-detection retry, rigging-failure detection, mobile camera API compatibility.++## Build this+For each tool (do them as sub-tasks, all must reach the bar):+1. **No lost work:** autosave/recover where a user invests effort (Scene, Pose, Compose).+2. **Validated output:** exports produce valid GLB/clip JSON (integrity-checked); attachments map to correct bones; rigging/scan failures are detected and explained with retry.+3. **All states + limits:** loading/empty/error states; enforced size/time/quality limits surfaced to the user.+4. **Monetize:** Pose/Compose/Voice outputs can be saved + listed for sale through the real payment path (A11/B03), $THREE economics applied.+5. **Privacy:** Voice/Scan document where recordings/images are stored and how to delete; honor it.+6. **Mobile + a11y:** at minimum a usable mobile path or a clear "best on desktop" with graceful degradation; keyboard + labels.++## Out of scope+- The shared avatar pipeline (**D01**) and payment internals (**B03**) — reuse them.++## Definition of done+- [ ] Each tool: no lost work, valid validated exports, all states, enforced+surfaced limits.+- [ ] Monetization wired for sellable outputs; privacy policy honored for Voice/Scan.+- [ ] Mobile path or graceful degradation; a11y verified; `npx vitest run` green.+- [ ] Changelog entry; committed + pushed to both remotes.++## Verify+- In each tool: invest work → reload → recovered; export → load the file back successfully; (Pose/Voice) list an output for sale and buy it; (Scan) deny camera → clear fallback.diff --git a/prompts/market/00-README-orchestration.md b/prompts/production-campaign/00-README-orchestration.mdsimilarity index 100%rename from prompts/market/00-README-orchestration.mdrename to prompts/production-campaign/00-README-orchestration.mddiff --git a/prompts/market/00b-the-bar.md b/prompts/production-campaign/00b-the-bar.mdsimilarity index 100%rename from prompts/market/00b-the-bar.mdrename to prompts/production-campaign/00b-the-bar.mddiff --git a/prompts/market/B-growth/00-README.md b/prompts/production-campaign/B-growth/00-README.mdsimilarity index 100%rename from prompts/market/B-growth/00-README.mdrename to prompts/production-campaign/B-growth/00-README.mddiff --git a/prompts/market/B-growth/B1-onboarding-activation.md b/prompts/production-campaign/B-growth/B1-onboarding-activation.mdsimilarity index 100%rename from prompts/market/B-growth/B1-onboarding-activation.mdrename to prompts/production-campaign/B-growth/B1-onboarding-activation.mddiff --git a/prompts/market/B-growth/B2-seo-structured-data.md b/prompts/production-campaign/B-growth/B2-seo-structured-data.mdsimilarity index 100%rename from prompts/market/B-growth/B2-seo-structured-data.mdrename to prompts/production-campaign/B-growth/B2-seo-structured-data.mddiff --git a/prompts/market/B-growth/B3-analytics-funnel.md b/prompts/production-campaign/B-growth/B3-analytics-funnel.mdsimilarity index 100%rename from prompts/market/B-growth/B3-analytics-funnel.mdrename to prompts/production-campaign/B-growth/B3-analytics-funnel.mddiff --git a/prompts/market/B-growth/B4-virality-share-loops.md b/prompts/production-campaign/B-growth/B4-virality-share-loops.mdsimilarity index 100%rename from prompts/market/B-growth/B4-virality-share-loops.mdrename to prompts/production-campaign/B-growth/B4-virality-share-loops.mddiff --git a/prompts/market/B-growth/B5-retention-lifecycle.md b/prompts/production-campaign/B-growth/B5-retention-lifecycle.mdsimilarity index 100%rename from prompts/market/B-growth/B5-retention-lifecycle.mdrename to prompts/production-campaign/B-growth/B5-retention-lifecycle.mddiff --git a/prompts/market/B-growth/B6-home-landing-conversion.md b/prompts/production-campaign/B-growth/B6-home-landing-conversion.mdsimilarity index 100%rename from prompts/market/B-growth/B6-home-landing-conversion.mdrename to prompts/production-campaign/B-growth/B6-home-landing-conversion.mddiff --git a/prompts/market/E-ecosystem/00-README.md b/prompts/production-campaign/E-ecosystem/00-README.mdsimilarity index 100%rename from prompts/market/E-ecosystem/00-README.mdrename to prompts/production-campaign/E-ecosystem/00-README.mddiff --git a/prompts/market/E-ecosystem/E1-sdk-production-polish.md b/prompts/production-campaign/E-ecosystem/E1-sdk-production-polish.mdsimilarity index 100%rename from prompts/market/E-ecosystem/E1-sdk-production-polish.mdrename to prompts/production-campaign/E-ecosystem/E1-sdk-production-polish.mddiff --git a/prompts/market/F-infra/00-README.md b/prompts/production-campaign/F-infra/00-README.mdsimilarity index 100%rename from prompts/market/F-infra/00-README.mdrename to prompts/production-campaign/F-infra/00-README.mddiff --git a/prompts/market/F-infra/F1-data-layer.md b/prompts/production-campaign/F-infra/F1-data-layer.mdsimilarity index 100%rename from prompts/market/F-infra/F1-data-layer.mdrename to prompts/production-campaign/F-infra/F1-data-layer.mddiff --git a/prompts/market/F-infra/F2-workers-reliability.md b/prompts/production-campaign/F-infra/F2-workers-reliability.mdsimilarity index 100%rename from prompts/market/F-infra/F2-workers-reliability.mdrename to prompts/production-campaign/F-infra/F2-workers-reliability.mddiff --git a/prompts/market/F-infra/F3-cicd-deploy-safety.md b/prompts/production-campaign/F-infra/F3-cicd-deploy-safety.mdsimilarity index 100%rename from prompts/market/F-infra/F3-cicd-deploy-safety.mdrename to prompts/production-campaign/F-infra/F3-cicd-deploy-safety.mddiff --git a/prompts/production-grade/00-README-orchestration.md b/prompts/production-grade/00-README-orchestration.mdnew file mode 100644index 000000000..c2b5031e8--- /dev/null+++ b/prompts/production-grade/00-README-orchestration.md@@ -0,0 +1,208 @@+# Program: Road to $1B — production-grade three.ws++> **Read this file in full before starting any task in this folder.** Every numbered+> prompt (`01-*` … `20-*`) assumes the context below and does not repeat it. One agent+> chat per task file. When a task is truly done (including the self-improve pass and a+> changelog entry), the agent **deletes its own prompt file**. Leave this README until+> the whole program is complete.++## Why this program exists++three.ws is already a real, broad, working platform — the 2026-06-18 audit+([docs/audit/2026-06-18-codebase-audit.md](../../docs/audit/2026-06-18-codebase-audit.md))+found it "in strong, production-ready shape," with only hardening and consistency work+outstanding. This program is the gap between "strong and working" and **a product that+could credibly carry a billion-dollar valuation**: one that activates new users on first+visit, spreads itself, converts to revenue, never falls over, pays its creators visibly,+and reads as a real company to users, partners, and enterprise buyers.++Each task below was derived from a grounded survey of the actual codebase. The file paths+are real. The gaps are real. None of these are greenfield — every task is "this exists,+here's where it falls short of the bar, raise it." That's the work.++**The bar:** would a senior engineer demo this without apologizing? Would a degen who+trades for a living switch to three.ws because of it? Would someone screenshot it? If not,+it isn't done.++## The literal seed of this program++This program started from one request: the Forge engine picker lists its two free 3D+lanes by vendor — `nvidia: 'NVIDIA'` and `huggingface: 'Hunyuan3D'` in+[src/forge.js](../../src/forge.js) (`ENGINE_LABELS`, ~line 180), each rendered with a+`FREE` pill — and they should instead read as **three.ws's own** house engines, not a+vendor billboard. That relabel is the first concrete deliverable of task `20`. It's small;+it's also the spirit of the whole program — every surface should sell three.ws, not the+infrastructure underneath it.++## Hard rules (from [CLAUDE.md](../../CLAUDE.md) — non-negotiable, repeated so you don't skip them)++- **No mocks. No fake data. No placeholders. No sample arrays. No `setTimeout` fake+ loading.** Every number on screen and in every response traces to a real API, real RPC,+ real chain call, or real DB row. If a value is `0`, render a real `0`.+- **No TODOs, no stubs, no `throw new Error("not implemented")`, no commented-out code.**+ If you write it, finish it and wire it end-to-end so a real user/agent can reach it.+- **No errors without solutions.** Find the root cause, ship the correct fix with a real+ fallback. Lazy error propagation is not engineering.+- **The only coin is `$THREE`** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Never+ name, hardcode, link, or recommend any other token anywhere — code, copy, tests,+ fixtures, commits, or conversation. The only exceptions are runtime-supplied mints (a+ user sniping an arbitrary launch; the `/launches` feed rendering platform launch+ records). Never hardcode or promote a specific non-$THREE mint. Tests use the $THREE CA+ or a synthetic placeholder (`THREEsynthetic1111…`).+- **Every state is designed:** loading (skeletons via [src/shared/state-kit.js](../../src/shared/state-kit.js),+ not spinners), empty (tell the user what to do next), error (actionable + retry),+ populated, overflow.+- **Accessibility is not optional:** semantic HTML, ARIA on interactive elements, keyboard+ nav, focus rings, contrast, `prefers-reduced-motion`.+- **Match the design system.** Tokens live in [public/tokens.css](../../public/tokens.css).+ Never hardcode hex/px when a token exists.++## Design system (use these, never invent values)++Source of truth: [public/tokens.css](../../public/tokens.css), imported globally.+Monochrome glass on near-black: `--bg-0`, surfaces `--surface-1/2/3`,+`--stroke`/`--stroke-strong`, `--accent`, text `--ink`/`--ink-dim`/`--ink-bright`/`--ink-faint`,+`--success`/`--danger`/`--warn`. Type: `--font-display` (Space Grotesk), `--font-body`+(Inter), `--font-mono` (JetBrains Mono — all addresses/amounts). Spacing: phi scale+`--space-*`. Radii `--radius-*`. Shadows `--shadow-*`. Blur `--blur-*`. Motion+`--duration-*`/`--ease-standard`. Shared UI states come from+[src/shared/state-kit.js](../../src/shared/state-kit.js); nav from+[public/nav.js](../../public/nav.js)/[public/nav-data.js](../../public/nav-data.js).++## Repo orientation (read before exploring)++- [STRUCTURE.md](../../STRUCTURE.md) maps every product surface to its directory. Read it+ first — there are 60+ top-level dirs.+- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000). Pages in `pages/` ++ `src/`, static in `public/`.+- Backend: Vercel functions in `api/`, Cloudflare workers in `workers/`. Shared backend+ libs in `api/_lib/`.+- Data/DB: Neon via [api/_lib/db.js](../../api/_lib/db.js); migrations in+ `api/_lib/migrations/` applied with `npm run db:migrate` (dry-run by default).+- 3D: Three.js + glTF/GLB. Avatar animation is universal (no rig allowlist) — see CLAUDE.md.++## Working rules for THIS repo (traps that have bitten agents here)++- **Concurrent agents share this worktree.** Others commit on `main` while you work.+ **Stage explicit paths only** (`git add path/to/file`) — never `git add -A`/`git add .`.+ Re-run `git status` + `git diff --staged` right before committing. Expect files you+ didn't write to appear; don't stage them.+- **`npx vercel build` overwrites `api/*.js` in place** with esbuild bundles. If a large+ `api/` diff shows `__defProp`/`createRequire` at the top of a file, recover with+ `git restore -- api/ public/`. Prefer not to run it.+- **Two remotes.** `threews` (canonical) and `threeD` (push-only mirror). **Never pull,+ fetch, or merge from `threeD`.** Pull only from `threews`. Push to BOTH when asked.+- **Do not commit or push unless the user explicitly asks.** Leave clean, reviewed work.+- Run `npm run dev` and exercise UI work in a real browser. No console errors/warnings+ from your code. Confirm real API calls in the Network tab.+- Tests: `npm test` (vitest + playwright), `npm run test:core` (vitest, single worker).+ Verify the runner works in your environment; **write real vitest/playwright tests+ regardless** — CI runs them.++## Changelog (every user-visible change)++Append an entry to [data/changelog.json](../../data/changelog.json): date, holder-readable+title + summary (plain language, no commit jargon), tags from+`feature|improvement|fix|sdk|infra|docs|security`. Run `npm run build:pages` to validate+and regenerate. Do **not** run `changelog:push`. Internal-only chores (CI, refactors with+no visible effect) get no entry.++## Definition of done (per task)++1. Code written, wired into the UI/API/SDK, reachable by a real user/agent across **all**+ relevant surfaces — no dead paths.+2. UI exercised in a real browser via `npm run dev`. No console errors/warnings.+3. Network tab shows real API calls returning real data.+4. Every interactive element has hover/active/focus states; every state+ (loading/empty/error/populated/overflow) designed.+5. Logged-out / signed-in / owner / visitor states correct where relevant.+6. Real tests written; `npm test` passes. Changelog entry added. `git diff` self-reviewed —+ every changed line justified.+7. You would proudly demo this to a room of senior engineers **and** to a room of degens.++## Then: improve, then delete this task++After meeting the DoD, run the CLAUDE.md self-review protocol (lazy check, user check,+integration check, edge-case check — 0/1/1000 items, very long names, network failure+mid-op, expired session — pride check). Find the single biggest weakness and fix it now.+Then ask: does what you built unlock something adjacent? Wire that connection.++**Finally, when the task is complete (and committed, if the user asked), delete your own+prompt file** so the board reflects reality. Leave this README in place.++## Tracks & task index++Six tracks. Tasks within a track are mostly independent and can run in parallel chats;+note the few dependencies. There is no hard global ordering, but the suggested sequencing+front-loads activation/growth (revenue-facing) and reliability (won't-fall-over), since+those gate everything else.++### Track A — Activation & onboarding (turn first visits into first success)+- `01-first-run-and-feature-tour.md` — auto-launch the feature tour for new visitors;+ build/repair the `/start` wizard; wire onboarding to real progress.+- `02-funding-and-free-to-paid-upsell.md` — "get USDC" funding step + quota-hit+ instrumentation and upgrade CTAs before any 403.++### Track B — Virality & distribution (make the product spread)+- `03-dynamic-og-and-social-proof.md` — per-agent/per-coin/per-avatar OG images, share+ buttons in detail heroes, real social-proof counts on cards.+- `04-referral-program-surfaced.md` — surface the existing referral engine: share card,+ leaderboard, `ref=` propagation, incentive copy.+- `05-programmatic-seo.md` — crawlable/prerendered agent, skill, and marketplace pages ++ structured data + high-intent content.++### Track C — Revenue & creator economy (prove creators earn)+- `06-creator-dashboard.md` — self-serve creator UI: price editor, live earnings, payout+ history, analytics.+- `07-skill-reviews-and-revenue-attribution.md` — ship the reviews/ratings system (schema+ exists) and the full purchase→revenue→payout analytics funnel.+- `08-checkout-completion-and-unified-pricing.md` — complete checkout (EVM, receipts,+ retry, abandonment tracking) + one coherent pricing surface.++### Track D — Reliability & hardening (a $1B platform does not fall over)+- `09-resilience-external-calls.md` — wrap every external call (Solana RPC, pump.fun,+ forge providers, x402 facilitator, LLMs) in timeout + retry + circuit breaker.+- `10-payments-integrity.md` — idempotency everywhere, settlement reconciliation, refund+ path, queryable audit log.+- `11-rate-limit-and-abuse-caps.md` — per-principal spend caps and global concurrency+ ceilings on every expensive endpoint.+- `12-observability-and-status.md` — structured logging + request tracing + server-side+ Sentry + secret scrubbing + a `/api/status` that probes live dependencies.+- `13-cron-hardening.md` — distributed locks, run-history/last-success, failure alerting,+ surfaced in status.++### Track E — Engineering excellence (ship safely, stay fast)+- `14-e2e-tests-and-ci-gate.md` — Playwright E2E for checkout/signup/forge/avatar; move+ E2E into the CI merge gate; add coverage reporting.+- `15-ci-security-and-quality-gates.md` — dependency/vuln scanning, blocking typecheck,+ bundle-size budget.+- `16-performance-and-assets.md` — lazy-load heavy GLBs, move the 200MB+ animation set to+ CDN out of git, add Core Web Vitals monitoring.++### Track F — Trust, legal, docs & polish (read as a real company)+- `17-company-and-brand-surfaces.md` — About/team/careers/press-kit/brand assets.+- `18-compliance-and-trust-pages.md` — cookie consent, accessibility statement,+ disclosure/bug-bounty, incident history.+- `19-i18n-activation.md` — run the translation pipeline for all configured locales, add a+ language switcher, RTL support.+- `20-design-system-and-a11y-polish.md` — **relabel the free Forge lanes (the seed task)**,+ tokenize stray hex/px, keyboard-navigable 3D viewers, modal focus management.++### Suggested sequencing++1. **First wave (revenue + safety, run in parallel):** `01`, `03`, `09`, `11`, `14`.+2. **Second wave:** `02`, `04`, `06`, `10`, `12`, `15`.+3. **Third wave:** `05`, `07`, `08`, `13`, `16`.+4. **Fourth wave (credibility + polish):** `17`, `18`, `19`, `20`.++Dependencies are called out inside each file. Coordinate only on shared modules+(`src/shared/*`, `api/_lib/*`, [src/analytics.js](../../src/analytics.js),+[public/tokens.css](../../public/tokens.css)).++## The invention bar (read twice)++Table stakes are the floor, not the goal. The ceiling is what is **only possible because+three.ws welds a funded, self-custodial wallet to a rigged, talking, ownable 3D agent**.+When a task offers a choice between "what every SaaS has" and "what only we can do," build+ours. Every feature should answer "why can only three.ws do this?" — if the answer is+"anyone could," raise it until someone would switch platforms for it.diff --git a/prompts/production-grade/01-first-run-and-feature-tour.md b/prompts/production-grade/01-first-run-and-feature-tour.mdnew file mode 100644index 000000000..b6460e294--- /dev/null+++ b/prompts/production-grade/01-first-run-and-feature-tour.md@@ -0,0 +1,71 @@+# Task 01 — First-run activation: auto-launch the tour + repair the `/start` wizard++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. Inherit every+> rule there. This task is in **Track A — Activation**. It has no hard dependencies and+> should land early; other Track A/B work links to the onboarding entry points you finish.++## The thesis++Activation is the single highest-leverage lever on valuation: a platform that turns first+visits into first success compounds; one that drops new users on a blank page does not.+three.ws already built most of the machinery — it just doesn't fire for the people who+need it.++## What exists today (read these before touching anything)++- **Feature tour** — [src/feature-tour/](../../src/feature-tour/) (director, narrator,+ guide-avatar, free-roam, controls; recently added). Wired to `/tour?track=quick|full`+ and `?tour=start|1|0`, state in `sessionStorage`. It is **not** auto-offered to+ first-time visitors anywhere — you reach it only via a deep link or nav.+- **Getting-started checklist** — [public/getting-started.js](../../public/getting-started.js):+ floating checklist (create → brain → embed core + optional on-chain/monetize), milestones+ in `localStorage`, skippable welcome modal.+- **Dashboard onboarding panel** — [src/dashboard-next/pages/home.js](../../src/dashboard-next/pages/home.js):+ reconciles progress with server data.+- **Onboarding plan of record** — [docs/onboarding/ONBOARDING-PLAN-2026-06-19.md](../../docs/onboarding/ONBOARDING-PLAN-2026-06-19.md):+ read it; it defines the intended phases. Honor it.+- **`/start` wizard** — listed in [data/pages.json](../../data/pages.json) as a "5-step+ onboarding wizard" but **the page does not exist** (`pages/start.html` is missing). This+ is a documented-but-dead route: a conversion blocker and an `audit:pages` liability.++## The gap++1. New visitors are never offered the tour or a guided path — the machinery sits idle.+2. `/start` is advertised but 404s / is unbuilt. Either build the real wizard or remove the+ route from the manifest — no dead advertised paths. **Build it** (it's the better first+ step than dropping a cold user into `/forge` or `/create`).+3. The tour, the getting-started checklist, and the dashboard panel track progress in three+ different stores and don't agree. Onboarding state should be one source of truth.++## What to build++1. **First-run offer.** On a first-ever visit (no returning-visitor marker), show a tasteful,+ dismissible prompt to take the guided tour / start the wizard — on the home page and/or+ via [public/nav.js](../../public/nav.js). Respect `prefers-reduced-motion`. Never nag: one+ offer, remembered if dismissed or completed. Don't show it to returning/known users.+2. **Build the real `/start` wizard** (`pages/start.html` + its module). Five real steps that+ end in a real first success (e.g. create-or-pick an avatar → connect a brain → generate or+ embed → optional on-chain/monetize). Each step does real work via the existing+ create/forge/brain/embed APIs — no fake progress. Designed empty/loading/error states per+ step; back/skip; resumable. Reuse the feature-tour and getting-started infrastructure+ rather than forking a third system.+3. **Unify onboarding progress** into one source of truth (prefer the server-backed model the+ dashboard already reconciles against), and have the checklist, the wizard, and the+ dashboard panel all read/write it. Completing a step anywhere advances it everywhere.+4. **Instrument it.** Fire the real activation funnel events through+ [src/analytics.js](../../src/analytics.js) (it already defines an activation funnel —+ `LANDING_VIEWED` → … → `AGENT_CREATED`). Add the wizard's per-step start/complete/skip+ events so drop-off is measurable. No new analytics vendor; use what's wired.++## Definition of done++Everything in the README DoD, plus:+- A brand-new visitor (fresh browser profile) is offered a path and can complete a real first+ success without dead ends.+- `/start` exists, passes `npm run audit:pages` (route ↔ manifest parity), is reachable from+ nav and the first-run offer, and is fully responsive (320 / 768 / 1440).+- Onboarding progress is consistent across the checklist, the wizard, and the dashboard.+- Activation + per-step events fire (verify in the Network tab / analytics debug).+- Changelog entry (`feature`). Then run the self-review and improve the weakest step.++Delete this file when done.diff --git a/prompts/production-grade/02-funding-and-free-to-paid-upsell.md b/prompts/production-grade/02-funding-and-free-to-paid-upsell.mdnew file mode 100644index 000000000..f20070569--- /dev/null+++ b/prompts/production-grade/02-funding-and-free-to-paid-upsell.md@@ -0,0 +1,68 @@+# Task 02 — Funding on-ramp + free-to-paid upsell (close the money gap)++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track A —+> Activation.** Pairs naturally with `08` (checkout) and `06`/`07` (creator revenue), but+> stands alone. Touches `src/analytics.js` and the paywall paths — coordinate on those.++## The thesis++Users hit a wall the moment money is required: free Forge/skill quotas run out, or an x402+call needs USDC the user doesn't have, and the product just… 403s. There's no "here's how to+get USDC" and no "upgrade to keep going." Every silent rejection there is lost revenue and a+lost user. A $1B funnel makes the paid step feel like the natural next move, not a brick wall.++## What exists today (read first)++- **Pricing tiers / holder discounts** — [api/_lib/three-tier.js](../../api/_lib/three-tier.js)+ (Member/Bronze/Silver/Gold/Genesis, 0–30% discount; free-quota multipliers), and Forge tier+ prices in [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js).+- **Checkout** — [api/x402-checkout.js](../../api/x402-checkout.js) prepares/encodes Solana+ transactions only (no EVM, no receipt, no retry — that's task `08`).+- **Wallet skills** — the harness exposes `fund`, `send-usdc`, `trade`, `authenticate-wallet`+ skills; the platform has agent custodial wallets ([api/_lib/agent-wallet.js](../../api/_lib/agent-wallet.js))+ and on-ramp touchpoints. Find the existing funding/on-ramp code before adding any.+- **Analytics** — [src/analytics.js](../../src/analytics.js) has an activation funnel and a+ `$THREE` purchase funnel but **no** `QUOTA_EXCEEDED` / `UPGRADE_PROMPTED` /+ `PAYMENT_INITIATED` events. Quota walls are currently invisible to analytics.+- **The onboarding plan** explicitly lists "close the funding gap" as Phase 2+ ([docs/onboarding/ONBOARDING-PLAN-2026-06-19.md](../../docs/onboarding/ONBOARDING-PLAN-2026-06-19.md)).++## The gap++1. No in-product "get USDC" path at the moment a user needs it.+2. Free→paid transition is a hard 403 with no upgrade CTA, no "buy 10 generations," no holder+ benefit shown ("hold $THREE for up to 10× free quota").+3. Quota hits and upgrade prompts aren't instrumented, so the biggest revenue leak is unmeasured.++## What to build++1. **Funding step at the point of need.** When a paid action lacks funds, show a real,+ inline funding flow (reuse the existing on-ramp / `fund` path — do not invent a fake one).+ Show real balance, real required amount, real options. Designed loading/error/success.+2. **Upgrade / upsell surface before any 403.** When a free quota is about to be (or just+ was) exhausted, surface an actionable CTA: the relevant price, what a purchase unlocks, and+ the holder benefit from [three-tier.js](../../api/_lib/three-tier.js) (real tier, real+ multiplier — never a fake number). Link to the pricing surface (`08`) and to `$THREE`.+ This must appear on the real quota-gated paths (Forge generation, skill unlock, any+ metered x402 lane) — audit which endpoints return quota 403s and cover them.+3. **Instrument the wall.** Add `QUOTA_EXCEEDED`, `UPGRADE_PROMPTED`, `UPGRADE_CLICKED`,+ `FUNDING_STARTED`, `FUNDING_SUCCEEDED`, `PAYMENT_INITIATED` to+ [src/analytics.js](../../src/analytics.js) and fire them at the real moments. No new vendor.+4. **Holder-aware copy.** A $THREE holder hitting a wall sees their actual multiplier and the+ next tier's benefit — turning the wall into a reason to hold more, not a dead end.++## Hard rules specific to this task++- **$THREE is the only coin** anywhere in funding/upsell copy and links. USDC is settlement+ plumbing (fine); never name or link any other token. Holder benefits reference $THREE only.+- Every amount, balance, quota, and multiplier is **real** (live balance / DB quota / tier+ lookup). No fabricated "$1,234" anywhere.++## Definition of done++README DoD, plus: a user with zero USDC can reach a working funding flow from a paywall; a+user out of free quota sees a real, accurate upgrade CTA before being blocked; the new+analytics events fire (verify in Network/analytics debug); holder vs non-holder copy both+correct. Changelog (`feature`). Self-review, then improve the weakest moment in the flow.++Delete this file when done.diff --git a/prompts/production-grade/03-dynamic-og-and-social-proof.md b/prompts/production-grade/03-dynamic-og-and-social-proof.mdnew file mode 100644index 000000000..ba94439b9--- /dev/null+++ b/prompts/production-grade/03-dynamic-og-and-social-proof.md@@ -0,0 +1,67 @@+# Task 03 — Dynamic OG images + share buttons + real social proof++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track B —+> Virality.** Independent; lands early. Coordinate with `04` (referral) on the share UI and+> with `05` (SEO) on the OG/meta endpoints.++## The thesis++three.ws is intrinsically shareable — a rigged, talking 3D agent is a screenshot waiting to+happen — but right now every agent and every coin shares the **same static `og-image.png`**.+A link to your agent on X looks identical to everyone else's. That kills the single cheapest+growth loop a platform like this has. Fix the share surface and the product spreads itself.++## What exists today (read first)++- **Static OG only on detail pages.** [pages/agent-detail.html](../../pages/agent-detail.html)+ (~line 16) and [pages/launch-detail.html](../../pages/launch-detail.html) (~line 20) both+ fall back to the generic `og-image.png`.+- **A page-OG generator exists but only for static pages** — `/api/page-og` (used by the home+ page). There is no per-agent / per-coin / per-avatar OG route.+- **Share panel exists** — [src/share-panel.js](../../src/share-panel.js): link / iframe /+ web-component snippets, QR via [src/erc8004/qr.js](../../src/erc8004/qr.js), proper+ `role="dialog"` + focus management. It's good — but it's a modal you have to go find; there+ are no share buttons in the detail-page heroes.+- **No social proof on cards.** Marketplace ([src/marketplace.js](../../src/marketplace.js)),+ launches ([pages/launches.html](../../pages/launches.html)), gallery+ ([pages/gallery.html](../../pages/gallery.html)) show no follower/holder/view/like counts and+ no "trending" badges, even though the underlying feeds have the data.++## What to build++1. **Dynamic OG image routes.** Build real OG-image endpoints for agents, coins/launches, and+ gallery avatars (mirror the `/api/page-og` approach — server-rendered image with the+ agent's avatar render or coin logo, name/symbol, and a real stat or two). Wire+ `agent-detail.html` and `launch-detail.html` (and the avatar/gallery detail) to emit+ per-entity `og:image`, `og:title`, `og:description`, and Twitter card tags. Validate the+ cards render in a real share preview.+2. **Share buttons in the hero.** Put a direct share affordance (copy link + X/Twitter intent,+ plus "embed") in the detail-page hero — not buried in a modal. Reuse+ [src/share-panel.js](../../src/share-panel.js); don't reimplement it. Keyboard + focus ++ ARIA correct.+3. **Real social proof on cards and heroes.** Add the genuine signals the feeds already carry:+ holder count / market cap on coin cards, followers / chats / views on agent cards, likes /+ downloads on avatars, and a "🔥 trending" treatment for high-activity items (drive it from+ real activity data — e.g. [api/trending.js](../../api/trending.js), not a hardcoded list).+ Every number is real; if a count is 0, show a real 0 or omit gracefully.+4. **Referral-aware links (coordinate with `04`).** Shared links from a signed-in user should+ carry their `ref=` code so a share is also a referral. Build the share side here; `04` owns+ the attribution. Don't double-implement — agree on the param.++## Hard rules specific to this task++- **$THREE only** in any token-related share/OG copy. Coin/launch OG images render whatever+ mint the launch record references at runtime (allowed — platform launch directory), but+ never hardcode or promote a specific non-$THREE mint in templates or copy.+- OG endpoints must handle the missing/edge entity (deleted agent, no avatar yet, long+ name/emoji) without producing a broken image — design the fallback.++## Definition of done++README DoD, plus: pasting an agent URL and a coin URL into a link-preview tool shows distinct,+correct, good-looking cards; share buttons work from the hero with keyboard; cards show real+counts and trending treatment; shared links from a logged-in user carry `ref=`. OG routes+have tests for the edge entities. Changelog (`feature`). Self-review, then improve the+weakest card state.++Delete this file when done.diff --git a/prompts/production-grade/04-referral-program-surfaced.md b/prompts/production-grade/04-referral-program-surfaced.mdnew file mode 100644index 000000000..56b91b4bd--- /dev/null+++ b/prompts/production-grade/04-referral-program-surfaced.md@@ -0,0 +1,60 @@+# Task 04 — Surface the referral program (the growth loop that's already built)++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track B —+> Virality.** The backend is done; this is almost entirely the missing front end + a couple+> of incentive hooks. Coordinate with `03` on `ref=` propagation in shared links.++## The thesis++three.ws has a complete, real referral engine — and **zero UI for it**. Users have a referral+code they can't see, earnings they can't watch accrue, and a leaderboard position nobody shows+them. This is a fully built growth loop sitting behind a missing button. Surfacing it is one+of the highest ROI tasks in the program: no new backend, pure activation of an existing asset.++## What exists today (read first — it's real, don't rebuild it)++- **Referral engine** — [api/_lib/referrals.js](../../api/_lib/referrals.js): every signup gets+ a collision-safe `referral_code`; `getMembershipCard()` returns the code, referred-user+ count, lifetime earnings, and a score; commission (default 5%, `REFERRAL_COMMISSION_BPS`) is+ credited on confirmed purchase via [api/_lib/purchase-confirm.js](../../api/_lib/purchase-confirm.js)+ (`creditReferralCommission`). Position is a 1-based signup ordinal today.+- **It's data-only.** There is no copy-to-clipboard share card, no leaderboard UI, no+ "earn per signup" messaging, no `ref=` propagation into agent/share URLs, no funnel step.++## What to build++1. **Referral hub / share card.** A real surface (in the dashboard/account area and reachable+ from nav) that shows the user's actual code, their share link, lifetime earnings, referred+ count, and rank — all from `getMembershipCard()`. One-tap copy and a share affordance+ (reuse [src/share-panel.js](../../src/share-panel.js)). Designed empty state ("you haven't+ referred anyone yet — here's your link").+2. **`ref=` propagation.** When a signed-in user shares an agent/coin/page (coordinate with+ `03`), embed their referral code. On landing, capture `ref=` → attribute on signup through+ the existing referral plumbing. Don't bypass the server logic in `referrals.js`.+3. **A public referral leaderboard.** Turn the existing score/position into a real, shareable+ leaderboard surface (top referrers, the viewer's own rank highlighted). Real data only.+ This doubles as social proof and an SEO/landing surface (coordinate with `05`).+4. **Incentive copy + one real reward hook.** Add honest "earn X% on every purchase you refer"+ messaging where it belongs (referral hub, maybe a homepage strip). Then wire **one** real,+ non-fake incentive milestone (e.g. refer N confirmed signups → a real, server-granted perk+ such as bonus free-generation quota via the existing quota system). It must grant a real+ benefit through real backend state — no cosmetic-only "badge" that does nothing.+5. **Funnel events.** Add referral events to [src/analytics.js](../../src/analytics.js)+ (`REFERRAL_VIEWED`, `REFERRAL_COPIED`, `REFERRAL_LANDED`, `REFERRAL_SIGNUP`) at the real+ moments.++## Hard rules specific to this task++- Earnings, counts, rank, and rewards are **real** (from `referrals.js` / DB) — never fabricated.+- Don't change the backend invariants in `referrals.js`/`purchase-confirm.js`; surface them.+- **$THREE only** in any token-denominated reward/earning copy. USDC settlement is fine.++## Definition of done++README DoD, plus: a user can find, read, copy, and share their referral link; a `ref=` landing+attributes correctly through the real engine; the leaderboard renders real data with the+viewer highlighted; the one incentive milestone grants a real server-side benefit; events fire.+Tests for `ref=` capture/attribution. Changelog (`feature`). Self-review, then improve the+weakest moment (likely the empty state or the share preview).++Delete this file when done.diff --git a/prompts/production-grade/05-programmatic-seo.md b/prompts/production-grade/05-programmatic-seo.mdnew file mode 100644index 000000000..ca608a41d--- /dev/null+++ b/prompts/production-grade/05-programmatic-seo.md@@ -0,0 +1,68 @@+# Task 05 — Programmatic SEO: make every agent, skill, and coin crawlable++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track B —+> Virality.** Coordinate with `03` (OG/meta endpoints) and `04` (leaderboard as a landing+> surface). Independent otherwise.++## The thesis++The platform's growth surface area is its user-generated content — thousands of agents,+skills, launches, avatars. Today almost none of it is crawlable: agent pages render+client-side, marketplace listings have no structured data, and there are no high-intent+content/landing pages. A $1B consumer platform earns a large share of acquisition from+organic search; right now that channel is near zero. This task turns UGC into an indexable,+compounding acquisition engine.++## What exists today (read first)++- **Static-page SEO only.** [scripts/inject-seo-meta.mjs](../../scripts/inject-seo-meta.mjs)+ backfills title/description/OG/JSON-LD onto **static** pages from+ [data/pages.json](../../data/pages.json). It does nothing for dynamic entity pages.+- **Blog + changelog feeds exist** — `blog/` (auto-generated from `.md`),+ `public/changelog.{json,xml}`, sitemap via [vercel.json](../../vercel.json) routes.+- **Discovery manifests exist** — `public/.well-known/openapi.yaml`, `agent-card.json`,+ `ai-plugin.json`, etc.+- **The gap:** agent profiles (`/agents/:id` / `/agent/:id`), skill listings, and+ launch/coin pages are client-rendered with generic meta and no structured data; there's no+ programmatic SEO sweep, no entity sitemaps, and no high-intent content/tutorial landing pages+ to rank for "3D AI agent", "monetize an AI skill", "launch an agent token", etc.++## What to build++1. **Crawlable entity pages.** Ensure agent, skill, and launch/coin detail pages serve real,+ entity-specific `<title>`, meta description, canonical URL, OG/Twitter tags (reuse the+ dynamic OG endpoints from `03`), and **JSON-LD structured data** appropriate to the type+ (e.g. `Product`/`Offer` with real price + rating for skills once `07` ships reviews;+ `Person`/`CreativeWork` for agents). If pages are client-rendered, add server-rendered+ meta/SSR or prerendering for crawlers so the head is correct without a JS execution — pick+ the approach that fits the existing Vercel setup and document it. No cloaking: served+ content must match what users see.+2. **Entity sitemaps.** Generate and serve sitemaps (or a sitemap index) covering live agents,+ public skills, and launches, refreshed on a sane cadence (a build step and/or cron). Wire+ into `robots.txt` / [vercel.json](../../vercel.json).+3. **High-intent content/landing pages.** Add a small set of genuinely useful, real-content+ pages targeting high-intent queries (e.g. "make your first 3D AI agent", "monetize a skill+ with x402", "launch an agent token"). Real content, internal links to the product, correct+ meta — extend the existing blog/static pipeline; don't bolt on a new CMS.+4. **Structured data for the catalog.** Add the marketplace/skill structured data and a+ machine-readable catalog where it helps discovery, consistent with the existing+ `.well-known` manifests.++## Hard rules specific to this task++- **No doorway/spam pages, no keyword-stuffed thin content.** Every generated/landing page+ must be genuinely useful and accurate, or it hurts the domain. Quality over volume.+- **$THREE only** in token copy. Coin pages render runtime launch-record mints (allowed); never+ hardcode/promote a specific non-$THREE mint in templates or content.+- Don't regress `npm run audit:pages` (route ↔ manifest parity) — register new routes in+ [data/pages.json](../../data/pages.json).++## Definition of done++README DoD, plus: an agent page, a skill page, and a coin page each return correct+entity-specific head + valid JSON-LD (validate with a structured-data testing tool); sitemaps+list live entities and are referenced from robots/sitemap config; the new content pages are+live, useful, internally linked, and pass `audit:pages`. Changelog (`improvement`/`docs`).+Self-review, then improve the weakest entity type's metadata.++Delete this file when done.diff --git a/prompts/production-grade/06-creator-dashboard.md b/prompts/production-grade/06-creator-dashboard.mdnew file mode 100644index 000000000..0f9085bf0--- /dev/null+++ b/prompts/production-grade/06-creator-dashboard.md@@ -0,0 +1,68 @@+# Task 06 — Creator dashboard: make "creators earn real money" visible++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track C —+> Revenue.** The backend APIs exist; this is the missing self-serve creator UI. Pairs with+> `07` (reviews + attribution) and `08` (pricing/checkout).++## The thesis++The lever between a $1M platform and a $1B platform is **supply-side proof**: creators who can+see they earn real money, paid out, with real analytics — they tell other creators, and the+flywheel turns. three.ws already settles royalties and exposes per-agent revenue over APIs,+but creators have **no UI** to set prices, watch earnings, or track payouts. They're earning+in the dark. Light it up.++## What exists today (read first — these are real endpoints)++- **Revenue** — [api/monetization/revenue.js](../../api/monetization/revenue.js): per-agent+ gross/net/fees, breakdown by skill, daily timeseries.+- **Payout wallets** — [api/monetization/wallet.js](../../api/monetization/wallet.js): set+ Solana + EVM (Base) payout addresses, preferred network.+- **Withdrawals** — [api/monetization/withdrawals.js](../../api/monetization/withdrawals.js).+- **Royalty settlement** — [api/_lib/royalty.js](../../api/_lib/royalty.js): settles pending+ royalties to creator wallets; ledger has pending/settling/settled states.+- **Skill pricing** — [api/_lib/skill-pricing-rules.js](../../api/_lib/skill-pricing-rules.js)+ + the `agent_skill_prices` table support dynamic rules (first-N, after-N, time-window).+- **Creator analytics endpoint** — [api/creators/skill-analytics.js](../../api/creators/skill-analytics.js)+ exists with **no UI**.+- **The gap:** no `creator-dashboard` page; creators can't self-serve any of the above.++## What to build++A real **creator dashboard** (a new page under the dashboard surface, e.g.+`src/dashboard-next/pages/creator.js` + route; follow the existing dashboard-next patterns):++1. **Price editor.** Set/edit a skill's price and pricing rules via the real+ `agent_skill_prices` plumbing and [skill-pricing-rules.js](../../api/_lib/skill-pricing-rules.js).+ Validate inputs; show the resulting buyer-facing price (including any $THREE-holder discount+ from [three-tier.js](../../api/_lib/three-tier.js)). No fake preview — compute it for real.+2. **Live earnings.** Render gross/net/fees and the daily timeseries from+ [revenue.js](../../api/monetization/revenue.js) with real charts. Designed empty state+ ("no sales yet — here's how to get your first").+3. **Payout management + history.** Set payout wallets ([wallet.js](../../api/monetization/wallet.js)),+ see the royalty ledger (pending/settling/settled from [royalty.js](../../api/_lib/royalty.js)),+ and request/track withdrawals ([withdrawals.js](../../api/monetization/withdrawals.js)).+ Show real on-chain settlement state. Exportable history.+4. **Per-skill analytics.** Surface [skill-analytics.js](../../api/creators/skill-analytics.js)+ (installs, conversion, earnings per skill) as a real table/graph.+5. **Onboarding to selling.** A short "become a creator → set your first price → first sale"+ path, instrumented in [src/analytics.js](../../src/analytics.js) (add the creator funnel+ events). Reachable from the main dashboard and nav.++## Hard rules specific to this task++- Every figure is **real** (live API/DB/on-chain). No mock earnings, no placeholder charts.+- Owner-only: a creator sees only their own agents/skills/earnings. Enforce auth+ ([api/_lib/auth.js](../../api/_lib/auth.js)); never leak another creator's revenue.+- **$THREE only** in any token copy. Payout amounts in USDC/settlement currency are fine.+- Don't change settlement/ledger invariants — surface them faithfully.++## Definition of done++README DoD, plus: a creator can set a price, watch real earnings update after a real purchase,+set a payout wallet, and see/track a real payout; every state designed; owner isolation+verified; creator funnel events fire. Tests for the price-editor logic and the owner-isolation+guard. Changelog (`feature`). Self-review, then improve the weakest panel (likely empty state+or payout clarity).++Delete this file when done.diff --git a/prompts/production-grade/07-skill-reviews-and-revenue-attribution.md b/prompts/production-grade/07-skill-reviews-and-revenue-attribution.mdnew file mode 100644index 000000000..664773641--- /dev/null+++ b/prompts/production-grade/07-skill-reviews-and-revenue-attribution.md@@ -0,0 +1,66 @@+# Task 07 — Skill reviews/ratings + end-to-end revenue attribution++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track C —+> Revenue.** Two tightly related halves: a trust signal (reviews) and a measurement spine+> (attribution). Coordinate with `06` (creator dashboard consumes both) and `05` (reviews+> feed SEO structured data).++## The thesis++A marketplace without reviews can't build buyer trust, and a business that can't trace+"who spent what on whose skill, referred by whom" can't optimize pricing, discounts, payouts,+or acquisition. Both are foundational to a $1B marketplace. The reviews **schema already+exists** — the handlers and UI don't. Attribution events are **half-defined** — the revenue+half is missing. Finish both.++## What exists today (read first)++- **Reviews schema, no handlers/UI.** A migration exists+ (`api/_lib/migrations/…skill_reviews.sql`) but there are no review endpoints and no review+ UI. Buyers cannot rate skills; creators get no feedback loop.+- **Analytics stops at activation.** [src/analytics.js](../../src/analytics.js) defines an+ activation funnel and a `$THREE` purchase funnel, but there is **no** buyer-revenue funnel:+ no `SKILL_SEARCHED` / `SKILL_VIEWED` / `PAYMENT_INITIATED` / `PAYMENT_CONFIRMED` /+ `SKILL_UNLOCKED`, and no chained attribution to creator + referrer.+- **Purchase confirmation is real** — [api/_lib/purchase-confirm.js](../../api/_lib/purchase-confirm.js)+ already credits referral commission on confirmed purchase; that's the join point for+ attribution.++## What to build++### A. Reviews & ratings+1. **Endpoints**: create/read/update/delete a review (rating + text) for a skill, gated to+ buyers who actually purchased it (verify against purchase records). Aggregate rating per+ skill. Abuse controls (one review per buyer per skill; rate-limited; moderation hook).+2. **UI**: show aggregate rating + reviews on skill/marketplace pages; let eligible buyers+ leave/edit a review; surface a creator-facing view of their reviews in the `06` dashboard.+ Designed empty/loading/error states; ARIA on the rating control; keyboard operable.+3. **Structured data**: expose aggregate rating for `05`'s `Product`/`Offer` JSON-LD.++### B. Revenue attribution funnel+4. **Events**: add the buyer-revenue funnel to [src/analytics.js](../../src/analytics.js)+ (`SKILL_SEARCHED`, `SKILL_VIEWED`, `PAYMENT_INITIATED`, `PAYMENT_CONFIRMED`,+ `SKILL_UNLOCKED`) and fire them at the real moments in the marketplace + checkout paths.+5. **Attribution chain**: at confirmed purchase+ ([purchase-confirm.js](../../api/_lib/purchase-confirm.js)), record the full chain — buyer →+ skill → creator → referrer → amount/net/fees — so the question "what % of signups buy within+ 7 days, and which channel/referrer drove it" is answerable. Persist it in a queryable shape+ (real table; reuse existing revenue/royalty tables where possible). No PII beyond what's+ already stored; respect the privacy policy.++## Hard rules specific to this task++- Reviews are **real and earned** — only genuine purchasers can review; never seed fake+ reviews or ratings, ever (that violates the no-fake-data rule and is fraud).+- Attribution is **real** — derived from real purchase/referral rows, not synthesized.+- **$THREE only** in token copy. USDC settlement amounts are fine.++## Definition of done++README DoD, plus: a real buyer can review a purchased skill and a non-buyer cannot; aggregate+ratings render and feed JSON-LD; the buyer-revenue funnel events fire end-to-end; a confirmed+purchase writes a complete attribution row that the `06` dashboard can read. Tests for the+buyer-only review gate and the attribution write. Changelog (`feature`). Self-review, then+improve the weakest state (likely the review empty/first-review prompt).++Delete this file when done.diff --git a/prompts/production-grade/08-checkout-completion-and-unified-pricing.md b/prompts/production-grade/08-checkout-completion-and-unified-pricing.mdnew file mode 100644index 000000000..593f6c18e--- /dev/null+++ b/prompts/production-grade/08-checkout-completion-and-unified-pricing.md@@ -0,0 +1,67 @@+# Task 08 — Complete checkout (EVM, receipts, retry) + one coherent pricing surface++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track C —+> Revenue.** Pairs with `02` (funding/upsell), `06`/`07` (creator/attribution). Touches the+> x402 payment path — coordinate with `10` (payments integrity) so you don't conflict on+> idempotency/settlement.++## The thesis++Checkout is where intent becomes revenue, and three.ws's is half-built: Solana-only, no+receipt, no failed-payment recovery, no abandonment signal. Meanwhile pricing is scattered+across three subsystems with no single place a buyer (or a finance team) can understand what+things cost. A $1B business has a frictionless, recoverable checkout and one legible price+surface. Build both.++## What exists today (read first)++- **Checkout prep** — [api/x402-checkout.js](../../api/x402-checkout.js): prepares/encodes+ **Solana** transactions only. No EVM path, no email receipt, no retry-on-failure, no+ abandonment tracking. (There's a prepare test:+ [tests/x402-checkout-prepare.test.js](../../tests/x402-checkout-prepare.test.js).)+- **x402 paid endpoints + checkout core** — [public/x402.js](../../public/x402.js),+ [public/x402-pay-core.js](../../public/x402-pay-core.js), [api/_lib/x402.js](../../api/_lib/x402.js)+ and `api/_lib/x402/*`.+- **Pricing is fragmented:** Forge tiers in [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js)+ (USDC atomics), skill pricing in [api/_lib/skill-pricing-rules.js](../../api/_lib/skill-pricing-rules.js)+ / `agent_skill_prices`, subscriptions in [api/subscriptions.js](../../api/subscriptions.js),+ holder discounts in [api/_lib/three-tier.js](../../api/_lib/three-tier.js). The public+ `pages/pricing.html` only describes seat tiers, not per-API/skill pricing.+- **Email framework exists** — [api/_lib/email.js](../../api/_lib/email.js) (Resend) already+ sends referral/verification mail; reuse it for receipts.++## What to build++1. **EVM checkout path.** Add Base/EVM payment support alongside Solana in the checkout flow+ (the platform already supports EVM payout wallets and x402 on Base — wire the buyer side).+ Real transaction prep/verify/settle; no stub.+2. **Receipts.** On confirmed payment, send a real email receipt via+ [email.js](../../api/_lib/email.js) and persist a retrievable receipt record (buyer can view+ past purchases). Real amounts, real tx links.+3. **Failed-payment recovery.** Detect failed/expired/abandoned payment attempts and offer a+ real retry path; don't leave the buyer stranded on an error. Coordinate idempotency with+ `10` so a retry can't double-charge.+4. **Abandonment tracking.** Emit `CHECKOUT_STARTED` / `CHECKOUT_ABANDONED` /+ `CHECKOUT_COMPLETED` to [src/analytics.js](../../src/analytics.js) so cart abandonment is+ measurable (it currently isn't).+5. **One pricing surface.** Build a single, accurate pricing page/section that reflects the+ **real** numbers from all four pricing subsystems (Forge tiers, skill pricing, subscriptions,+ holder discounts) — computed, not hand-copied, so it can't drift. Show the buyer their actual+ $THREE-holder discount when signed in.++## Hard rules specific to this task++- Money is real: amounts, fees, discounts, balances all from real config/chain/DB.+- **$THREE only** in token copy. USDC is settlement plumbing — fine to name as the currency.+- Don't weaken the x402 verify/settle ordering or idempotency — align with `10`.++## Definition of done++README DoD, plus: a buyer can complete a real purchase on **both** Solana and EVM, receives a+real receipt, can recover a failed attempt without double-charging, and the pricing surface+shows accurate computed prices including the holder discount; abandonment events fire. Tests+extend [tests/x402-checkout-prepare.test.js](../../tests/x402-checkout-prepare.test.js) to cover+EVM prep + the retry/idempotency guard. Changelog (`feature`). Self-review, then improve the+weakest path (likely the failure/retry UX).++Delete this file when done.diff --git a/prompts/production-grade/09-resilience-external-calls.md b/prompts/production-grade/09-resilience-external-calls.mdnew file mode 100644index 000000000..103f54f4f--- /dev/null+++ b/prompts/production-grade/09-resilience-external-calls.md@@ -0,0 +1,72 @@+# Task 09 — Resilience sweep: no naked external call anywhere++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track D —+> Reliability.** High priority, lands early. Coordinate with `10` (payments) on the+> facilitator path and `12` (observability) on how failures are logged.++## The thesis++A platform whose handlers hang for 60s when Helius is slow, or 500 when a facilitator blips,+is not a $1B platform — it's a platform one upstream incident away from looking broken. The+repo already has the right primitive (`resilience.js`, cockatiel) but **<2% of call sites use+it**. Most `fetch`/RPC calls to Solana, pump.fun, forge providers, the x402 facilitator, and+the LLMs are naked: no timeout, no retry, no circuit breaker. Close that systematically.++## What exists today (read first — reuse, don't reinvent)++- **Resilience helper** — [api/_lib/resilience.js](../../api/_lib/resilience.js): `withBreaker()`+ and friends (cockatiel). Adopted in only a handful of places (e.g.+ [api/cron/forge-seed-cron.js](../../api/cron/forge-seed-cron.js) circuit state,+ provider-health cooldown). This is the pattern to spread. (User memory: cockatiel is the+ sanctioned resilience helper; prefer vetted OSS, additive.)+- **Naked upstreams to fix** (non-exhaustive — audit for the rest):+ - Solana RPC via the shared connection in [api/pump/[action].js](../../api/pump/[action].js),+ [api/pump/launch-agent.js](../../api/pump/launch-agent.js) — no AbortSignal timeout.+ - Forge providers (Replicate/NVIDIA/HF) in [api/forge.js](../../api/forge.js) — submit + poll+ with no timeout/breaker; polling has no backoff.+ - x402 facilitator verify/settle in [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) — no+ timeout, no fallback when the facilitator is down.+ - Image fetch/decode in [api/_lib/forge-image-validate.js](../../api/_lib/forge-image-validate.js)+ — no AbortSignal; a never-closing socket hangs the handler.+ - LLM fallover in [api/chat.js](../../api/chat.js) / [api/_lib/chat-models.js](../../api/_lib/chat-models.js)+ — retries immediately on 429 instead of backing off.+ - Redis-backed caches/limiters ([api/_lib/cache.js](../../api/_lib/cache.js),+ [api/_lib/x402/idempotency-cache.js](../../api/_lib/x402/idempotency-cache.js)) — no timeout+ on Redis ops; cache.js swallows errors silently (masking outages).++## What to build++1. **A single resilient-fetch wrapper** (extend [resilience.js](../../api/_lib/resilience.js))+ that every outbound call routes through: explicit per-call **timeout** (AbortSignal),+ bounded **retry with backoff** on transient (429/5xx/network) errors only, and a **circuit+ breaker** per upstream so a dead dependency fails fast instead of hanging. Sensible+ per-upstream defaults; overridable.+2. **Migrate the high-value call sites** above (and the rest you find — grep for `fetch(` and+ raw RPC usage in `api/` and `workers/`) onto it. Each external call must have a timeout and+ a real fallback or a clean, fast error — never an indefinite hang and never a silent swallow.+3. **Stop silent degradation.** [cache.js](../../api/_lib/cache.js) and the limiter fallback+ must still degrade gracefully **but** surface the degradation (a metric/log via `12`), so a+ Redis outage is visible instead of masked.+4. **Bound the cost paths.** Forge provider polling gets backoff; the facilitator path degrades+ sensibly (coordinate with `10`).++## Hard rules specific to this task++- **No errors without solutions** (CLAUDE.md): every wrapped call has a defined behavior on+ timeout/open-circuit — a real fallback, a cached value, or a clean typed error the caller+ handles. Never a bare throw that 500s the user.+- Don't change business logic or response shapes — this is a reliability layer, transparent to+ callers on the happy path.+- Be careful not to retry **non-idempotent** operations blindly (payments, launches) — retry+ only where safe; coordinate with `10`/`11`.++## Definition of done++README DoD, plus: the high-value upstreams are wrapped with timeout + breaker + bounded retry;+a forced upstream failure (simulate a slow/500 dependency in a test) fails fast with the+defined fallback instead of hanging; cache/limiter degradation emits a signal. Vitest covers+the wrapper (timeout fires, breaker opens, retry backs off, non-idempotent calls aren't+retried). Changelog (`infra`/`improvement`). Self-review, then extend the sweep to the next+batch of naked calls you found.++Delete this file when done.diff --git a/prompts/production-grade/10-payments-integrity.md b/prompts/production-grade/10-payments-integrity.mdnew file mode 100644index 000000000..6c04e7e48--- /dev/null+++ b/prompts/production-grade/10-payments-integrity.md@@ -0,0 +1,66 @@+# Task 10 — Payments integrity: idempotency, reconciliation, refunds, audit++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track D —+> Reliability.** The most consequential reliability task — it's real money. Coordinate with+> `08` (checkout), `09` (facilitator resilience), `11` (caps).++## The thesis++Nothing erodes trust — or a valuation — faster than charging someone twice, or charging them+and not delivering. three.ws's x402 stack is solid but has integrity gaps: idempotency is+opt-in per endpoint and missing on several, settlement can fail after verify succeeds with no+reconciliation, there's no refund path when a paid generation fails, and the audit log can't+be queried by transaction. A $1B payments surface closes every one of these.++## What exists today (read first)++- **Paid-endpoint core** — [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js):+ supports a payment-identifier (idempotency) extension, but it's **optional per endpoint**.+ `api/x402/forge.js` and `api/x402/pump-launch.js` use it; **`api/x402/vanity.js` and+ `api/x402/dance-tip.js` do not** — a timeout between verify and settle can double-charge.+- **Verify/settle** — [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js): `verifyPayment()` /+ `settlePayment()` call the facilitator; if settle fails after verify succeeds, the handler+ 500s while the buyer may be charged — and there's **no reconciliation job**.+- **Idempotency cache** — [api/_lib/x402/idempotency-cache.js](../../api/_lib/x402/idempotency-cache.js):+ no lock, so two concurrent requests with the same paymentId can both miss and settle twice.+- **Audit log** — [api/_lib/x402/audit-log.js](../../api/_lib/x402/audit-log.js): stores events+ but offers no query-by-transaction API, so reconciliation is manual.++## What to build++1. **Idempotency everywhere.** Make the payment-identifier path **mandatory** for every paid+ endpoint (verify → settle keyed on a stable payment id). Add it to the endpoints missing it+ (`vanity`, `dance-tip`, and any others you find). A retried request returns the original+ result, never a second charge.+2. **Concurrency-safe settlement.** Add a real lock (Redis SETNX/lease or equivalent) around+ settle keyed by payment id so parallel requests can't both settle. Handle lock+ acquisition/expiry cleanly.+3. **Settlement reconciliation job.** A cron (under `api/cron/`, hardened per `13`) that finds+ payments stuck in "verified-but-not-settled" (or settled-but-not-fulfilled) and resolves+ them — completes settlement, fulfills, or flags for refund. Idempotent and observable (`12`).+4. **Refund / credit-back path.** When a paid action fails *after* settlement (provider 5xx,+ RPC error), trigger a real refund or platform credit-back through a defined mechanism — not+ manual ops. Record it in the ledger and notify the buyer+ ([api/_lib/notify.js](../../api/_lib/notify.js) / email).+5. **Queryable audit.** Add an owner/admin endpoint to query settlement/audit events by+ transaction id and by buyer, so any charge can be traced end-to-end.++## Hard rules specific to this task++- **Real funds, real chain.** Every verify/settle/refund hits the real facilitator/chain. No+ simulated settlement, no fake refund. Test with synthetic placeholders, never a real+ third-party mint (**$THREE** CA or `THREEsynthetic1111…` only).+- Preserve the verify→grind/generate→settle ordering where the endpoint depends on it.+- Don't retry settlement in a way that can double-settle — that's the whole point; coordinate+ with `09`'s retry policy (settlement is non-idempotent unless keyed + locked).++## Definition of done++README DoD, plus: every paid endpoint enforces idempotency (a replayed payment returns the+original result, no second charge); concurrent same-id settles are serialized; the+reconciliation cron resolves stuck payments; a post-settlement failure produces a real refund++ buyer notification; audit is queryable by tx. Vitest covers double-charge prevention, the+concurrency lock, and the reconciliation logic. Changelog (`security`/`fix`). Self-review,+then harden the next-weakest payment path.++Delete this file when done.diff --git a/prompts/production-grade/11-rate-limit-and-abuse-caps.md b/prompts/production-grade/11-rate-limit-and-abuse-caps.mdnew file mode 100644index 000000000..1c1d74098--- /dev/null+++ b/prompts/production-grade/11-rate-limit-and-abuse-caps.md@@ -0,0 +1,62 @@+# Task 11 — Per-principal spend caps + global concurrency ceilings++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track D —+> Reliability.** Protects platform margin and prevents abuse. Coordinate with `09` (resilience)+> and `12` (so cap hits are observable).++## The thesis++Several of the most expensive operations on the platform — paid 3D generation, premium LLM+chat, token launches, vanity grinding — are throttled per-IP but **not capped per principal or+globally**. An authenticated user (or a botnet spread across IPs) can run up real platform cost+with no ceiling: $9/min of Claude tokens, hundreds of paid generations across 10 IPs, unbounded+launches from a compromised agent. A $1B platform protects its unit economics by construction.++## What exists today (read first)++- **Rate limiter** — [api/_lib/rate-limit.js](../../api/_lib/rate-limit.js): per-IP/per-route+ buckets (e.g. `chatUser` 40/min, forge per-user/hr, vanity publish 12/10m). Real and used —+ but it's request-count throttling, not **spend** or **global concurrency** control, and it+ doesn't differentiate cost per model/provider.+- **Forge scaling** — [api/_lib/forge-scale.js](../../api/_lib/forge-scale.js): per-provider ++ per-user slots, but **no global ceiling** on total concurrent paid Replicate/NVIDIA jobs.+- **Cost-bearing endpoints lacking principal/global caps:**+ [api/chat.js](../../api/chat.js) (no per-model spend cap — Claude/GPT cost ~10× free Groq),+ [api/x402/pump-launch.js](../../api/x402/pump-launch.js) and+ [api/pump/launch-agent.js](../../api/pump/launch-agent.js) (no per-agent daily launch+ ceiling), [api/forge.js](../../api/forge.js) (no global generation concurrency cap),+ vanity grind ([api/x402/vanity.js](../../api/x402/vanity.js), grind queue depth unbounded).++## What to build++1. **Per-principal spend/usage caps.** Add a real, configurable per-user (and per-agent where+ relevant) ceiling on expensive operations over a rolling window — denominated in cost, not+ just request count. Premium-LLM chat, paid generation, launches, and grinding each get a+ sane cap with a clear, actionable 429/upgrade response (coordinate the upgrade CTA with+ `02`). Caps must be **cost-aware**: a Claude call counts more than a free-Groq call.+2. **Global concurrency ceilings.** Add a platform-wide cap on total concurrent+ cost-bearing jobs (paid forge generations, grind workers) so a coordinated surge can't blow+ the budget. Excess requests queue or get a clean "busy, try shortly" with a retry hint —+ never silently dropped, never unbounded.+3. **Per-agent launch ceiling.** Cap token launches per agent/day so a compromised custodial+ agent can't spam launches. Real ceiling, real enforcement, real audit entry on hit.+4. **Make limits observable.** Emit a metric/log on every cap hit (via `12`) and a real signal+ when a global ceiling is saturated (input to `12`'s status + alerting).++## Hard rules specific to this task++- Caps protect cost **without** breaking legitimate power users: tune to real provider pricing,+ give holders their real higher quota ([three-tier.js](../../api/_lib/three-tier.js)), and+ always return an actionable response (why blocked, when to retry, how to upgrade).+- **$THREE only** in any upgrade/quota copy.+- Don't double-charge or lose work when a request is queued/throttled — coordinate with `10`.++## Definition of done++README DoD, plus: each expensive endpoint enforces a per-principal cost-aware cap with an+actionable response; a global concurrency ceiling bounds total paid jobs; per-agent launch+ceiling enforced; every cap hit is observable; holder quotas honored. Vitest covers cap+enforcement (per-principal, global, per-agent) and the cost-weighting. Changelog+(`infra`/`security`). Self-review, then close the next-weakest unbounded cost path.++Delete this file when done.diff --git a/prompts/production-grade/12-observability-and-status.md b/prompts/production-grade/12-observability-and-status.mdnew file mode 100644index 000000000..9b6aeebbf--- /dev/null+++ b/prompts/production-grade/12-observability-and-status.md@@ -0,0 +1,71 @@+# Task 12 — Observability: tracing, server-side Sentry, secret scrubbing, live status++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track D —+> Reliability.** Foundational — `09`/`10`/`11`/`13` all emit into what you build here.+> Lands early so the other Track D tasks have somewhere to report.++## The thesis++You can't operate a $1B platform you can't see. Today errors are mostly `console.log`, there's+no request tracing across the Vercel→upstream boundary, server-side exceptions in functions+largely aren't captured, secrets can leak into logs, and `/api/status` reports green even when a+core dependency is down. This task makes the platform observable and its health honest.++## What exists today (read first)++- **Sentry, thinly wired** — [api/_lib/sentry.js](../../api/_lib/sentry.js) (fire-and-forget,+ no retry, no URL scrubbing); only ~27 `captureException` calls across ~360 handlers, mostly+ on the client ([api/client-errors.js](../../api/client-errors.js)). Server exceptions in+ functions are largely uncaptured.+- **Logging is unstructured** — `console.*` throughout `api/` and `workers/`; no request id /+ trace id propagation in [api/_lib/http.js](../../api/_lib/http.js).+- **Secret-leak risk** — [api/_lib/http.js](../../api/_lib/http.js) logs raw `err.message` on+ 5xx (RPC URLs often embed API keys); redaction (`SENSITIVE_QUERY_KEYS`) misses `api-key`,+ `sig`, `auth`, etc.+- **Status is shallow** — [api/status.js](../../api/status.js) returns cached cron-probe data+ and does **not** check live deps (Redis limiter, LLM providers via+ [api/_lib/llm-health.js](../../api/_lib/llm-health.js), Solana RPC). Forge/LLM health+ ([api/_lib/forge-health.js](../../api/_lib/forge-health.js)) exists but isn't reflected.+ Status page UI: [pages/status.html](../../pages/status.html).++## What to build++1. **Structured logging + request tracing.** A small structured logger (level, message,+ context, request id, route) used across handlers via [http.js](../../api/_lib/http.js).+ Generate/propagate a request/trace id (`x-request-id`) through inbound handling and outbound+ calls (tie into `09`'s wrapper) so a single request can be followed end to end.+2. **Real server-side error capture.** Route handler exceptions through+ [sentry.js](../../api/_lib/sentry.js) (or equivalent) with request/trace context, at the+ `http.js` boundary so coverage is uniform — not 27 ad-hoc call sites. Add retry so a dropped+ Sentry POST doesn't lose the event silently.+3. **Secret scrubbing.** Scrub secrets from everything logged or sent to Sentry: redact+ credentials in URLs (RPC keys), expand the sensitive-key list (`api-key`, `sig`, `auth`,+ `token`, authorization headers), and never serialize a keypair/secret. Add a test that a+ known-secret-shaped string never reaches a log/Sentry payload.+4. **Honest live status.** Make [api/status.js](../../api/status.js) probe **live**+ dependencies — limiter/Redis reachability, LLM provider health+ ([llm-health.js](../../api/_lib/llm-health.js)), forge backend health+ ([forge-health.js](../../api/_lib/forge-health.js)), Solana RPC — and reflect degraded+ states (not just hard down). Surface per-component status on+ [pages/status.html](../../pages/status.html) with designed states. Include cron+ freshness (from `13`) so "rewards-distribute last ran 6h ago" is visible.+5. **Metrics sink for the other tasks.** Provide the lightweight metric/log hook that `09`+ (degradation), `11` (cap hits), `13` (cron outcomes) emit into.++## Hard rules specific to this task++- **Never log or transmit a secret.** This is a security task as much as an ops one — the+ scrubbing test is mandatory.+- Observability must not add meaningful latency or block the request path (fire-and-forget with+ bounded cost; degrade silently if the sink is down — but record that it degraded).++## Definition of done++README DoD, plus: a request can be traced by id through handler + upstreams; handler exceptions+reach Sentry with context; the secret-scrubbing test passes (no secret in any log/payload);+`/api/status` reflects real live-dependency and cron-freshness state and the status page shows+per-component health with designed states. Vitest covers scrubbing + the status aggregation+logic. Changelog (`infra`/`security`). Self-review, then widen logging coverage to the next+subsystem.++Delete this file when done.diff --git a/prompts/production-grade/13-cron-hardening.md b/prompts/production-grade/13-cron-hardening.mdnew file mode 100644index 000000000..ebc9aebdb--- /dev/null+++ b/prompts/production-grade/13-cron-hardening.md@@ -0,0 +1,63 @@+# Task 13 — Cron hardening: locks, run history, failure alerting++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track D —+> Reliability.** Depends on `12` (emits run outcomes + freshness into status). The+> reconciliation cron from `10` and the asset/seed crons all benefit.++## The thesis++Background jobs are where silent failures live. three.ws runs real crons — rewards+distribution, forge seeding, oracle ticks, uptime checks — but they can double-run (no+distributed lock), fail silently (inconsistent error handling), and never record when they last+succeeded (so staleness is invisible). A $1B platform's automated money/asset jobs are+locked, observable, alerting, and auditable.++## What exists today (read first)++- **Cron dispatcher** — [api/cron/[name].js](../../api/cron/[name].js): dynamic dispatch;+ per-cron error handling is inconsistent (some `captureException`, most `console.error`).+- **No concurrency lock** — [api/cron/forge-seed-cron.js](../../api/cron/forge-seed-cron.js)+ runs per-minute; if a run exceeds 60s, Vercel can spawn a second instance that races DB state.+- **No run history** — nothing records each cron's last-success time, so `/api/status` can't+ report staleness and a stalled `rewards-distribute` goes unnoticed for hours.+- **Uptime check is narrow** — [api/cron/uptime-check.js](../../api/cron/uptime-check.js) probes+ ~5 hardcoded public paths; new critical endpoints (e.g. paid flows) aren't monitored, and+ it's GET-only (no signed/payment flow coverage).+- **Shared secret** — a single `CRON_SECRET` ([api/_lib/env.js](../../api/_lib/env.js)) guards+ all crons.++## What to build++1. **Distributed lock per cron.** A real lease/lock (Redis SETNX with TTL or equivalent) so a+ given cron has at most one active run; a slow run blocks the next tick instead of racing.+ Release on completion; auto-expire on crash.+2. **Run-history / last-success tracking.** Record every cron run (name, start, end, outcome,+ duration, error) to a real table. Expose last-success + last-error so `12`'s `/api/status`+ can show freshness ("X last ran N min ago"). Add queue-depth visibility where a cron drains a+ work table (e.g. forge seed jobs) so backups are detectable.+3. **Uniform failure handling + alerting.** Standardize cron error handling (every cron+ captures to Sentry via `12` and emits a run-history failure row), and alert on+ failure/staleness/queue-backup through the existing ops channel (the uptime check already+ pages Telegram on failure — reuse that path; don't add a new vendor).+4. **Broaden synthetic monitoring.** Extend [uptime-check.js](../../api/cron/uptime-check.js) to+ cover the critical endpoints that matter now (including a safe synthetic check of a paid/+ signed path where feasible) instead of the 5 hardcoded public GETs.+5. **(If low-risk) per-cron secrets.** Move toward per-cron secrets or signed invocation so a+ single leaked secret can't trigger every cron. Keep it simple; don't break existing schedules.++## Hard rules specific to this task++- **Idempotent crons.** Locking + run-history must not cause a missed run to silently skip+ money/asset work — a lock that can't be acquired this tick should be picked up next tick, not+ dropped. Money jobs (rewards, reconciliation from `10`) must never double-pay.+- Don't change cron schedules or break the dispatcher contract; harden in place.++## Definition of done++README DoD, plus: each cron holds a lock (a forced overlap doesn't double-run); run history+records every execution with outcome; `/api/status` shows real cron freshness; failures/+staleness/queue-backups alert through the existing channel; synthetic monitoring covers the+real critical paths. Vitest covers the lock (no double-run) and the run-history write.+Changelog (`infra`). Self-review, then harden the next-weakest job.++Delete this file when done.diff --git a/prompts/production-grade/14-e2e-tests-and-ci-gate.md b/prompts/production-grade/14-e2e-tests-and-ci-gate.mdnew file mode 100644index 000000000..a450941a1--- /dev/null+++ b/prompts/production-grade/14-e2e-tests-and-ci-gate.md@@ -0,0 +1,63 @@+# Task 14 — E2E tests for the money paths + put Playwright in the merge gate++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track E —+> Engineering excellence.** Lands early; it's the safety net every other task ships behind.+> Coordinate with `08`/`10` (checkout/payments specs) so E2E covers the real flow.++## The thesis++The critical flows that *make the money* — checkout/x402 payment, signup/auth, Forge+generation, avatar creation — have thin or no end-to-end coverage, and Playwright **isn't in+the CI merge gate** (it's manual-only). That means a regression in checkout can ship green. A+$1B platform gates its revenue paths behind automated browser tests that block merge.++## What exists today (read first)++- **Unit tests are solid** — ~219 vitest files; Forge, avatar, wallet, on-chain parity covered+ ([tests/](../../tests/)).+- **E2E is thin** — [playwright.config.js](../../playwright.config.js) runs ~10 specs in+ [tests/e2e/](../../tests/e2e/) (e.g. `coin-buy-trade.spec.js`, `nav-auth.spec.js`). There is+ **no** end-to-end test for the main x402 checkout/payment modal, the full signup/identity+ flow, the Forge text→3D happy path, or avatar creation.+- **CI doesn't gate E2E** — [.github/workflows/ci.yml](../../.github/workflows/ci.yml) runs+ lint/vitest/build but `npm run test:e2e` is not in the merge gate.+- **No coverage reporting** — [vitest.config.js](../../vitest.config.js) has no coverage config;+ the tested % of API handlers is unknown.++## What to build++1. **E2E specs for the critical flows** (real browser, real app via `npm run dev`, against real+ or properly-seeded test data — no mocked happy paths that hide breakage):+ - **Checkout / x402 payment** — the full pay flow (coordinate with `08`/`10`): quote →+ pay → confirm → unlock/receipt, including the failure/retry branch.+ - **Signup / auth** — complete the identity flow (extend+ [tests/e2e/nav-auth.spec.js](../../tests/e2e/nav-auth.spec.js)): email/SIWS/SIWE/OAuth+ callback chain through to a signed-in session.+ - **Forge text→3D** — prompt → generate → result rendered (free lane), with the empty/error+ states asserted.+ - **Avatar creation** — create/upload → rigged → reachable agent page.+2. **Put Playwright in the CI gate.** Add an E2E job to+ [.github/workflows/ci.yml](../../.github/workflows/ci.yml) that runs the specs on PR and+ **blocks merge** on failure. Make it reliable (seeded data, retries on genuine flake only,+ sensible timeouts) — a flaky gate gets ignored, which is worse than none.+3. **Coverage reporting.** Add coverage (c8/v8) to [vitest.config.js](../../vitest.config.js),+ report it in CI, and set a floor on **changed** files so new code can't ship untested.+ Don't retrofit a giant global threshold that blocks unrelated work — gate the diff.++## Hard rules specific to this task++- **Real flows, real assertions.** E2E that stubs the thing it claims to test is worse than no+ test. Use real endpoints / seeded test fixtures; if a flow needs test funds, use a synthetic+ placeholder (**$THREE** CA or `THREEsynthetic1111…`), never a real third-party mint.+- The gate must be **trustworthy**: if it's flaky, fix the flake or quarantine the spec+ explicitly with a tracked reason — never `continue-on-error` the whole job to make it pass.++## Definition of done++README DoD, plus: the four critical flows have passing E2E specs (including a failure branch+for checkout); the E2E job runs on PR and blocks merge; coverage is reported and a changed-files+floor is enforced; the gate is green and not flaky over repeated runs. Changelog+(`infra`/`improvement` — or omit if you judge it internal-only per CLAUDE.md). Self-review,+then add the next-most-valuable E2E flow you noticed was uncovered.++Delete this file when done.diff --git a/prompts/production-grade/15-ci-security-and-quality-gates.md b/prompts/production-grade/15-ci-security-and-quality-gates.mdnew file mode 100644index 000000000..9de6e0276--- /dev/null+++ b/prompts/production-grade/15-ci-security-and-quality-gates.md@@ -0,0 +1,60 @@+# Task 15 — CI hardening: dependency scanning, blocking typecheck, bundle budget++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track E —+> Engineering excellence.** Independent of `14` but completes the CI story. Mostly CI/config+> work — much of it may be internal-only (no changelog entry) per CLAUDE.md.++## The thesis++A $1B platform doesn't merge unvetted dependencies, ship type-unsafe contract changes, or let+multi-megabyte bundles slip in silently. three.ws's CI is good but has three holes: no+dependency/vulnerability scanning, typecheck is advisory (`continue-on-error`), and the bundle+size limit is a warning, not a gate. Close them.++## What exists today (read first)++- **CI** — [.github/workflows/ci.yml](../../.github/workflows/ci.yml): lint, vitest, source+ guards, build check. Typecheck runs with `continue-on-error: true` (~line 78) — advisory only.+- **No dependency scanning** — no `.github/dependabot.yml`, no `npm audit` gate, no SBOM. With+ ~20 workspaces and 100+ direct deps, transitive CVEs can ship unnoticed.+- **Bundle limit is a warning** — [vite.config.js](../../vite.config.js)+ `chunkSizeWarningLimit: 1000` (~line 219) warns but never fails; multi-MB chunks ship silently.+- **Typecheck setup** — `npm run typecheck` (`tsc -p jsconfig.json`) passes today (0 errors per+ the audit), so flipping it to blocking is low-risk and locks in the win.++## What to build++1. **Dependency / vulnerability scanning in CI.** Add Dependabot (`.github/dependabot.yml`) for+ the npm workspaces (grouped, sensible cadence) **and** a CI step that runs `npm audit` (or an+ equivalent scanner) and fails on high/critical advisories. Tune the severity threshold so the+ gate is meaningful but not noise — document any allowlisted advisory with a reason.+2. **Make typecheck blocking.** Flip the typecheck job off `continue-on-error` in+ [ci.yml](../../.github/workflows/ci.yml) now that it's clean, so a type regression blocks+ merge. If flipping surfaces latent errors, fix them (don't re-disable). Consider adding+ `@ts-check` to high-value `api/` handlers incrementally to widen real coverage — but don't+ boil the ocean; the gate is the win.+3. **Bundle-size budget gate.** Turn the bundle limit into a real gate: fail CI when a chunk+ exceeds a budget you set from current real sizes (with a little headroom), so regressions are+ caught. Keep heavy-but-intentional chunks (three.js, solana) within explicit, documented+ budgets rather than an undifferentiated global number.+4. **Wire the existing audit scripts into the gate.** The repo already has+ `audit:handlers`/`audit:pages`/`audit:mcp`/`audit:deploy` — ensure the ones that should block+ merge actually run in CI (audit which are gated vs manual; close the gaps).++## Hard rules specific to this task++- **Gates must be trustworthy, not theatrical.** A scanner that always fails on irrelevant+ advisories gets bypassed. Set thresholds a real team would keep green, and document+ exceptions.+- Don't break existing green CI for unrelated PRs. Roll out blocking gates in a way that's+ immediately passing on `main` (fix-forward, not disable).++## Definition of done++README DoD adapted for infra: Dependabot configured; an `npm audit` (or equivalent) gate fails+on high/critical; typecheck is blocking and green; a bundle-size budget gate is in place and+green; the appropriate `audit:*` scripts run in CI. Demonstrate each gate catches a planted+regression (then revert the plant). Changelog only if user-visible (likely omit — internal).+Self-review, then tighten the weakest gate.++Delete this file when done.diff --git a/prompts/production-grade/16-performance-and-assets.md b/prompts/production-grade/16-performance-and-assets.mdnew file mode 100644index 000000000..f23e27131--- /dev/null+++ b/prompts/production-grade/16-performance-and-assets.md@@ -0,0 +1,67 @@+# Task 16 — Performance: lazy-load heavy GLBs, move the animation set to CDN, watch CWV++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track E —+> Engineering excellence.** Independent. Touches the asset pipeline and Vite config — be+> careful not to break the build (read the `npx vercel build` trap in the README).++## The thesis++A 3D platform lives or dies on load performance: a homepage that blocks first paint on+multi-megabyte avatar decodes, and a 200MB+ animation set committed to git and shipped on every+deploy, are exactly the things that tank Core Web Vitals and bounce mobile users. Speed is a+feature — and at $1B scale, a ranked one. Make the heavy stuff lazy and off the critical path.++## What exists today (read first)++- **Optimization tooling exists** — [scripts/compress-glbs.mjs](../../scripts/compress-glbs.mjs)+ / [scripts/optimize-glb.mjs](../../scripts/optimize-glb.mjs) (WebP texture compression);+ Vite prebundles three.js, defers the Draco loader, and splits chunks+ ([vite.config.js](../../vite.config.js)).+- **But the heavy assets aren't managed for first paint:**+ - Avatar GLBs are 160KB–3.2MB each in [public/avatars/](../../public/avatars/) and are loaded+ eagerly by avatar pickers (`/start`, `/create`) — decode blocks first paint.+ - The animation set in [public/animations/](../../public/animations/) is **~200MB committed to+ git**, redownloaded every deploy, with no clear per-page loading story.+ - [vite.config.js](../../vite.config.js) `chunkSizeWarningLimit` only warns (gate is `15`).+ - No global Core Web Vitals monitoring (there's an IRL-only perf budget,+ [src/irl/perf-budget.js](../../src/irl/perf-budget.js)).++## What to build++1. **Lazy-load heavy GLBs off the critical path.** Avatar pickers and 3D scenes should show a+ lightweight placeholder (poster/thumbnail or a tiny proxy) and defer the full GLB decode+ until needed/visible (intersection-based, on-demand). First paint must not wait on a 3MB+ model. Keep the universal animation system intact (CLAUDE.md — no rig allowlist).+2. **Get the animation set off git and onto the CDN.** Move [public/animations/](../../public/animations/)+ (the ~200MB built GLB clips) to R2/CDN delivery (the repo already proxies R2 — see the+ `/r2-proxy` config in [vite.config.js](../../vite.config.js)), reference them by CDN URL,+ load per-page only what's used, and stop committing the binaries (gitignore + a documented+ `build:animations` → upload step). Don't break the animation pipeline+ ([scripts/build-animations.mjs](../../scripts/build-animations.mjs),+ [docs/3d-asset-pipeline.md](../../docs/3d-asset-pipeline.md)) — update it.+3. **Ensure assets are compressed.** Run/verify the GLB compression pipeline covers the shipped+ avatars; flag any uncompressed outliers. Set correct long-cache headers for immutable+ hashed assets ([vercel.json](../../vercel.json)).+4. **Core Web Vitals monitoring.** Add lightweight, global CWV (LCP/INP/CLS) reporting (e.g.+ `web-vitals` → the analytics sink) so regressions are measurable. Wire a real budget/alert+ so a bad deploy is visible.++## Hard rules specific to this task++- **Don't regress correctness for speed.** Avatars and animations must still load and play+ everywhere they do today — lazy means deferred, not dropped. Test the pickers and key 3D+ surfaces in a real browser.+- Mind the build traps: don't let `npx vercel build` clobber `api/*.js`; verify the production+ build (`npm run build`) still succeeds and the moved assets resolve.+- Moving 200MB of git history is sensitive — remove the binaries from future commits and CDN+ them; do **not** rewrite published history without explicit user sign-off.++## Definition of done++README DoD, plus: avatar pickers and 3D pages show a placeholder and defer heavy decode (first+paint no longer blocked — verify with a throttled profile); the animation set loads from CDN+and is no longer committed; assets are compressed with correct cache headers; CWV reporting is+live with a budget. Tests/build verify assets still resolve and play. Changelog+(`improvement`/`infra`). Self-review, then optimize the next-heaviest surface.++Delete this file when done.diff --git a/prompts/production-grade/17-company-and-brand-surfaces.md b/prompts/production-grade/17-company-and-brand-surfaces.mdnew file mode 100644index 000000000..d761beb90--- /dev/null+++ b/prompts/production-grade/17-company-and-brand-surfaces.md@@ -0,0 +1,62 @@+# Task 17 — Company surfaces: About, team, careers, press/brand kit++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track F —+> Credibility.** Independent. This is the cheapest credibility you can buy and it's entirely+> missing today.++## The thesis++Enterprise buyers, partners, press, and serious users all ask the same silent question: "Is+this a real company or a weekend project?" three.ws has world-class legal/docs/security+surfaces but **no About page, no team, no careers, no press/brand kit** — the basic signals+of legitimacy. A $1B company looks like a company. Build that surface.++## What exists today (read first)++- **Strong legal/docs/security already** — `public/legal/*`, `docs/*`,+ `public/.well-known/security.txt`, [pages/support.html](../../pages/support.html),+ [pages/status.html](../../pages/status.html). Reuse their layout/tone.+- **Company identity is basically absent** — only footer links+ ([public/footer.html](../../public/footer.html)) and the README. There is **no** `/about`,+ `/team`, `/careers`, or `/press`. Press mentions exist (Business Insider, IBM, Yahoo Finance,+ Crunchbase, Vogue) but only as scattered footer links.+- Nav/manifest: register any new page in [data/pages.json](../../data/pages.json) so+ `npm run audit:pages` passes, and link it from [public/nav-data.js](../../public/nav-data.js)+ / [public/footer.html](../../public/footer.html).++## What to build++Real, on-brand pages (match the design system and the existing page chrome):++1. **About / company** (`/about`) — the mission ("Give your AI a body."), what three.ws is, how+ it works at a glance, the real traction signals that exist (press logos linking to the real+ articles, on-chain/ecosystem facts that are true). No invented metrics — only real, citable+ facts. If a number isn't real, don't print it.+2. **Team** (`/team` or a section of `/about`) — the people behind it, to whatever degree the+ user is comfortable making public. Build the page and layout; where specific bios/photos+ aren't provided, leave a clearly-structured, easily-fillable section rather than inventing+ names. (Ask nothing — build the structure; the user can populate.)+3. **Careers** (`/careers`) — even a simple "we're building the body layer for AI agents,+ here's how to reach us / roles we want" page signals growth. Wire to the real contact channel+ ([pages/support.html](../../pages/support.html) emails).+4. **Press / brand kit** (`/press`) — logo assets (the real three.ws marks), color palette+ (straight from [public/tokens.css](../../public/tokens.css)), the one-liner, boilerplate+ description, and press contact. Make assets downloadable. Consolidate the existing press+ mentions here.++## Hard rules specific to this task++- **No fabricated facts.** Don't invent funding, user counts, customer logos, awards, or team+ members. Use only what's real and citable; structure the rest for the user to fill. Inventing+ company facts is the same violation as fake data.+- **$THREE only** if tokens are mentioned at all.+- Every page: responsive, accessible, designed empty/edge states, real links (no dead `#`).++## Definition of done++README DoD, plus: `/about`, `/team`, `/careers`, `/press` are live, on-brand, responsive,+accessible, linked from nav + footer, and pass `npm run audit:pages`; brand assets download;+press mentions consolidated; zero invented facts. Changelog (`docs`/`feature`). Self-review,+then improve the weakest page (likely About's traction section or the brand kit completeness).++Delete this file when done.diff --git a/prompts/production-grade/18-compliance-and-trust-pages.md b/prompts/production-grade/18-compliance-and-trust-pages.mdnew file mode 100644index 000000000..8ee37cb86--- /dev/null+++ b/prompts/production-grade/18-compliance-and-trust-pages.md@@ -0,0 +1,65 @@+# Task 18 — Compliance & trust: cookie consent, a11y statement, disclosure, incident history++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track F —+> Credibility.** Independent. These are the trust surfaces enterprise/partners and EU users+> check for — present individually small, collectively the difference between "credible" and+> "hobby."++## The thesis++three.ws already has real legal, security, and status surfaces — better than most startups.+The remaining gaps are the specific trust artifacts buyers and regulators look for: a GDPR+cookie-consent path, a published accessibility commitment, a responsible-disclosure/bug-bounty+policy, and a persistent incident history. Each is small; together they signal a platform that+takes trust seriously enough to scale.++## What exists today (read first)++- **Privacy/ToS/EULA are real** — `public/legal/{privacy,tos,eula,aws-marketplace-eula}.html`+ (privacy already documents cookies + GDPR rights, but there's **no consent UI** and **no+ standalone cookie policy**).+- **Security is real** — `public/.well-known/security.txt` (RFC 9116),+ [docs/security.md](../../docs/security.md) — but there's **no public responsible-disclosure /+ bug-bounty page** linked for users, and **no compliance posture** (SOC2 status/roadmap).+- **Status is real-time** — [pages/status.html](../../pages/status.html) (live, 90-day uptime)+ — but there's **no persistent incident history / postmortem archive**.+- **A11y is strong in code** (per the changelog) but there's **no public accessibility+ statement** (`/accessibility`) and no a11y feedback channel.++## What to build++1. **Cookie consent (GDPR).** A real, accessible consent banner/preference UI for non-essential+ cookies/analytics, honoring the choice (don't load non-essential tracking before consent in+ relevant regions). Plus a standalone `/legal/cookies` page (or a clearly-linked section)+ listing the real cookies the privacy policy already documents. Consent state persists and is+ revocable.+2. **Accessibility statement** (`/accessibility`) — the real WCAG target (state the level+ honestly given the code's current state — don't over-claim), the commitment, known+ limitations, and a dedicated feedback channel ([pages/support.html](../../pages/support.html)+ emails). Link from footer.+3. **Responsible disclosure / security policy page** — a public page describing how to report a+ vulnerability, scope, safe-harbor language, and response SLA, consistent with+ `security.txt`. If the user wants a bug bounty, structure it; otherwise a clear coordinated-+ disclosure policy. Link from `security.txt`, `/security` (if present), and footer.+4. **Incident history / status archive.** Persist past incidents (date, impact, resolution,+ postmortem link) and surface them on [pages/status.html](../../pages/status.html) so the+ status page has memory, not just a live light. Real incidents only — start the log; don't+ invent past ones. Coordinate with `12`/`13` (they produce the real signal).++## Hard rules specific to this task++- **Honest claims only.** Don't claim SOC2 you don't have, a WCAG level you don't meet, or+ incidents that didn't happen. State the real posture and the roadmap. False compliance claims+ are worse than absent ones.+- Accessible and responsive themselves (a cookie banner that traps keyboard focus or fails+ contrast is self-defeating).++## Definition of done++README DoD, plus: a working, accessible, revocable cookie-consent flow + cookies page;+`/accessibility` live with an honest WCAG claim + feedback channel; a public disclosure/security+policy linked from `security.txt` and footer; an incident-history section on the status page+backed by real data. All pass `npm run audit:pages` and are linked from footer. Changelog+(`security`/`docs`). Self-review, then strengthen the weakest claim's accuracy/clarity.++Delete this file when done.diff --git a/prompts/production-grade/19-i18n-activation.md b/prompts/production-grade/19-i18n-activation.mdnew file mode 100644index 000000000..0a55a528c--- /dev/null+++ b/prompts/production-grade/19-i18n-activation.md@@ -0,0 +1,62 @@+# Task 19 — Internationalization: activate the pipeline that's already built++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track F —+> Credibility / reach.** Independent. Like the referral task, this is a built-but-dormant+> asset — activating it unlocks global reach for near-zero net-new infrastructure.++## The thesis++A $1B consumer platform is multilingual. three.ws has a real, production-grade i18n+pipeline — extraction, translation, glossary lock, build gates — but it's only run for **2 of+10 configured locales** and ~20 strings (homepage hero only). There's no language switcher and+no RTL support. The machinery exists; it's just turned off for the world outside English.++## What exists today (read first — it's real)++- **Pipeline** — [scripts/i18n-extract.mjs](../../scripts/i18n-extract.mjs) ++ [scripts/i18n-translate.mjs](../../scripts/i18n-translate.mjs) (`npm run i18n`,+ `i18n:extract`, `i18n:translate`, `i18n:lint`). Config in [.i18nrc.json](../../.i18nrc.json):+ 10 target locales (`es, zh-CN, ja, ko, fr, de, pt-BR, ar, hi, ru`), Groq with a Gemini+ fallback for CJK/Arabic/Hindi, and a **glossary lock** that preserves `$THREE`, `x402`,+ `USDC`, `Solana`, `MCP`, `Forge`, etc. byte-for-byte.+- **Runtime** — [public/i18n.js](../../public/i18n.js) swaps strings via `data-i18n` attributes.+- **Coverage today** — [public/locales/](../../public/locales/): only `en.json` (~19 keys) ++ `es.json`; `manifest.json` declares only `en`/`es`. RTL locales are configured but no layout+ support exists. **No language switcher UI.**++## What to build++1. **Widen string extraction.** Annotate the high-traffic surfaces (home, nav/footer, forge,+ marketplace, pricing, onboarding, the new Track F pages) with `data-i18n` so+ `i18n:extract` captures the real user-facing copy — not just the hero. Keep the glossary+ terms locked. Don't translate code, addresses, or token names.+2. **Run the translation pipeline for all configured locales.** Generate real translations for+ the 10 locales via the existing `i18n:translate` flow, pass `i18n:lint` and the build gates,+ and update `manifest.json`. Real translations only — the pipeline produces them; never+ hand-fake a locale.+3. **Language switcher UI.** Add an accessible language selector (nav and/or footer) that swaps+ locale via [public/i18n.js](../../public/i18n.js), persists the choice, and respects the+ browser's `Accept-Language` on first visit. Designed, keyboard-operable, ARIA-correct.+4. **RTL support.** For `ar` (and any other RTL locale enabled), add real `dir="rtl"` layout+ support — logical CSS properties, mirrored components — so the RTL experience isn't broken.+ Verify a few key pages actually read correctly RTL.+5. **Keep it maintainable.** Wire extraction/translation into the build or a cron so new copy+ doesn't silently fall back to English forever (coordinate cadence with `13`). Document the+ workflow for future contributors.++## Hard rules specific to this task++- **Glossary terms stay byte-for-byte** ($THREE, x402, USDC, Solana, MCP, Forge, pump.fun,+ GLB, glTF, WebGL, Three.js, ERC-8004, Granite). Never translate or alter them.+- **$THREE only** — translations must not introduce any other coin name.+- Don't ship a half-translated page that mixes languages mid-sentence — gate on `i18n:lint`.++## Definition of done++README DoD, plus: the high-traffic surfaces are extracted and translated across the configured+locales (passing `i18n:lint` + build gates, `manifest.json` updated); an accessible language+switcher works and persists; RTL renders correctly on key pages; glossary terms preserved; a+documented path keeps new copy translated. Changelog (`feature`/`improvement`). Self-review,+then extend coverage to the next set of surfaces.++Delete this file when done.diff --git a/prompts/production-grade/20-design-system-and-a11y-polish.md b/prompts/production-grade/20-design-system-and-a11y-polish.mdnew file mode 100644index 000000000..674ceadb4--- /dev/null+++ b/prompts/production-grade/20-design-system-and-a11y-polish.md@@ -0,0 +1,87 @@+# Task 20 — Brand the free lanes (the seed task) + design-system & a11y polish sweep++> Read [00-README-orchestration.md](./00-README-orchestration.md) first. **Track F —+> Polish.** This is where the program started. Independent of the others; great as a final+> consistency pass once other surfaces have landed (or anytime — the relabel is standalone).++## The thesis++A $1B product is consistent and accessible to the pixel. three.ws is close — there's a real+token system and broad ARIA coverage — but vendor names leak into the UI, stray hex/px bypass+the tokens, 3D viewers aren't keyboard-navigable, and some modals don't manage focus. This task+is the craftsmanship sweep: small fixes, large cumulative effect. **It begins with the literal+request that kicked off this whole program.**++## Part 1 — Relabel the free Forge lanes (the seed task; do this first)++Today the Forge engine picker labels its two free lanes by **vendor**:+[src/forge.js](../../src/forge.js) `ENGINE_LABELS` (~line 180) maps `nvidia: 'NVIDIA'` and+`huggingface: 'Hunyuan3D'`, each rendered with a `FREE` pill → the buttons read "NVIDIA FREE"+and "Hunyuan3D FREE". These are three.ws's own house free engines (one is the text→3D lane, the+default for draft/standard; the other is the photo→3D / high-tier lane) — they should read as+**three.ws's**, not a vendor billboard.++- **Rename both to three.ws-native labels** that (a) are distinct from each other (the code+ deliberately avoids two lanes both reading "Free" — see the `ENGINE_FREE_PILL` comment around+ [src/forge.js:173](../../src/forge.js#L173)), and (b) communicate the lane's role. The+ natural differentiator is input modality: the `nvidia` lane is text→3D, the `huggingface`+ lane is photo→3D. Pick clean house names (e.g. by input — "Prompt" / "Photo" — or a house+ brand pairing); keep them short enough for the picker button. Use your product judgment;+ match the existing label tone (`'Fast'`, `'Meshy'`, etc.).+- **Keep the underlying engine truth in the tooltip/`title`/`aria-label`**, not the button face+ — the picker already builds `title`/`aria-label` from the backend `label`/`blurb`+ ([src/forge.js:466-472](../../src/forge.js#L466-L472)). The honest "free TRELLIS on NVIDIA+ NIM / Hunyuan3D on community GPUs" detail can stay in the hover text; the **button** shows the+ three.ws name + FREE pill.+- **Sweep the sibling surfaces** so they agree: the showcase map in+ [src/forge-showcase.js](../../src/forge-showcase.js) (line ~18, where `nvidia: 'Free'`), and+ the user-facing copy in [pages/forge.html](../../pages/forge.html) (~line 3304: "Free uses+ NVIDIA-hosted generation…"). Don't touch the backend ids/keys in+ [api/_lib/forge-tiers.js](../../api/_lib/forge-tiers.js) (`nvidia`/`huggingface` are routing+ ids) — only the **user-facing labels**. Vendor names may remain in code comments and backend+ blurbs; the goal is the **UI** reads as three.ws.++## Part 2 — Design-system polish sweep++Replace stray hardcoded values with tokens from [public/tokens.css](../../public/tokens.css):+- Inline px/hex in [src/forge-pay.js](../../src/forge-pay.js) (`.fpay-modal width:min(420px…)`,+ `.fpay-x`), [src/walk.js](../../src/walk.js) (inline `max-width:420px` etc.),+ [src/avatar-page.js](../../src/avatar-page.js) (`width:480px;height:480px`),+ [src/trades.js](../../src/trades.js) (48px chips), [src/first-meet.js](../../src/first-meet.js).+- JS breakpoints hardcoded in px — [src/marketplace-detail.js](../../src/marketplace-detail.js)+ (`max-width: 880px`) and [src/walk.js](../../src/walk.js) (`max-width: 640px`): route through a+ shared breakpoint constant/token so they can't drift from CSS.+- Custom skeleton vars in [src/agent-detail.css](../../src/agent-detail.css) that duplicate+ `--surface-*` — fold onto the tokens.+Don't churn working code for its own sake; fix the genuine inconsistencies, keep diffs tight.++## Part 3 — Accessibility polish++- **Keyboard-navigable 3D viewers.** The Three.js scenes (viewer, [pages/pose.html](../../pages/pose.html),+ [pages/scene.html](../../pages/scene.html), avatar studio) require a mouse to rotate/pan/zoom.+ Add documented keyboard controls + visible focus + an accessible-name for the canvas region.+- **Modal focus management.** Audit modals (Brain multi-LLM, others) for focus trap + restore on+ close; [src/share-panel.js](../../src/share-panel.js) already does this well — match it.+- **Icon-only buttons** in Brain/Scene/Pose studios need `aria-label`s.+- **Color-only state** (e.g. activity win/loss/open pills) needs a text/icon companion for+ non-color perception and contrast.++## Hard rules specific to this task++- **$THREE only** anywhere copy changes touch tokens.+- The free-lane relabel must not change routing/behavior — labels only. Verify both free lanes+ still select, still show the FREE pill, still gate text-vs-photo input exactly as before.+- Keep the design-system sweep additive and consistent; don't introduce new ad-hoc values while+ removing old ones.++## Definition of done++README DoD, plus: the two free Forge lanes read as three.ws house engines (distinct names, FREE+pill, vendor truth only in tooltip) across forge.js, forge-showcase.js, and forge.html, with no+behavior change; the listed hardcoded px/hex are tokenized and JS breakpoints centralized; 3D+viewers are keyboard-operable with focus; audited modals trap/restore focus; icon buttons+labelled; color-only states fixed. Exercise the Forge picker and a 3D viewer in a real browser.+Update [tests/glb-canonicalize.test.js] only if relevant; add/extend tests where you changed+logic. Changelog (`improvement`). Self-review, then fix the next inconsistency you spot.++Delete this file when done.diff --git a/prompts/production-hardening/00-INDEX.md b/prompts/production-hardening/00-INDEX.mdnew file mode 100644index 000000000..793af20bf--- /dev/null+++ b/prompts/production-hardening/00-INDEX.md@@ -0,0 +1,118 @@+# Production-Hardening Program — Prompt Library++A **sequenced set of execution prompts** that take three.ws from "impressive platform" to+"ship-grade, scalable, trustworthy $1B platform." Each file is a complete brief meant to be+pasted into a **fresh Claude Code chat in this repo**, run to completion, reviewed, and shipped.++Every prompt is grounded in a real audit of this codebase (100 API endpoints, 125 pages,+456+ tests, ~20 workers, a dozen published SDKs/MCP servers). The file paths cited inside each+prompt are real starting points.++> **Scope of this library:** *hardening, reliability, security, scale, trust, and developer+> experience* — the work that turns a great product into a bankable platform. For **new feature+> ideas**, see the sibling directories (`prompts/monetization`, `prompts/agent-wallets`,+> `prompts/moonshots`, `prompts/road-to-1b`, …). This set is deliberately complementary, not a+> replacement.++---++## How to run each prompt++1. Open a **new chat** in this repo. (CLAUDE.md auto-loads, so the operating rules already apply.)+2. Paste the **entire** prompt file as your first message.+3. Let it finish, review `git diff`, then commit and push **both** remotes (`threeD` + `threews`).+4. Tick the box below and move on.++One prompt ≈ one focused PR. Where a prompt is marked **Parallel-safe**, you can run it in its own+chat alongside others in the same phase. Concurrent agents share this worktree, so every prompt+already instructs: stage explicit paths, never `git add -A`, re-check `git status` before committing.++---++## Guardrails every prompt inherits (from CLAUDE.md)++- **$THREE is the only coin** — `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never reference any other token, anywhere.+- **No mocks / fake data / placeholders / TODOs / stubs.** Finished, real implementations only.+- **Push BOTH remotes.** Never pull or fetch from `threeD`.+- **Changelog** every user-visible change in `data/changelog.json`, then `npm run build:pages`.+- **Watch the deploy trap**: `npx vercel build` overwrites `api/*.js` with esbuild bundles — never commit those.++---++## The program (tracker)++### Phase 0 — Test confidence & release gate *(do first — everything depends on it)*+- [ ] [01 · Expand the deploy release gate + harden CI](01-release-gate-and-ci.md)+- [ ] [02 · Test the money path (x402, settlement, payments)](02-tests-payments-x402.md)+- [ ] [03 · Test the product core (forge, avatar, auto-rig)](03-tests-forge-avatar.md)+- [ ] [04 · E2E coverage for critical user journeys](04-e2e-critical-flows.md)+- [ ] [05 · Load, chaos, a11y & visual-regression test infra](05-test-infra-load-chaos-a11y.md)++### Phase 1 — Reliability & error handling+- [ ] [06 · Eliminate silent failures (empty catch / fire-and-forget)](06-error-handling-sweep.md)+- [ ] [07 · Fetch `.ok` guards + universal input validation](07-fetch-guards-input-validation.md)+- [ ] [08 · Unify circuit breakers on cockatiel](08-circuit-breakers-cockatiel.md)+- [ ] [09 · Graceful degradation for auth & payments](09-graceful-degradation.md)++### Phase 2 — Money safety *(highest blast radius)*+- [ ] [10 · Settlement↔delivery atomicity + refund path](10-settlement-delivery-refund.md)+- [ ] [11 · Idempotency for external x402 flows](11-x402-external-idempotency.md)+- [ ] [12 · Enforce agent spend policy (no silent platform-wallet fallback)](12-agent-spend-policy.md)+- [ ] [13 · $THREE gating: fail-closed + tier caching](13-three-gate-fail-closed.md)+- [ ] [14 · Payment reconciliation ledger + ops alerts](14-payment-reconciliation.md)++### Phase 3 — Security hardening+- [ ] [15 · Remediate vulnerable dependencies (axios et al.)](15-dependency-vuln-remediation.md)+- [ ] [16 · Startup secret validation + key-rotation safety](16-secrets-startup-validation.md)+- [ ] [17 · Rate-limit coverage audit across all endpoints](17-rate-limit-coverage.md)+- [ ] [18 · Global CSP + security headers](18-csp-security-headers.md)+- [ ] [19 · Pre-launch security review & pentest prep](19-security-review-pentest.md)++### Phase 4 — Frontend excellence+- [ ] [20 · Unify every list/feed on the shared state-kit](20-state-kit-unification.md)+- [ ] [21 · WCAG 2.2 AA accessibility pass](21-accessibility-wcag.md)+- [ ] [22 · Performance: code-split, lazy 3D, Lighthouse ≥90](22-performance-code-split.md)+- [ ] [23 · Responsive at 320 / 768 / 1440 across all surfaces](23-responsive-audit.md)+- [ ] [24 · Dead-path & broken-link CI gate](24-dead-path-link-gate.md)+- [ ] [25 · Server-side Forge thumbnails](25-forge-server-thumbnails.md)++### Phase 5 — Observability & operations+- [ ] [26 · Structured logging + request correlation/tracing](26-logging-tracing.md)+- [ ] [27 · Metrics, dashboards & SLOs](27-metrics-dashboards-slos.md)+- [ ] [28 · Deploy safety: auto-rollback + isolated staging](28-deploy-safety-rollback.md)+- [ ] [29 · Data backup/DR runbook + migration gating](29-backup-dr-migrations.md)+- [ ] [30 · Async job queue for heavy generation](30-async-job-queue.md)+- [ ] [31 · Worker autoscaling & one-command deploy](31-worker-autoscaling.md)++### Phase 6 — Developer ecosystem (SDK / MCP)+- [ ] [32 · Per-package CHANGELOGs + SDK unit tests](32-sdk-changelogs-tests.md)+- [ ] [33 · Unify the publish pipeline](33-publish-pipeline.md)+- [ ] [34 · Generated API-reference docs site](34-api-reference-docs.md)+- [ ] [35 · "Build on three.ws with MCP + x402" integration guide](35-mcp-x402-integration-guide.md)+- [ ] [36 · CI that proves the examples still work](36-examples-ci.md)++### Phase 7 — Growth, trust & launch+- [ ] [37 · SEO, structured data & agent-discovery surfaces](37-seo-discovery.md)+- [ ] [38 · First-run onboarding + product docs](38-onboarding-docs.md)+- [ ] [39 · Legal, trust & compliance surfaces](39-legal-trust-compliance.md)+- [ ] [40 · Public status page + incident runbooks](40-status-incident-runbooks.md)+- [ ] [41 · Final polish pass + launch-readiness checklist](41-launch-readiness.md)++---++## Sequencing++```+Phase 0 → Phase 1 → Phase 2 → Phase 3 ┐+ ├─► Phase 7 (launch)+Phase 4 ───────────────────────────────┤+Phase 5 ───────────────────────────────┤+Phase 6 ───────────────────────────────┘+```++Phases 0–3 are the critical chain — a payment bug or a silent failure is existential. Once Phase 0+gives you a trustworthy gate, Phases 4/5/6 run as parallel tracks. Phase 7 is the final mile.++**Whole-program done:** every box ticked · `npm run test:all` green · clean `audit:web` / `audit:links`+/ `check:images` · Lighthouse ≥90 on the top 10 pages · zero criticals in the security review ·+dashboards live · a rehearsed, tested rollback.diff --git a/prompts/production-hardening/01-release-gate-and-ci.md b/prompts/production-hardening/01-release-gate-and-ci.mdnew file mode 100644index 000000000..28a1038f5--- /dev/null+++ b/prompts/production-hardening/01-release-gate-and-ci.md@@ -0,0 +1,48 @@+# 01 · Expand the deploy release gate + harden CI++> **Phase 0 — Test confidence** · **Depends on:** none · **Parallel-safe:** no (foundation) · **Effort:** M++## Mission+Today the pre-deploy gate (`scripts/test-gate.mjs`) runs **7 files / ~73 assertions**, while+`.vercelignore` strips all but those 7 files from the deploy. A regression in any of the ~90+untested-on-deploy endpoints — including most of the money path — can ship silently. Turn the+gate into a real safety net and make CI enforce it. Nothing else in this program is trustworthy+until a green gate actually means "safe to deploy."++## Context (read first)+- `CLAUDE.md` + `STRUCTURE.md`.+- `scripts/test-gate.mjs` — the curated critical-path gate (`GATE_TESTS` list).+- `.vercelignore` — re-includes only the gate files into the deploy bundle. **Keep it in lockstep with the gate.**+- `.github/workflows/*.yml` — current CI (lint + full vitest + guards; typecheck is advisory only).+- `package.json` scripts: `test`, `test:core`, `test:gate`, `test:e2e`, `typecheck`, `lint`.++## Current state (from audit)+- Gate covers: `solana-confirm`, `http-cache-control`, `agent-custody-guards`, `agent-wallet-vanity`, `api/x402` (manifest/verify), `three-token-leaderboard`, `healthz`.+- **Not in the gate:** `x402-pay`, `x402-checkout`, `x402-merchant`, `x402-status`, agent A2A payment routes, all forge endpoints, wallet deposit/withdraw/pay, avatar create/render, `solana-rpc`.+- Typecheck (`tsc -p jsconfig.json`) runs advisory-only; ESLint warns but doesn't block. No flake detection.+- Drift risk: a gate test file can be deleted without `.vercelignore` noticing → deploy silently loses coverage.++## Build this+1. **Grow `GATE_TESTS`** to a production tier (~30–40 files) covering money path, core features, auth/access, and reliability. Coordinate with prompts 02–04 — they create the tests this gate will reference. Add only tests that are deterministic and offline-safe (no live DB/RPC/Redis).+2. **Lockstep `.vercelignore`**: write a single source of truth (e.g. the `GATE_TESTS` array) and have `.vercelignore` generated/validated from it. Add `scripts/test-gate.mjs --audit` that fails if a gate-listed file is missing OR a gate file isn't re-included in `.vercelignore`.+3. **Harden CI** (`.github/workflows`): on PR run `lint` (blocking), `typecheck` (blocking — flip from advisory), `vitest run`, and `test:gate`. On the deploy path, run `test:gate` as a required check. Cache npm + node_modules for speed.+4. **Flake detection**: add an opt-in CI job that re-runs the gate N times (e.g. 3×) nightly and reports any non-deterministic failures.+5. **Coverage visibility**: emit a one-line summary (files, assertions, duration) and a coverage delta comment is *not* required, but `npm run test:gate` must print exactly what it guards.++## Files likely in play+`scripts/test-gate.mjs`, `.vercelignore`, `.github/workflows/ci.yml` (+ a new nightly workflow), `package.json` (scripts), `jsconfig.json` / `tsconfig` if typecheck needs fixes to go blocking.++## Out of scope+Writing the endpoint tests themselves (that's prompts 02–04). Here you build the *gate machinery* and wire whichever tests already exist; leave TODO-free placeholders out — only reference tests that exist.++## Definition of done+- [ ] `npm run test:gate` runs the expanded set, green, and prints what it covers.+- [ ] `npm run test:gate -- --audit` fails loudly on gate/`.vercelignore` drift; passes now.+- [ ] CI blocks merge on lint + typecheck + vitest + gate; config committed.+- [ ] Typecheck is clean and blocking (fix real type errors; don't suppress).+- [ ] Nightly flake job committed.+- [ ] Changelog: infra-only → **no** changelog entry (internal).+- [ ] `git diff` reviewed; explicit paths staged.++## Guardrails+Follow CLAUDE.md. Don't weaken the gate to make it pass — fix the underlying test/type issues. Push both remotes when done.diff --git a/prompts/production-hardening/02-tests-payments-x402.md b/prompts/production-hardening/02-tests-payments-x402.mdnew file mode 100644index 000000000..2caac1b64--- /dev/null+++ b/prompts/production-hardening/02-tests-payments-x402.md@@ -0,0 +1,38 @@+# 02 · Test the money path (x402, settlement, payments)++> **Phase 0 — Test confidence** · **Depends on:** 01 (gate machinery) · **Parallel-safe:** yes · **Effort:** L++## Mission+Money endpoints are the highest-risk, least-tested surface: 4 of 5 x402 payment endpoints have+zero tests, and none are in the deploy gate. Write deterministic, offline-safe unit/integration+tests that lock down payment correctness — happy path **and** the failure modes that lose or+double-charge money — then add them to the gate (prompt 01).++## Context (read first)+- `CLAUDE.md` (note: **$THREE is the only coin**; use the real CA or a synthetic `THREEsynthetic…` placeholder in fixtures — never a real third-party mint).+- Payment surface: `api/x402-pay.js`, `api/x402-checkout.js`, `api/x402-checkout-record.js`, `api/x402-merchant.js`, `api/x402-status.js`.+- Libs: `api/_lib/x402-spec.js` (facilitator), `api/_lib/x402-solana-confirm.js` (static tx decode), `api/_lib/evm-payment-verify.js`, `api/_lib/x402/idempotency-cache.js`, `api/_lib/x402-bsc-direct.js`, `api/_lib/solana/connection.js` (RPC failover).+- Existing patterns: `tests/api/x402.test.js`, `tests/solana-confirm.test.js`, `tests/agent-custody-guards.test.js`. Match their style (route-layer fixtures, real `Transaction` objects, deterministic — not client rewrites).++## What to cover (write tests for)+1. **x402-pay prepare/confirm** — valid payment → 200 + correct credit; missing/invalid payment payload → 402 with proper `accepts`; underpaid amount → reject; wrong recipient → reject; wrong mint → reject.+2. **Settlement vs delivery** — assert the *intended* ordering and that a post-settlement failure is detectable (this test will tighten once prompt 10 lands; encode the expected contract now).+3. **Idempotency** — same payment signature submitted twice credits once (internal Solana path via `idempotency-cache.js`); checkout double-record blocked by the unique `(sku_id, tx_signature)` index (`x402-checkout-record.js`).+4. **Solana static decode** — `x402-solana-confirm.js`: a signed SPL-Token transfer is validated **without** RPC; malformed/short tx → reject; transfer to wrong owner → reject.+5. **EVM verify** — `evm-payment-verify.js`: correct Transfer event/amount/confirmations passes; spoofed/insufficient → reject.+6. **RPC failover** — `solana/connection.js`: provider rotation + cooldown behavior under simulated endpoint failure (mock at the transport boundary only, not the verification logic).+7. **x402-checkout ATA probe** — `ataExists()` failing open is *intentional + idempotent*; assert the extra create-ATA instruction is idempotent and amounts/recipients are unchanged.++## Files likely in play+`tests/api/x402-pay.test.js` (new), `tests/api/x402-checkout.test.js` (new — extend existing `tests/x402-checkout-prepare.test.js` if present), `tests/api/x402-settlement.test.js` (new), `tests/api/evm-payment-verify.test.js` (new), `tests/api/solana-rpc-failover.test.js` (new). Add the deterministic ones to `GATE_TESTS`.++## Definition of done+- [ ] New tests pass under `vitest run`; deterministic across 3 reruns.+- [ ] Money-path happy + failure cases covered per the list above.+- [ ] Deterministic tests added to `scripts/test-gate.mjs` + `.vercelignore` (re-run `--audit`).+- [ ] No real third-party token addresses in fixtures; $THREE CA or synthetic placeholders only.+- [ ] No mocks of the verification logic itself — only the network transport boundary.+- [ ] Changelog: internal test work → **no** entry.++## Guardrails+Follow CLAUDE.md. If a test reveals a real money bug, **note it clearly in your final summary** and (if quick + safe) fix it; otherwise the dedicated Phase-2 prompt will. Push both remotes.diff --git a/prompts/production-hardening/03-tests-forge-avatar.md b/prompts/production-hardening/03-tests-forge-avatar.mdnew file mode 100644index 000000000..72513afc0--- /dev/null+++ b/prompts/production-hardening/03-tests-forge-avatar.md@@ -0,0 +1,38 @@+# 03 · Test the product core (forge, avatar, auto-rig)++> **Phase 0 — Test confidence** · **Depends on:** 01 · **Parallel-safe:** yes · **Effort:** L++## Mission+The Forge (text/photo → 3D) and avatar creation/auto-rig pipeline are the product. Several forge+endpoints and core `src/` modules ship without dedicated tests. Lock down generation cost caps,+provider failover, asset delivery, the avatar create→rig path, and the bone-name canonicalization+that the whole animation system depends on.++## Context (read first)+- `CLAUDE.md` — note the **"avatar animation is universal — no rig allowlist"** rule and the canonicalization contract.+- Forge endpoints: `api/forge.js`, `api/forge-creation.js`, `api/forge-enhance.js`, `api/forge-gameready.js`, `api/forge-gallery.js`, and the engine lanes (nvidia/trellis/meshy/tripo/hunyuan3d/triposg).+- Store: `api/_lib/forge-store.js` (`listShowcase`, `listCreations`, `setPreview`).+- Avatar/animation: `src/glb-canonicalize.js` + `tests/glb-canonicalize.test.js` (extend), `src/animation-retarget.js`, `AnimationManager.supportsCanonicalClips()`, `api/avatars.js`, `api/avatar-render.js`, MCP `rig_mesh` / `forge_avatar` paths.+- Showcase client logic: `src/forge-showcase.js` (thumbnail fallback chain).++## What to cover (write tests for)+1. **Forge cost cap & gating** — generation respects the free/holder/paid tiers; a request over quota is rejected cleanly; $THREE-holder free lane works (server-verified).+2. **Provider failover** — when the primary engine lane errors, the chain falls back per the documented order and surfaces a real error if all fail (no fake success).+3. **Asset delivery & store** — `forge-store.listShowcase` ordering (preview-first, recency tiebreak), `done + glb_url` filter, `rejected` exclusion; `setPreview` only sets when null and only by the creating client.+4. **Gallery API** — `api/forge-gallery.js` scope=community vs client scope; `enabled:false` when store unconfigured; dedupe/limit behavior.+5. **GLB canonicalization** — extend `tests/glb-canonicalize.test.js` with every skeleton convention named in CLAUDE.md (Mixamo, Avaturn, Unreal, VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, Blender `.L`, simple `shoulderL`). A genuinely non-humanoid rig falls back to default (gate), never a T-pose.+6. **Avatar create→rig** — `api/avatars.js` POST validation + the auto-rig-on-create path; humanoid gate behavior.+7. **Showcase thumbnail fallback** — `src/forge-showcase.js`: Plan A/B/C/D selection logic given preview/glb presence (pure-logic assertions; DOM via jsdom).++## Files likely in play+`tests/api/forge-critical-path.test.js` (new), `tests/api/forge-gallery.test.js` (extend), `tests/glb-canonicalize.test.js` (extend), `tests/api/avatar-creation.test.js` (new), `tests/src/forge-showcase.test.js` (new). Add deterministic ones to the gate.++## Definition of done+- [ ] New/extended tests pass; deterministic across reruns.+- [ ] Every CLAUDE.md skeleton convention has a canonicalization test case.+- [ ] Cost cap, provider failover, and store ordering all asserted.+- [ ] Deterministic tests added to `GATE_TESTS` + `.vercelignore` (`--audit` clean).+- [ ] Changelog: internal → **no** entry.++## Guardrails+Follow CLAUDE.md. Use synthetic GLB fixtures or existing test assets — never fabricate "passing" generation results. If a test exposes a real pipeline bug, fix it or flag it explicitly. Push both remotes.diff --git a/prompts/production-hardening/04-e2e-critical-flows.md b/prompts/production-hardening/04-e2e-critical-flows.mdnew file mode 100644index 000000000..dfcb28e8f--- /dev/null+++ b/prompts/production-hardening/04-e2e-critical-flows.md@@ -0,0 +1,37 @@+# 04 · E2E coverage for critical user journeys++> **Phase 0 — Test confidence** · **Depends on:** 01 · **Parallel-safe:** yes · **Effort:** L++## Mission+Playwright today has ~10 specs with high fidelity but thin breadth, and 4 are quarantined+(`.skip`) because they need live DB/Redis/WebSocket. Cover the journeys that *make money or make+users stay* end-to-end, and unquarantine the skipped specs by giving them deterministic synthetic+backends instead of live dependencies.++## Context (read first)+- `CLAUDE.md`; `playwright.config.*`; `tests/e2e/*.spec.*`.+- Tested today: launch-token-flow, coin-buy-trade, create-agent-avatar, nav-auth.+- Quarantined (`.skip`): club (needs Redis), avatar-edit (needs WebSocket server), gallery-picker (needs live DB), galaxy (needs IBM agent discovery).+- Fidelity pattern in use: real Solana `Transaction` objects, real modal code, **route-layer** deterministic responses (not client rewrites). Keep that pattern.++## Build this+1. **New journeys** (add specs):+ - **Forge generation** — enter prompt → Generate (free lane) → model appears in viewer → download/share affordances work.+ - **x402 checkout → confirm → delivery** — full paid path with route-layer-deterministic payment + settlement; assert the artifact/credit is delivered.+ - **Avatar create → personalize → use** — create, edit, and land it somewhere it's consumed (profile/walk).+ - **Wallet connect → balance → gated action** — connect, read balance, attempt a $THREE-gated action.+2. **Unquarantine the 4 skips** by introducing deterministic fakes at the *infrastructure boundary only* (a synthetic Redis/WebSocket/DB stub the test owns) — never by mocking the product logic under test. If a flow truly cannot be made deterministic in CI, document precisely why in the spec and keep it in a separate `@manual` project, not silently skipped.+3. **CI wiring** — ensure `npm run test:e2e` runs the deterministic specs headless in CI; heavy/manual ones are a separate, non-blocking project.++## Files likely in play+`tests/e2e/forge-generate.spec.*` (new), `tests/e2e/x402-checkout.spec.*` (new), `tests/e2e/avatar-lifecycle.spec.*` (new), `tests/e2e/wallet-gating.spec.*` (new), the 4 quarantined specs, `playwright.config.*`, `.github/workflows`.++## Definition of done+- [ ] New specs pass headless, deterministically (3 reruns).+- [ ] Previously-skipped specs either run green with synthetic backends or are moved to a clearly-labeled `@manual` project with a documented reason (no silent `.skip`).+- [ ] `npm run test:e2e` green in CI config.+- [ ] No product logic mocked — only infra boundaries.+- [ ] Changelog: internal → **no** entry.++## Guardrails+Follow CLAUDE.md. Use the real CA or synthetic placeholders for any token in fixtures. Keep route-layer determinism; don't rewrite client code to make tests pass. Push both remotes.diff --git a/prompts/production-hardening/05-test-infra-load-chaos-a11y.md b/prompts/production-hardening/05-test-infra-load-chaos-a11y.mdnew file mode 100644index 000000000..5153fc0da--- /dev/null+++ b/prompts/production-hardening/05-test-infra-load-chaos-a11y.md@@ -0,0 +1,34 @@+# 05 · Load, chaos, a11y & visual-regression test infra++> **Phase 0 — Test confidence** · **Depends on:** 01–04 · **Parallel-safe:** yes · **Effort:** L++## Mission+A $1B platform proves it survives load, failure, and regressions — not just that the happy path+passes. Stand up the four test types the suite is missing today: **load/soak**, **chaos/resilience**,+**accessibility**, and **visual regression**. These run out-of-band (nightly / pre-GA), not on every PR.++## Context (read first)+- `CLAUDE.md`; existing partial perf tests (`tests/*club-perf*`, `*club-venue-load*`).+- Heaviest request paths: forge generation (300s `maxDuration` in `vercel.json`), x402-pay, agent create, avatar render.+- Dependencies already present you can lean on: `@playwright/test`, `fast-check` (property tests), `cockatiel` (for chaos injection of breakers).++## Build this+1. **Load/soak** — a script (`scripts/loadtest-*.mjs` or k6/autocannon if you add it as a devDep) that drives sustained RPS against forge-creation, x402-pay, and agent-create, recording p50/p95/p99 latency, error rate, and DB connection-pool behavior. Define target SLOs (e.g. p95 < Xs at N RPS) and fail the run if breached.+2. **Chaos/resilience** — tests that inject failure at boundaries (RPC down, DB timeout, Redis unavailable, payment facilitator slow) and assert graceful degradation, not 500 storms. Pair with Phase 1/5 work (breakers, fallbacks).+3. **Accessibility** — wire `@axe-core/playwright` (add devDep) into a Playwright project that scans the top ~15 pages and fails on serious/critical violations. This becomes the gate for prompt 21.+4. **Visual regression** — Playwright screenshot baselines for the top pages + key components (forge card, marketplace grid, dashboard). Tolerant diffing; baselines committed; a `--update-snapshots` path documented.+5. **Property tests** — use `fast-check` on at least the canonicalization / pricing / parsing logic where input space is large.++## Files likely in play+`scripts/loadtest-forge.mjs` / `loadtest-x402.mjs` (new), `tests/chaos/*.test.js` (new), `tests/a11y/axe.spec.*` (new), `tests/visual/*.spec.*` (new + baselines), `package.json` (new devDeps + `test:load`, `test:chaos`, `test:a11y`, `test:visual` scripts), nightly `.github/workflows`.++## Definition of done+- [ ] Each of the four suites runs locally and in a nightly CI job; documented in `tests/README.md`.+- [ ] Load run prints latency percentiles + error rate and enforces SLO thresholds.+- [ ] Chaos suite asserts degradation (no unhandled 500s) for RPC/DB/Redis/facilitator outages.+- [ ] axe suite is green on the top pages (or filed issues for what it flags → feeds prompt 21).+- [ ] Visual baselines committed; diff job runs in CI.+- [ ] Changelog: internal → **no** entry.++## Guardrails+Follow CLAUDE.md. Don't point load tests at production money endpoints with real funds — use a test/staging target or deterministic local server. Push both remotes.diff --git a/prompts/production-hardening/06-error-handling-sweep.md b/prompts/production-hardening/06-error-handling-sweep.mdnew file mode 100644index 000000000..80160bcc1--- /dev/null+++ b/prompts/production-hardening/06-error-handling-sweep.md@@ -0,0 +1,34 @@+# 06 · Eliminate silent failures (empty catch / fire-and-forget)++> **Phase 1 — Reliability** · **Depends on:** none (pairs with 26) · **Parallel-safe:** yes · **Effort:** M++## Mission+The audit found **138 files with empty catch blocks** and **70+ `.catch(() => {})` fire-and-forget**+chains across `api/`. Critical background work — receipt emails, payment cleanup, resource teardown,+cache invalidation — fails invisibly. CLAUDE.md forbids lazy error propagation. Replace silent+swallows with logged-and-alerted handling via a shared helper, so every failure is at least *seen*.++## Context (read first)+- `CLAUDE.md` hard rule #9 ("No errors without solutions"); errors handled at boundaries.+- Existing infra: `api/_lib/sentry.js` (`captureException`), `sendOpsAlert`, the `wrap()` boundary in `api/_lib/http.js` (used by ~512 handlers), `scripts/audit-empty-handlers.mjs` (`npm run audit:handlers`).+- Confirmed offenders: `api/agents.js:353,363` (`pingIndexNow().catch(()=>{})`), `api/forge.js:1315` (`releaseForgePayment().catch(()=>{})` — payment cleanup hidden), `api/payments/evm/[action].js:126` (receipt email loss), `api/pump-fun-mcp.js:518,577,606,612` (swallowed metadata/price/teardown), 16+ `Promise.all` that fail-whole on one rejection (`api/sitemap.js:57`).++## Build this+1. **A shared background-task helper** — e.g. `api/_lib/background.js` exporting `fireAndLog(promise, { op, context })` that awaits where appropriate or attaches a `.catch` that calls `captureException` + a debug log (and `sendOpsAlert` for the ones that matter: payments, emails, settlement cleanup). One canonical way to do "non-critical but observable."+2. **Sweep `api/`** replacing bare `catch {}` / `.catch(() => {})` with either: (a) real recovery, (b) `fireAndLog(...)`, or (c) a deliberate, commented `// best-effort: <why>` *only* where truly inconsequential. No silent swallow survives without justification.+3. **Fix fail-whole `Promise.all`** — convert to `Promise.allSettled` with sane per-item defaults where one failure shouldn't 500 the whole response (sitemap, home-stats, status, aggregations).+4. **Tighten `galaxy.js`-style `readJson().catch(() => ({}))`** that silently proceeds with empty input → validate or 400 (overlaps with prompt 07; do the obvious ones here).+5. **Extend `scripts/audit-empty-handlers.mjs`** to flag new bare empty catches / fire-and-forget without the helper, and add it to CI so the regression can't return.++## Files likely in play+`api/_lib/background.js` (new), the offender files above + the broader sweep across `api/`, `scripts/audit-empty-handlers.mjs`, `.github/workflows`.++## Definition of done+- [ ] `npm run audit:handlers` (extended) passes and is wired into CI.+- [ ] Every payment/email/settlement background task is observable (logged + alerted).+- [ ] No fail-whole `Promise.all` on multi-source read endpoints.+- [ ] Existing tests pass; add a small test for `fireAndLog` behavior.+- [ ] Changelog: mostly internal; if any user-visible reliability fix results (e.g. receipts that were silently dropping now send), add a **fix** entry.++## Guardrails+Follow CLAUDE.md. Don't introduce noisy logging in hot read paths — alert only on what matters. Stage explicit paths (large sweep across shared files; re-check `git status`). Push both remotes.diff --git a/prompts/production-hardening/07-fetch-guards-input-validation.md b/prompts/production-hardening/07-fetch-guards-input-validation.mdnew file mode 100644index 000000000..e9f7ed6cc--- /dev/null+++ b/prompts/production-hardening/07-fetch-guards-input-validation.md@@ -0,0 +1,34 @@+# 07 · Fetch `.ok` guards + universal input validation++> **Phase 1 — Reliability** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+Two systemic gaps from the audit: (1) **20+ `await res.json()` calls without a prior `if (!res.ok)`+guard** — an upstream 4xx/5xx throws a confusing `JSON.parse` error instead of a clean failure; and+(2) **public read endpoints trust raw query params** while POST bodies are well-validated with zod.+Close both so every external response and every inbound request is validated at the boundary.++## Context (read first)+- `CLAUDE.md` ("Errors handled at boundaries (network, user input)").+- Validation infra: `zod` (dependency), `api/_lib/validate.js` (existing schemas), `readJson(req)` helper.+- Confirmed unguarded fetches: `api/play-og.js:74`, `api/pump/curve.js:45`, `api/agent-wallet-bridge.js:126`.+- Confirmed weak param handling: `api/galaxy.js:179` (`readJson().catch(() => ({}))` → empty query proceeds), `api/explore-item.js:23` (`kind` unparsed), `api/play-og.js:199` (`coin` empty-string accepted).++## Build this+1. **A safe fetch-JSON helper** — `api/_lib/fetch-json.js` exporting something like `fetchJson(url, opts)` that: respects existing SSRF guards (`api/_lib/ssrf.js` / `guardedFetch`), checks `res.ok`, and throws a structured error with status + a snippet of the body on failure. Replace the raw `await res.json()` sites with it.+2. **Query/param validation** — add zod schemas for query params on read endpoints (mirror the POST-body pattern). Validate at entry; return a clean 400 on bad input; never let `undefined`/empty silently flow downstream.+3. **`readJson` fallback discipline** — anywhere `readJson().catch(() => ({}))` is used, validate the parsed body with a schema and 400 on failure instead of proceeding with an empty object.+4. **A lint guard** — add a check (ESLint rule or a `scripts/audit-*.mjs`) that flags `await <x>.json()` not preceded by an `.ok` check / not going through `fetchJson`, and `readJson(` without a nearby `.parse(`. Wire into CI so it can't regress.++## Files likely in play+`api/_lib/fetch-json.js` (new), the unguarded-fetch + weak-param files above, broader `api/` sweep, `api/_lib/validate.js` (new query schemas), `.eslintrc`/`scripts/audit-*.mjs`, `.github/workflows`.++## Definition of done+- [ ] No raw `await res.json()` without `.ok`/`fetchJson` in `api/`; lint guard enforces it.+- [ ] Read endpoints validate query params with zod and return clean 400s.+- [ ] No `readJson().catch(() => ({}))` proceeding on empty/invalid input.+- [ ] Tests: add cases for malformed input → 400 and upstream-error → structured failure.+- [ ] Changelog: internal hardening → **no** entry (unless a user-visible error message improves).++## Guardrails+Follow CLAUDE.md. Keep using `guardedFetch`/SSRF protections — do **not** route new fetches through `axios` (see prompt 15). Push both remotes.diff --git a/prompts/production-hardening/08-circuit-breakers-cockatiel.md b/prompts/production-hardening/08-circuit-breakers-cockatiel.mdnew file mode 100644index 000000000..ebe6f308f--- /dev/null+++ b/prompts/production-hardening/08-circuit-breakers-cockatiel.md@@ -0,0 +1,34 @@+# 08 · Unify circuit breakers on cockatiel++> **Phase 1 — Reliability** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+`cockatiel` is already a dependency (and a saved team preference — see memory "Prefer vetted OSS,+additive"), yet each subsystem reinvents its own ad-hoc cooldown/breaker logic (`api/feed-stream.js`+`breakerUntil` + 5-min cooldown, forge's own breaker, `solana/connection.js` per-provider cooldown).+Consolidate on a shared cockatiel-based resilience layer so external-dependency failures are handled+consistently and one flaky provider can't take down unrelated features.++## Context (read first)+- `CLAUDE.md`; memory note: adopt vetted OSS, **additive** — wrap new/unprotected call sites, don't rip out working code mid-flight.+- `cockatiel` docs (retry, circuit breaker, timeout, bulkhead, fallback policies).+- Existing ad-hoc breakers: `api/feed-stream.js`, the forge generation breaker, `api/_lib/solana/connection.js` (well-implemented failover — wrap, don't break it).++## Build this+1. **A shared resilience module** — `api/_lib/resilience.js` exposing named policies built on cockatiel: e.g. `rpcPolicy`, `facilitatorPolicy`, `upstreamApiPolicy`, each a composed retry + timeout + circuit-breaker (+ fallback) tuned per dependency class. Include a small in-memory breaker-state registry so health is inspectable.+2. **Adopt additively** — route currently-unprotected external calls (per prompt 07's `fetchJson`, LLM proxies, image fetches, facilitator calls) through the appropriate policy. Migrate the ad-hoc breakers to the shared one **only where it's a clean swap**; leave the solid `solana/connection.js` failover intact but expose its breaker state to the registry.+3. **Surface breaker state** — a tiny read path (used later by the status page, prompt 40) listing each breaker's open/half-open/closed state and last error.+4. **Tests** — cover open→half-open→closed transitions and fallback behavior (pairs with the chaos suite, prompt 05).++## Files likely in play+`api/_lib/resilience.js` (new), `api/feed-stream.js`, forge generation path, LLM/image proxy call sites, `api/_lib/x402-spec.js` (facilitator calls), `api/_lib/solana/connection.js` (registry hook), tests.++## Definition of done+- [ ] One shared cockatiel-based policy module; named policies per dependency class.+- [ ] Previously-unprotected external calls now wrapped; no behavior regressions.+- [ ] Breaker states inspectable via a single read path.+- [ ] Tests cover breaker transitions + fallbacks; chaos suite (05) exercises them.+- [ ] Changelog: internal reliability → **no** entry.++## Guardrails+Follow CLAUDE.md and the "additive" preference — don't refactor working failover into a regression. Keep timeouts conservative so you don't add latency to hot paths. Push both remotes.diff --git a/prompts/production-hardening/09-graceful-degradation.md b/prompts/production-hardening/09-graceful-degradation.mdnew file mode 100644index 000000000..2d508e48e--- /dev/null+++ b/prompts/production-hardening/09-graceful-degradation.md@@ -0,0 +1,34 @@+# 09 · Graceful degradation for auth & payments when deps are down++> **Phase 1 — Reliability** · **Depends on:** 08 (shared breakers) · **Parallel-safe:** yes · **Effort:** M++## Mission+The audit found critical paths with no explicit fallback: if the DB is down, **login 500s**; if+Upstash Redis is down, **every `/api/x402/*` endpoint exits with code 1** on cold start. Define and+implement deliberate degradation behavior for the paths users cannot live without — fail *safe and+legibly*, never with a raw 500 or a silent fail-open on money.++## Context (read first)+- `CLAUDE.md` hard rule #9.+- `api/healthz.js` (already catches DB errors → liveness fallback), `api/status.js` (warming-up state).+- Auth: `api/_lib/auth.js`, `csrf.js`. Payments: `api/_lib/x402/*`, Redis requirement (`@upstash/redis`, `@upstash/ratelimit`) — note USE-15: x402 exits on missing Redis.+- Resilience layer from prompt 08.++## Build this+1. **Auth degradation** — when the DB/session store is briefly unavailable: distinguish "can't verify → 503 with Retry-After + clear message" from a hard 500. Never grant access on failure. Consider a short read-through cache for session validation so transient blips don't log everyone out.+2. **Payments + Redis** — x402 needs Redis for idempotency; do **not** fail-open (that risks double-spend). Instead: fail-*closed* with a clean 503 and a precise operator message, and add a startup/health signal that flags missing Redis loudly (pairs with prompt 16). If a safe degraded mode exists (e.g. DB-backed idempotency fallback), implement it explicitly and test it.+3. **Standard degraded response** — a shared helper for 503 + `Retry-After` + structured body, used consistently so clients (and the status page) can react.+4. **Decision matrix** — document, in `docs/`, for each critical dependency (DB, Redis, RPC, facilitator, S3/R2): what degrades, how, and what the user sees. This is the contract the chaos suite (05) verifies.++## Files likely in play+`api/_lib/auth.js`, `api/_lib/x402/*`, `api/_lib/http.js` (503 helper), `api/healthz.js`/`status.js`, `docs/degradation-matrix.md` (new), tests + chaos cases.++## Definition of done+- [ ] DB-down → auth returns 503 w/ Retry-After (not 500); never fail-open.+- [ ] Redis-down → x402 fails closed cleanly (or a tested DB-backed fallback), never silent-exit or double-spend.+- [ ] Degradation matrix doc committed; chaos suite asserts each row.+- [ ] Tests pass; no fail-open on money paths.+- [ ] Changelog: if users now see a clean "temporarily unavailable" instead of a broken page → **fix** entry.++## Guardrails+Follow CLAUDE.md. **Fail-closed on anything touching money or access.** Push both remotes.diff --git a/prompts/production-hardening/10-settlement-delivery-refund.md b/prompts/production-hardening/10-settlement-delivery-refund.mdnew file mode 100644index 000000000..112ba519a--- /dev/null+++ b/prompts/production-hardening/10-settlement-delivery-refund.md@@ -0,0 +1,36 @@+# 10 · Settlement↔delivery atomicity + refund path++> **Phase 2 — Money safety** · **Depends on:** 02 (tests), 14 (ledger — can land together) · **Parallel-safe:** no (core money logic) · **Effort:** L++## Mission+**Highest-priority money bug.** In `api/x402-pay.js`, settlement happens *after* MCP dispatch: if a+tool executes but fails before returning a result, the **payment is confirmed but no service is+delivered**, and there is **no refund path**. At volume this is unreconciled customer loss. Make+pay→deliver atomic-enough that every confirmed payment either delivers or refunds, and every+exception is recorded for reconciliation.++## Context (read first)+- `CLAUDE.md` ($THREE only; no shortcuts on money).+- `api/x402-pay.js` (~lines 790–832 settle-vs-dispatch ordering; lines 541–680 `runExternalFlow`).+- `api/_lib/x402-spec.js` (`settlePayment`, facilitator), `api/_lib/x402/idempotency-cache.js`.+- Reconciliation ledger from prompt 14 (build the table contract together if running them in sequence).++## Build this+1. **Order of operations** — settle only after the deliverable is secured, OR capture-then-settle: verify payment authorization → execute/deliver → settle. Where the deliverable can fail after an irreversible settlement, you MUST have a refund.+2. **Refund path** — implement `refundPayment(...)` for each rail (Solana SPL transfer back; EVM/BSC equivalent) that returns funds to the payer and records the refund. Trigger it automatically when delivery fails after settlement.+3. **Failed-delivery record** — write every "paid but not delivered (yet)" event to a durable table (`x402_failed_deliveries`: tx, sku, payer, amount, reason, refunded_at). This is the source of truth for ops + the ledger (prompt 14).+4. **Idempotent retries** — a delivery that times out but later succeeds must not double-charge or double-deliver; reconcile via the idempotency cache + the failed-delivery table.+5. **Tests** — simulate: dispatch throws after settle → refund issued + recorded; refund itself fails → flagged for manual reconciliation + alert; happy path unaffected. Add to gate.++## Files likely in play+`api/x402-pay.js`, `api/_lib/x402-spec.js`, `api/_lib/x402/refund.js` (new), `api/_lib/migrations/*_x402_failed_deliveries.sql` (new), `api/_lib/x402/idempotency-cache.js`, tests.++## Definition of done+- [ ] Every confirmed payment provably delivers or refunds; no settle-then-silently-fail path remains.+- [ ] `x402_failed_deliveries` table + migration; populated on failure, cleared on refund/redelivery.+- [ ] Refund implemented and tested per rail; refund failure alerts (via prompt 06 helper).+- [ ] Tests cover the loss scenario + idempotent retry; added to `GATE_TESTS`.+- [ ] Changelog: **fix** entry (user-visible trust: "payments that don't deliver are now auto-refunded").++## Guardrails+Follow CLAUDE.md. This is real money — be conservative, fail-closed, and over-record. Use $THREE CA or synthetic placeholders in tests. Push both remotes.diff --git a/prompts/production-hardening/11-x402-external-idempotency.md b/prompts/production-hardening/11-x402-external-idempotency.mdnew file mode 100644index 000000000..a6f07f74b--- /dev/null+++ b/prompts/production-hardening/11-x402-external-idempotency.md@@ -0,0 +1,34 @@+# 11 · Idempotency for external x402 flows++> **Phase 2 — Money safety** · **Depends on:** 10 · **Parallel-safe:** no (money logic) · **Effort:** M++## Mission+The internal Solana flow uses an idempotency cache, but `runExternalFlow` in `api/x402-pay.js`+**bypasses it entirely**. A network timeout mid-response on an external paid call can cause a+**double-charge** on retry. Bring external x402 flows under the same idempotency guarantee.++## Context (read first)+- `CLAUDE.md`.+- `api/x402-pay.js` `runExternalFlow` (~lines 541–680; the code already logs "status could not be confirmed" ~617–621 but offers no replay protection).+- `api/_lib/x402/idempotency-cache.js` (the existing internal guard — generalize it).+- Redis requirement + the fail-closed posture from prompt 09.++## Build this+1. **Idempotency key for external flows** — derive a stable key (payer + payTo + amount + asset + request fingerprint, or an explicit client-supplied `Idempotency-Key`). Before signing/sending, check the cache; on a confirmed prior result, return it instead of re-paying.+2. **Two-phase record** — mark "in-flight" before send, "settled"/"failed" after. A retry that finds "in-flight" must not re-send; it reconciles (poll/confirm) the original.+3. **Confirmation-after-timeout** — when send times out, attempt to confirm the original on-chain/with the facilitator before ever retrying; only retry if provably not landed.+4. **Generalize the cache** — refactor `idempotency-cache.js` so both internal and external flows share one implementation and one store (Redis-backed, with the prompt-09 fail-closed behavior).+5. **Tests** — same key twice → one charge; timeout-then-retry → reconcile, not double-send; concurrent duplicate requests → one settles. Add to gate.++## Files likely in play+`api/x402-pay.js`, `api/_lib/x402/idempotency-cache.js`, `api/_lib/x402/refund.js` (from prompt 10, for reconciliation), tests.++## Definition of done+- [ ] `runExternalFlow` is idempotent; duplicate/retried external payments charge exactly once.+- [ ] Timeout path reconciles before any retry; no blind re-send.+- [ ] One shared idempotency implementation for internal + external.+- [ ] Tests cover duplicate, timeout-retry, and concurrent-duplicate; added to `GATE_TESTS`.+- [ ] Changelog: **fix** entry (trust: "no more double-charges on flaky networks").++## Guardrails+Follow CLAUDE.md. Fail-closed if the idempotency store is unavailable (don't pay without it). $THREE/synthetic only in fixtures. Push both remotes.diff --git a/prompts/production-hardening/12-agent-spend-policy.md b/prompts/production-hardening/12-agent-spend-policy.mdnew file mode 100644index 000000000..c14997fdc--- /dev/null+++ b/prompts/production-hardening/12-agent-spend-policy.md@@ -0,0 +1,35 @@+# 12 · Enforce agent spend policy (no silent platform-wallet fallback)++> **Phase 2 — Money safety** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+In `api/x402-pay.js`, `resolvePayerRouting` **warns but allows** a fallback to the shared platform+wallet (`X402_AGENT_SOLANA_SECRET_BASE58`) when a call is missing `agentId` — bypassing per-agent+spend policy. A regression that drops `agentId` would spend platform funds *unmetered* until someone+reads the logs. Make the policy enforced, not advisory, and add a hard daily ceiling as a backstop.++## Context (read first)+- `CLAUDE.md`.+- `api/x402-pay.js` (~lines 1084–1106 `resolvePayerRouting`; line ~1100 `log.warn('platform_wallet_fallback')`).+- Spend policy + guards: `api/_lib/agent-spend-policy.js`, `agent-custody-guards.js`, `agent-trade-guards.js` (and `tests/agent-custody-guards.test.js`).++## Build this+1. **Reject, don't warn** — an agent payment call missing `agentId` (or with an `agentId` that can't be resolved to a funded, policy-bound wallet) returns **403** with a clear error. The shared platform wallet is used only for explicitly platform-initiated operations, never as an implicit fallback for agent calls.+2. **Per-agent caps enforced server-side** — ensure every spend path runs through `agent-spend-policy` (per-tx + rolling daily/period caps). No code path spends agent funds without a policy check.+3. **Global backstop** — a per-SKU and per-wallet daily ceiling (config-driven) that halts runaway spend from a bug even if per-agent policy is somehow bypassed; breach → block + ops alert (prompt 06 helper).+4. **Audit trail** — record every spend decision (allowed/blocked + reason) for reconciliation (prompt 14).+5. **Tests** — missing `agentId` → 403; over-cap → blocked; platform op still works; daily ceiling halts a simulated runaway. Add to gate.++## Files likely in play+`api/x402-pay.js`, `api/_lib/agent-spend-policy.js`, `api/_lib/agent-custody-guards.js`, config for ceilings, tests.++## Definition of done+- [ ] No silent platform-wallet fallback; missing/unresolvable `agentId` → 403.+- [ ] Every agent spend passes a server-side policy check.+- [ ] Global per-SKU/per-wallet daily ceiling enforced; breach alerts.+- [ ] Spend decisions recorded for audit.+- [ ] Tests cover all four; added to `GATE_TESTS`.+- [ ] Changelog: internal money-safety → optional **security**/**fix** entry if user-observable.++## Guardrails+Follow CLAUDE.md. Fail-closed. Don't loosen guards to make a flow work — fix the caller to pass `agentId`. Push both remotes.diff --git a/prompts/production-hardening/13-three-gate-fail-closed.md b/prompts/production-hardening/13-three-gate-fail-closed.mdnew file mode 100644index 000000000..605c78a7a--- /dev/null+++ b/prompts/production-hardening/13-three-gate-fail-closed.md@@ -0,0 +1,36 @@+# 13 · $THREE gating: fail-closed + tier caching++> **Phase 2 — Money safety** · **Depends on:** 08 (breakers) · **Parallel-safe:** yes · **Effort:** M++## Mission+$THREE holder gating is server-verified (good), but `api/_lib/three-access.js` **degrades to the+Member tier on any RPC failure** ("never throws — degrades to the Member floor"). When RPC is+flaky, gated benefits leak to non-holders. Decide and implement the correct posture: cache verified+tiers so transient RPC blips don't drop real holders, and fail-*closed* (not open) for paid/elevated+gates while keeping a graceful experience for read-only surfaces.++## Context (read first)+- `CLAUDE.md` — **$THREE is the only coin**, CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.+- `api/_lib/three-gate.js` (`checkThreeBalance`), `api/_lib/three-access.js` (~lines 165–174 fail-open degrade), `public/x402.js` (~213–231 client balance reads — display only, never authority).+- Memory: "Solana is the platform-wide default network."+- RPC failover (`api/_lib/solana/connection.js`) + resilience layer (prompt 08).++## Build this+1. **Tier cache** — cache a wallet's verified $THREE tier (Redis, TTL ~1h with jittered refresh) so a momentary RPC failure reuses the last *known-good* tier instead of dropping to Member. Cache only *successful* reads.+2. **Fail-closed for elevation** — for anything that grants paid features, free generation beyond the public allotment, or spend benefits: on an uncached RPC failure, **deny the elevated grant** (treat as unverified) rather than silently granting Member-or-above benefits that cost money. Make the distinction explicit in `three-access.js`.+3. **Graceful read surfaces** — purely cosmetic/read-only gating may degrade softly, but must not unlock anything monetizable.+4. **Client is never authority** — confirm `public/x402.js` balance reads are display-only and every grant is server-checked. Remove any path where the client value influences access.+5. **Tests** — RPC down + warm cache → real tier preserved; RPC down + cold cache → elevated denied, read-only soft-degrades; client-supplied balance never elevates. Add to gate.++## Files likely in play+`api/_lib/three-access.js`, `api/_lib/three-gate.js`, tier cache module (Redis), `public/x402.js` (audit), tests.++## Definition of done+- [ ] Verified tiers cached; transient RPC failures don't drop real holders.+- [ ] Elevated/monetizable grants fail-closed on uncached RPC failure.+- [ ] No client-supplied balance can elevate access.+- [ ] Tests cover warm-cache, cold-cache, and client-spoof cases; added to `GATE_TESTS`.+- [ ] Changelog: **security**/**fix** entry ("$THREE benefits no longer leak during RPC hiccups").++## Guardrails+Follow CLAUDE.md. $THREE is the only coin — never reference another token in code, tests, or copy. Fail-closed on money. Push both remotes.diff --git a/prompts/production-hardening/14-payment-reconciliation.md b/prompts/production-hardening/14-payment-reconciliation.mdnew file mode 100644index 000000000..3d0d47f5f--- /dev/null+++ b/prompts/production-hardening/14-payment-reconciliation.md@@ -0,0 +1,36 @@+# 14 · Payment reconciliation ledger + ops alerts++> **Phase 2 — Money safety** · **Depends on:** 10, 12 (share the table contracts) · **Parallel-safe:** yes · **Effort:** L++## Mission+There is **no reconciliation** between on-chain payment state and the DB, no refund audit, and no+early-warning on repeated settlement failures. A $1B platform must be able to answer, at any moment:+"who paid, what did they get, what's owed, and what's stuck?" Build a durable payment ledger plus a+reconciliation job and fraud/anomaly alerts.++## Context (read first)+- `CLAUDE.md`.+- Payment write paths: `api/x402-pay.js`, `api/x402-checkout-record.js` (unique `(sku_id, tx_signature)`), `api/_lib/x402-spec.js`, `api/_lib/x402-bsc-direct.js` (replay guard), `api/pump/[action].js`.+- Metrics sink already present: `api/_lib/axiom.js` (payment metrics). Ops alerts: `sendOpsAlert` + prompt 06 helper.+- The `x402_failed_deliveries` table from prompt 10.++## Build this+1. **Unified ledger** — a `payments_ledger` table capturing every money event (charge, settle, refund, failed-delivery, payout) with: rail, payer, payTo, amount, asset, tx ref, sku/agent, status, timestamps. All payment paths write to it (single helper, not scattered inserts).+2. **Reconciliation job** — a cron/worker that compares ledger entries to on-chain/facilitator truth: flags settled-but-not-delivered, delivered-but-not-settled, refunds owed, and orphaned txs. Emits a daily reconciliation report.+3. **Anomaly alerts** — real-time alert on: repeated settlement failures from one payer (fraud signal), refund spikes, daily-ceiling breaches (prompt 12), and any ledger row stuck > N minutes.+4. **Ops surface** — a minimal authenticated read (admin-gated, see `requireAdmin`) that lists open/stuck items for manual resolution; feeds the status/ops view.+5. **Tests** — ledger writes on each event; reconciliation correctly flags each mismatch class; alert fires on the fraud pattern.++## Files likely in play+`api/_lib/payments-ledger.js` (new), `api/_lib/migrations/*_payments_ledger.sql` (new), a reconciliation worker/cron (`workers/` or a scheduled function), `api/_lib/axiom.js` (metric hooks), admin read endpoint, tests.++## Definition of done+- [ ] Every money event writes to one ledger via one helper.+- [ ] Reconciliation job flags all mismatch classes + emits a daily report.+- [ ] Anomaly alerts wired (fraud, refund spike, stuck rows, ceiling breach).+- [ ] Admin-gated ops read of open items.+- [ ] Tests cover writes, reconciliation, and an alert path.+- [ ] Changelog: internal/ops → **no** entry (unless an admin-visible page is added → **feature**).++## Guardrails+Follow CLAUDE.md. Admin endpoints must use `requireAdmin`. $THREE/synthetic only in fixtures. Don't log full secrets/keys in the ledger. Push both remotes.diff --git a/prompts/production-hardening/15-dependency-vuln-remediation.md b/prompts/production-hardening/15-dependency-vuln-remediation.mdnew file mode 100644index 000000000..37ae4942f--- /dev/null+++ b/prompts/production-hardening/15-dependency-vuln-remediation.md@@ -0,0 +1,34 @@+# 15 · Remediate vulnerable dependencies (axios et al.)++> **Phase 3 — Security** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+`npm audit` surfaces high-severity issues — most notably **axios** (multiple CVEs incl. SSRF bypass,+prototype pollution, credential leakage). Given this codebase fetches user-supplied/remote URLs in+several paths, a vulnerable HTTP client is a direct SSRF/abuse risk *even with* the custom SSRF guard.+Patch or eliminate the risky deps and put a recurring audit in CI so they can't creep back.++## Context (read first)+- `CLAUDE.md`; memory: "Prefer vetted OSS, additive."+- SSRF defense: `api/_lib/ssrf.js` / `guardedFetch` (DNS-pin, private-IP blocklist) — the source of truth; native `fetch`/`undici` go through it.+- Flagged by audit: `axios` (14+ CVEs), `@opentelemetry/core` (<2.8.0 unbounded memory), `@libp2p/kad-dht` (<16.2.6 disk exhaustion, via helia), `@ai-sdk/provider-utils` (via `qwen-ai-provider`, no fix).++## Build this+1. **Inventory** — run `npm audit` (and `npm ls axios` etc.) and list exactly where each flagged dep is used, transitive vs direct.+2. **axios** — upgrade to the latest patched line; better, **migrate first-party axios usage to `guardedFetch`/native fetch** so all outbound HTTP goes through the SSRF guard. Where a transitive dep pins old axios, override via `package.json` `overrides`.+3. **Other flagged deps** — bump `@opentelemetry/core` ≥2.8.0 and `@libp2p/kad-dht`/`helia` to patched versions (via `overrides` if transitive). For `qwen-ai-provider` (no fix): assess whether it's actually used; if not, remove it; if yes, sandbox/limit its exposure and document the residual risk.+4. **CI guard** — add `npm audit --audit-level=high` (or `better-npm-audit` with a tracked allowlist for accepted/unfixable items) to CI; document any accepted exceptions with rationale + review date.+5. **Verify** — full test suite + `npm run build` succeed after upgrades; no runtime regressions in payment/forge/image-fetch paths.++## Files likely in play+`package.json` (deps + `overrides`), `package-lock.json`, first-party axios call sites → `guardedFetch`, `.github/workflows`, a short `docs/security/dependency-policy.md`.++## Definition of done+- [ ] `npm audit --audit-level=high` clean (or every remaining item explicitly accepted + documented).+- [ ] No first-party outbound HTTP bypasses the SSRF guard.+- [ ] CI fails on new high/critical advisories.+- [ ] Full test suite + build green post-upgrade.+- [ ] Changelog: **security** entry ("hardened dependencies / patched known vulnerabilities").++## Guardrails+Follow CLAUDE.md. Don't blanket-bump majors blindly — verify each upgrade against the suite. Keep the lockfile consistent (the repo uses workspaces; mind `npm ci`). Push both remotes.diff --git a/prompts/production-hardening/16-secrets-startup-validation.md b/prompts/production-hardening/16-secrets-startup-validation.mdnew file mode 100644index 000000000..9a73d4700--- /dev/null+++ b/prompts/production-hardening/16-secrets-startup-validation.md@@ -0,0 +1,35 @@+# 16 · Startup secret validation + key-rotation safety++> **Phase 3 — Security** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+`.env.example` documents 90–100+ secrets, but nothing validates them at boot. Worst case from the+audit: when `WALLET_ENCRYPTION_KEY` is unset it **falls back to `JWT_SECRET`** — so a `JWT_SECRET`+compromise = all custodial wallets compromised. And a missing `UPSTASH_*`/`JWT_SECRET` fails late,+mid-request. Add a fail-fast config validator and make key rotation safe by construction.++## Context (read first)+- `CLAUDE.md`.+- `.env.example` (the full required-vars list — treat as the schema source).+- `api/_lib/agent-wallet.js` (the WALLET_ENCRYPTION_KEY→JWT_SECRET fallback), `api/_lib/sentry.js` (silently null on bad DSN), Redis requirement (USE-15).+- Key-rotation notes already in `.env.example` (append-to-keyset, never remove mid-rotation).++## Build this+1. **Config schema** — a zod (or equivalent) schema in `api/_lib/config.js` describing every env var: name, required-in-prod?, format, and grouping (db, redis, payments, llm, storage, observability, naming). One typed accessor used everywhere instead of raw `process.env`.+2. **Fail-fast validation** — a startup/health check that, in production, **refuses to serve** (or loudly fails health) if any *critical* secret (`DATABASE_URL`, `JWT_SECRET`, `WALLET_ENCRYPTION_KEY`, x402 facilitator keys, `UPSTASH_*`) is unset/malformed. Non-critical missing vars degrade the related feature with a clear log, not a crash.+3. **Kill the dangerous fallback** — `WALLET_ENCRYPTION_KEY` must be **required and distinct** from `JWT_SECRET` in prod; the implicit fallback is removed (or hard-errors) in production. Document the migration for any existing data encrypted under the old key.+4. **Rotation safety** — support a key *set* (current + previous) for `JWT_SECRET` and `WALLET_ENCRYPTION_KEY` so rotation never breaks live sessions/wallets; add a tiny tool/check that warns if a key in active use is about to be removed.+5. **Tests** — missing critical secret → health fails; malformed value → rejected; wallet encryption refuses JWT_SECRET fallback in prod; rotation keyset decrypts old + new.++## Files likely in play+`api/_lib/config.js` (new), `api/healthz.js`/`status.js` (surface validation), `api/_lib/agent-wallet.js`, `.env.example` (annotate critical vs optional), tests, `docs/security/secrets.md`.++## Definition of done+- [ ] One typed config accessor; raw `process.env` reads removed from app code (or minimized + justified).+- [ ] Prod fails fast on any missing critical secret; non-critical degrade cleanly.+- [ ] `WALLET_ENCRYPTION_KEY` required + distinct in prod; JWT_SECRET fallback gone.+- [ ] Key-set rotation supported + documented; tests cover old+new decrypt.+- [ ] Changelog: **security** entry.++## Guardrails+Follow CLAUDE.md. Never print secret values in logs or errors. Coordinate with prompt 09 (Redis fail-closed). Push both remotes.diff --git a/prompts/production-hardening/17-rate-limit-coverage.md b/prompts/production-hardening/17-rate-limit-coverage.mdnew file mode 100644index 000000000..26efb2324--- /dev/null+++ b/prompts/production-hardening/17-rate-limit-coverage.md@@ -0,0 +1,36 @@+# 17 · Rate-limit coverage audit across all endpoints++> **Phase 3 — Security** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+Rate limiting exists and is well-built (`api/_lib/rate-limit.js`, Upstash sliding window, fails+closed in prod), but there's **no audit that every abuse-prone endpoint actually applies it**. A+single unlimited generation/mint/payment endpoint is a cost-and-abuse hole. Produce a coverage map,+close the gaps, and add a guard that flags any new endpoint shipping without an explicit limit decision.++## Context (read first)+- `CLAUDE.md`.+- `api/_lib/rate-limit.js` (`limits.*`, `clientIp`), `api/_lib/http.js` (`rateLimited`).+- Known-covered: paid `x402/*`, forge (global breaker), payments. Unmapped: many read endpoints (some intentionally).+- All ~100 handlers live in `api/`.++## Build this+1. **Coverage map** — a script (`scripts/audit-rate-limits.mjs`) that statically lists every endpoint and whether it calls a limiter, classifying each as: money/settlement, generation/compute, mint/launch, auth, write, or read. Output a table.+2. **Close gaps** — add appropriate buckets to any abuse-prone endpoint missing one: generation/compute (cost), mint/launch (`api/pump/*`), auth (brute-force), and write endpoints. Tune limits per class (per-IP and, where applicable, per-wallet/per-agent).+3. **Explicit opt-out** — endpoints that *intentionally* skip limiting (public caches, health) must declare it (a marker/comment the audit recognizes) so "no limit" is always a decision, never an oversight.+4. **CI guard** — the audit script fails CI if any non-opted-out endpoint lacks a limiter.+5. **Tests** — representative endpoints return 429 with correct headers past threshold; opted-out ones don't; limiter fails closed when Redis is down (coordinate with prompt 09).++## Files likely in play+`scripts/audit-rate-limits.mjs` (new), gap endpoints across `api/`, `api/_lib/rate-limit.js` (new buckets if needed), `.github/workflows`, tests.++## Definition of done+- [ ] Coverage map generated; every endpoint classified.+- [ ] All abuse-prone endpoints rate-limited with class-appropriate buckets.+- [ ] Intentional opt-outs explicitly marked.+- [ ] CI fails on an unmarked, unlimited endpoint.+- [ ] Tests cover 429 behavior + fail-closed.+- [ ] Changelog: **security** entry if user-observable (e.g. clearer 429s), else internal.++## Guardrails+Follow CLAUDE.md. Don't rate-limit so aggressively that legitimate agent traffic breaks — tune per class. Push both remotes.diff --git a/prompts/production-hardening/18-csp-security-headers.md b/prompts/production-hardening/18-csp-security-headers.mdnew file mode 100644index 000000000..e7b882cf5--- /dev/null+++ b/prompts/production-hardening/18-csp-security-headers.md@@ -0,0 +1,35 @@+# 18 · Global CSP + security headers++> **Phase 3 — Security** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+Baseline security headers are set (`x-content-type-options`, `x-frame-options: DENY`,+`referrer-policy`), but **Content-Security-Policy appears only on `artifact.js`, not globally**. For+a platform handling wallets and payments, a site-wide CSP (plus the rest of the modern header set)+is table stakes against XSS and clickjacking. Roll out a strict, tested CSP everywhere without+breaking the 3D viewers, wallet adapters, or embeds.++## Context (read first)+- `CLAUDE.md`.+- `api/_lib/http.js` (header helpers; current CORS + base headers ~lines 236–290), `api/artifact.js` (has a CSP line — generalize it), `vercel.json` (static asset headers).+- Third-party surfaces that must keep working: `model-viewer`, Three.js (WASM/workers), Solana/EVM wallet adapters, livekit/colyseus, `@vercel/og`, embed scripts, the chat app.++## Build this+1. **Inventory sources** — enumerate what pages legitimately load (scripts, styles, fonts, images, `connect-src` for RPC/API/facilitator/CDN, `worker-src`/`wasm-unsafe-eval` for Three.js, `frame-src` for embeds).+2. **Author a strict CSP** — default-deny, explicit allowlists, `frame-ancestors` to control embedding (the SDK embeds need framing — scope it, don't blanket-allow). Avoid `unsafe-inline` for scripts; use nonces/hashes for any inline. Set `object-src 'none'`, `base-uri 'self'`.+3. **Apply globally** — both dynamic responses (`api/_lib/http.js` for HTML) and static assets (`vercel.json` headers), with per-surface overrides where embeds need looser `frame-ancestors`.+4. **Round out headers** — `Strict-Transport-Security`, `Permissions-Policy` (lock down camera/mic/geo except where the selfie/AR features need them), `Cross-Origin-Opener-Policy`/`-Resource-Policy` as compatible.+5. **Report-only first** — ship `Content-Security-Policy-Report-Only` with a report sink, verify zero legit breakage across the top pages + viewers + wallet flows, then flip to enforcing. Add a Playwright check that the top pages load with no CSP violations.++## Files likely in play+`api/_lib/http.js`, `vercel.json`, `api/artifact.js` (consolidate), a CSP source-of-truth module, a CSP-violation report endpoint, Playwright check.++## Definition of done+- [ ] Strict CSP enforced site-wide; embeds/viewers/wallet flows verified working.+- [ ] Full modern header set present on HTML + static responses.+- [ ] Report-only soak done; zero legit violations before enforcing.+- [ ] Playwright asserts no CSP violations on the top pages.+- [ ] Changelog: **security** entry.++## Guardrails+Follow CLAUDE.md. Test 3D viewers, wallet connect, and embeds explicitly — these break first under CSP. Don't weaken to `unsafe-inline` to "make it work"; use nonces. Push both remotes.diff --git a/prompts/production-hardening/19-security-review-pentest.md b/prompts/production-hardening/19-security-review-pentest.mdnew file mode 100644index 000000000..cd2e95036--- /dev/null+++ b/prompts/production-hardening/19-security-review-pentest.md@@ -0,0 +1,35 @@+# 19 · Pre-launch security review & pentest prep++> **Phase 3 — Security** · **Depends on:** 15–18 · **Parallel-safe:** yes · **Effort:** L++## Mission+Tie off Phase 3 with a structured, documented security review of the whole platform and prepare the+artifacts an external pentest/audit firm will need. A $1B platform must be able to *show* its security+posture, not just claim it. This prompt is authorized defensive review of the team's own code.++## Context (read first)+- `CLAUDE.md`; the `/security-review` skill (run it on the current diff/branch).+- Prior findings to confirm-fixed: axios/deps (15), secret validation (16), rate limits (17), CSP (18), $THREE fail-closed (13), spend policy (12), idempotency (10/11).+- Strong-already areas to verify still hold: parametrized SQL (`api/_lib/db.js`), SSRF guard (`api/_lib/ssrf.js`), admin gating (`requireAdmin`), CSRF (`api/_lib/csrf.js`), CORS allowlist (`api/_lib/http.js`).++## Build this+1. **Run the security-review skill** across the branch and triage every finding (fix or formally accept with rationale).+2. **Threat model doc** — `docs/security/threat-model.md`: trust boundaries, assets (custodial keys, payments, user data, $THREE gating), attacker profiles, and the mitigations for each (STRIDE-style is fine). Cover the wallet custody model explicitly.+3. **Auth/authorization matrix** — table of every endpoint × required auth/role; verify against code (catches missing `requireAdmin`/auth). Generate it from a script so it stays current.+4. **Secrets & key management doc** — how secrets are stored, rotated (prompt 16), and what the blast radius of each compromise is.+5. **Pentest readiness pack** — scope doc, test accounts/env, architecture diagram, known-accepted risks, and a responsible-disclosure / `security.txt` (`/.well-known/security.txt`) with a contact.+6. **Dependency & SBOM** — generate an SBOM (e.g. `npm sbom` / CycloneDX) and commit the policy for keeping it fresh.++## Files likely in play+`docs/security/threat-model.md`, `docs/security/auth-matrix.md` (+ generator script), `docs/security/secrets.md` (from 16), `public/.well-known/security.txt`, SBOM output + script, fixes for any review findings.++## Definition of done+- [ ] security-review skill run; all findings fixed or documented-accepted.+- [ ] Threat model + auth matrix + secrets docs committed; auth matrix is script-generated.+- [ ] `security.txt` published with a disclosure contact.+- [ ] SBOM generated + refresh policy documented.+- [ ] Zero open criticals/highs (or each explicitly risk-accepted with an owner + date).+- [ ] Changelog: **security** entry ("completed pre-launch security review").++## Guardrails+Follow CLAUDE.md. Report only — do not build exploit tooling. Don't paste real secrets into docs. Push both remotes.diff --git a/prompts/production-hardening/20-state-kit-unification.md b/prompts/production-hardening/20-state-kit-unification.mdnew file mode 100644index 000000000..669aa7940--- /dev/null+++ b/prompts/production-hardening/20-state-kit-unification.md@@ -0,0 +1,37 @@+# 20 · Unify every list/feed on the shared state-kit++> **Phase 4 — Frontend excellence** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M++## Mission+CLAUDE.md mandates that *every* state is designed (loading/empty/error/populated/overflow). The audit+found only ~⅓ of major list surfaces use the shared `src/shared/state-kit.js`; others either+re-implement states ad-hoc (`launches.js`, `radar.js`, `oracle.js`) or have **no states at all**+(`/activity`, `/coin-intel`, `/trending`, `/feed`, `/animations`, gallery picker). Make state-kit the+single, mandatory path so no surface ever shows a blank void or a bare spinner.++## Context (read first)+- `CLAUDE.md` UI/UX standards + Definition of Done.+- `src/shared/state-kit.js` (`skeletonHTML`, `emptyStateHTML`, `errorStateHTML`, `ensureStateKitStyles`).+- Compliant examples to mirror: `src/forge-showcase.js`, marketplace, agent-detail, dashboard-next pages.+- Non-compliant: `/activity`, `/coin-intel`, `/trending`, `/feed`, `/animations`, `gallery-picker`; ad-hoc: `launches.js`, `radar.js`, `oracle.js`.++## Build this+1. **Migrate the ad-hoc surfaces** (`launches.js`, `radar.js`, `oracle.js`) to state-kit so empty/error/loading look consistent platform-wide; delete the bespoke `renderEmpty/renderError` duplicates.+2. **Add states to the bare surfaces** (`/activity`, `/coin-intel`, `/trending`, `/feed`, `/animations`, gallery picker): skeleton on load, helpful empty state (tells the user what to do next + a CTA), actionable error state (what failed + a retry).+3. **Overflow/long-content states** — long names, huge counts, 0 vs 1 vs 1000 items all render gracefully (truncation, pagination hooks).+4. **Make it enforceable** — a lightweight contract (e.g. every feed render goes through a `renderList({container, state, items, empty, error})` wrapper) and an audit/test that flags a list-rendering module not using state-kit.+5. **Verify in the browser** — `npm run dev`, exercise each surface's empty/error/loading by forcing the conditions; no blank screens, no console errors.++## Files likely in play+`src/shared/state-kit.js` (extend if needed), `src/launches.js`, `src/radar.js`, `src/oracle.js`, `src/activity*.js`, `src/coin-intel*.js`, `src/trending*.js`, `src/feed*.js`, `src/animations-gallery.js`, `src/gallery-picker*.js`, an audit script + test.++## Definition of done+- [ ] Every list/feed surface uses state-kit; no ad-hoc duplicates remain.+- [ ] Loading (skeleton, not spinner), empty (helpful + CTA), error (actionable + retry) designed for each.+- [ ] 0/1/many + long-content cases verified.+- [ ] Audit/test flags non-compliant list modules; wired to CI.+- [ ] Verified in a real browser; no console errors/warnings.+- [ ] Changelog: **improvement** entry ("consistent, helpful empty/loading/error states across the app").++## Guardrails+Follow CLAUDE.md. No mocked data to "show" populated states — wire real fetches. Push both remotes.diff --git a/prompts/production-hardening/21-accessibility-wcag.md b/prompts/production-hardening/21-accessibility-wcag.mdnew file mode 100644index 000000000..a131c421a--- /dev/null+++ b/prompts/production-hardening/21-accessibility-wcag.md@@ -0,0 +1,37 @@+# 21 · WCAG 2.2 AA accessibility pass++> **Phase 4 — Frontend excellence** · **Depends on:** 05 (axe infra helps) · **Parallel-safe:** yes · **Effort:** L++## Mission+CLAUDE.md says accessibility is not optional, but the audit expects axe/Lighthouse to flag missing+icon-button labels, inconsistent focus indicators, low-contrast dim text (`rgba(...,0.45/0.55)` on+dark), heading-hierarchy gaps, and unlabeled dynamic images. Bring the platform to **WCAG 2.2 AA**+and keep it there with an automated gate.++## Context (read first)+- `CLAUDE.md` accessibility standards.+- `public/buttons.css` (`:focus-visible` defined but not universally applied), the dim-text tokens, icon buttons in `launches.js`/`radar.js`/`oracle.js`.+- axe-core/Playwright infra from prompt 05 (build it here if 05 hasn't run).++## Build this+1. **Icon/interactive labels** — every icon-only button/link/chip/tab gets an `aria-label` (or visible text). Sweep `pages/` + `src/` for unlabeled interactive elements.+2. **Focus visibility** — a consistent, visible `:focus-visible` ring on *all* interactive elements (buttons, links, chips, toggles, custom widgets). No `outline:none` without a replacement.+3. **Contrast** — raise dim text/icon tokens to meet AA (4.5:1 body, 3:1 large/UI). Fix the `rgba(...,0.45/0.55)`-on-dark offenders centrally via tokens, not per-component.+4. **Semantics & landmarks** — proper heading hierarchy (no skips), `<nav>`/`<main>`/`<header>` landmarks, lists as lists, dialogs with `role="dialog"` + focus trap + ESC, `aria-live` for async updates (toasts, feed inserts).+5. **Keyboard nav** — every flow operable without a mouse: modals trap+restore focus, dropdowns/menus arrow-navigable, the forge/marketplace/dashboard fully keyboard-usable. Add a skip-to-content link.+6. **Dynamic images** — meaningful `alt` (or `aria-hidden` if purely decorative) on avatar/coin/model thumbnails.+7. **Gate it** — axe (prompt 05) green on the top ~15 pages at serious/critical; wire to CI.++## Files likely in play+Design tokens (CSS variables for text/contrast + focus ring), `public/buttons.css`, the offender modules, modal/dropdown components, `pages/*` landmark fixes, axe Playwright spec + CI.++## Definition of done+- [ ] axe: zero serious/critical violations on the top pages; CI-gated.+- [ ] All interactive elements labeled + keyboard-operable with visible focus.+- [ ] Contrast meets AA via tokens.+- [ ] Modals/menus/toasts have correct roles, focus management, and `aria-live`.+- [ ] Manually verified with keyboard-only + a screen reader on a key flow (forge or checkout).+- [ ] Changelog: **improvement** entry ("accessibility: WCAG 2.2 AA across the platform").++## Guardrails+Follow CLAUDE.md. Don't bolt on ARIA where native HTML suffices — semantic elements first. Push both remotes.diff --git a/prompts/production-hardening/22-performance-code-split.md b/prompts/production-hardening/22-performance-code-split.mdnew file mode 100644index 000000000..8267928cd--- /dev/null+++ b/prompts/production-hardening/22-performance-code-split.md@@ -0,0 +1,36 @@+# 22 · Performance: code-split, lazy 3D, Lighthouse ≥90++> **Phase 4 — Frontend excellence** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** L++## Mission+Several JS modules are huge and not split (`marketplace.js` ~313KB, `irl.js` ~317KB, `walk.js`+~178KB, `agent-edit.js` ~105KB), and heavy Three.js/`model-viewer` usage loads on the critical path+even for grid pages. That tanks LCP/FID on mobile. Code-split per surface, lazy-load 3D only when a+viewer mounts, and get the top pages to **Lighthouse ≥90 / Core Web Vitals green**.++## Context (read first)+- `CLAUDE.md` ("Performance by default": lazy-load heavy modules, debounce input, paginate, `transform`/`will-change` for animation).+- `vite.config.js` (existing manualChunks: `three-core`, `three-addons`, `solana`, `ethers`).+- Heavy modules above; PWA setup (`vite-plugin-pwa`, workbox).+- Image lazy audit: `scripts/audit-image-loading.mjs` (`npm run check:images`).++## Build this+1. **Lazy 3D** — dynamically `import()` Three.js addons (`GLTFLoader`, `OrbitControls`, controls) and `model-viewer` only when a viewer is actually mounted (intersection/interaction), not at module top-level. Grid/list pages must render and be interactive before any 3D loads.+2. **Per-surface code-split** — break the giant modules so each route loads only what it needs; push detail-only/editor-only code behind dynamic imports. Verify chunk graph in the build output.+3. **List performance** — paginate or virtualize unbounded lists (marketplace, gallery, feeds); debounce search inputs; cap initial render.+4. **CLS/LCP hygiene** — explicit `width`/`height` or `aspect-ratio` on all grid images (kills layout shift); `decoding="async"` + `loading="lazy"` off-fold (extend `check:images` to enforce both); preconnect/preload the true LCP resource per top page.+5. **Measure + gate** — run Lighthouse (CI via `@lhci/cli` or Playwright traces) on the top ~10 pages; commit budgets (LCP, TBT, CLS, bundle size) and fail CI on regression.++## Files likely in play+`vite.config.js` (chunking), the heavy `src/*.js` modules (dynamic imports), grid/list renderers (pagination/virtualization + image sizing), `scripts/audit-image-loading.mjs`, Lighthouse CI config + budgets, `.github/workflows`.++## Definition of done+- [ ] No page loads Three.js/`model-viewer` before first paint unless it shows 3D above the fold.+- [ ] Giant modules split; per-route bundle sizes meaningfully reduced (report before/after).+- [ ] Lists paginated/virtualized; search debounced.+- [ ] All grid images have dimensions/`aspect-ratio` + `decoding=async`; `check:images` enforces it.+- [ ] Lighthouse ≥90 (perf) on the top 10 pages; budgets gate CI.+- [ ] Changelog: **improvement** entry ("faster loads: code-splitting + lazy 3D").++## Guardrails+Follow CLAUDE.md. Don't break the viewers/PWA/offline behavior while splitting — verify in a real browser. Push both remotes.diff --git a/prompts/production-readiness/00-README.md b/prompts/production-readiness/00-README.mdnew file mode 100644index 000000000..5d42a9191--- /dev/null+++ b/prompts/production-readiness/00-README.md@@ -0,0 +1,135 @@+# three.ws — Production-Readiness Track (Road to $1B)++A complete, self-contained catalog of engineering + product-surface hardening prompts.+Each `NN-*.md` file is written to be **pasted into a fresh chat** at `/workspaces/three.ws`+and executed end-to-end by a senior agent with **no prior context**. Together they take+the platform from "works on a good day" to "fundable, demo-able to a room of senior+engineers, ready to scale."++> **Relationship to `prompts/road-to-1b/`:** that directory is the growth / monetization /+> conversion track (funding upsell, referrals, programmatic SEO, creator dashboard,+> checkout, studio/agent/marketplace surfaces). **This** directory is the+> engineering-readiness track: audits, cross-cutting hardening, every product surface,+> payments/on-chain safety, infra/ops, and the launch gate. They complement each other —+> run both. Where topics overlap (observability, rate-limiting, SEO), treat the more+> specific prompt as authoritative and don't redo work already shipped.++---++## How to use+1. Open a **new chat** in this repo (`/workspaces/three.ws`).+2. Paste the **full contents** of one prompt file. Nothing else is needed — each file is standalone.+3. Let the agent map → execute → verify → report. Review the `git diff`.+4. Commit + push when satisfied: `git push threeD main && git push threews main`.+5. Move to the next prompt. Mark it done in the tracker below.++Many prompts within a phase run in parallel in **separate chats** — but every agent shares+**one worktree**, so each must stage explicit paths only (never `git add -A`) and re-check+`git status` before committing.++---++## Phases+- **Phase 1 — Audit & baseline** (`01`–`04`): find every gap first. These produce issue lists later phases consume. **Run first.**+- **Phase 2 — Cross-cutting hardening** (`05`–`20`): secrets, errors, security, rate limits, resilience, observability, caching, tests, CI, a11y, responsive, performance, design system.+- **Phase 3 — Product surfaces** (`21`–`34`): harden each surface end-to-end — every state designed, every path reachable.+- **Phase 4 — Payments / on-chain / agent economy** (`35`–`44`): x402, wallets, pump.fun, $THREE gating, MCP, SDKs, contracts, money safety.+- **Phase 5 — Infra & ops** (`45`–`50`): migrations, load, status page, DR, key rotation, crons.+- **Phase 6 — Growth, SEO, GTM & launch** (`51`–`60`): SEO, i18n, analytics, legal, PWA, email, homepage, docs, pricing, launch gate.++**Recommended order:** Phase 1 → (Phase 2 ∥ Phase 3) → Phase 4 → Phase 5 → Phase 6.+`60-final-launch-checklist.md` is the gate — run it last and let nothing through that fails it.++---++## Operating rules (non-negotiable — every prompt repeats a short form of these)+- **Read `CLAUDE.md` + `STRUCTURE.md` first.** CLAUDE.md overrides defaults. STRUCTURE.md maps every surface to its directory.+- **No mocks, fake data, placeholders, TODOs, stub functions, or `throw new Error("not implemented")`.** Real APIs, real endpoints, real implementations only. Errors handled at boundaries; internal code trusts itself.+- **`$THREE` is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never reference, name, hardcode, import, render, or recommend any other token anywhere (code, copy, tests, fixtures, commits). If you find another coin referenced, remove it like a leaked secret. The only exceptions are runtime-supplied mints in coin-agnostic plumbing and the platform's own launch directories.+- **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 committing.+- **esbuild trap:** `npx vercel build` overwrites `api/*.js` with bundles. Never commit an `api/*.js` whose first line starts with `__defProp`/`createRequire`. Recover with `git restore -- api/ public/`.+- **Changelog:** every user-visible change → an entry in `data/changelog.json` (date, holder-readable title + summary, tags), then `npm run build:pages`. Internal-only chores get no entry.+- **Push to BOTH remotes** when asked: `git push threeD main` **and** `git push threews main`. **Never** pull/fetch/merge from `threeD` (push-only mirror); pulls come from `threews` only.+- **Definition of done** = CLAUDE.md's checklist: wired + reachable, every state designed (loading/empty/error/populated/overflow), no console errors, real API calls, hover/active/focus states, `npm test` green, `git diff` self-reviewed.++---++## Key facts every agent should know (verified 2026-06-21)+- **Stack:** vanilla JS modules + Vite (`npm run dev`, port 3000) · Three.js + glTF/GLB · Vercel functions in `api/` · Cloudflare workers in `workers/`.+- **Tests:** Vitest (`vitest run`) + Playwright (`tests/e2e/*.spec.js`). `npm test` runs both. `npm run test:gate` = critical money/auth subset. Config: `vitest.config.js`, `playwright.config.js`.+- **CI:** `.github/workflows/ci.yml` — lint (eslint, new-errors-only), unit (vitest), source guards (`check-api-not-bundled.mjs`, `check:images`, `build:pages`), typecheck (advisory).+- **API helpers:** `api/_lib/http.js` (`json`/`error`/`serverError`, security headers, no-store default), `api/_lib/env.js` (`req`/`opt`/`addr`/`pem` lazy getters), `api/_lib/db.js` (Neon serverless Postgres), `api/_lib/rate-limit.js` (Upstash Redis, fail-closed in prod), `api/_lib/sentry.js` (custom HTTP envelope), `api/_lib/secret-box.js` (AES-256-GCM).+- **Health:** `api/healthz.js` → `GET /api/healthz`. Client error reporter: `public/error-reporter.js` → `POST /api/client-errors`.+- **DB migrations:** `api/_lib/migrations/*.sql` (183 files), runner `scripts/apply-migrations.mjs` (`npm run db:migrate` / `db:status`), tracked in `schema_migrations`.+- **Headers/routes:** `vercel.json` (HSTS, nosniff, referrer-policy, permissions-policy, CSP, per-route cache + frame-ancestors).+- **Design tokens:** `public/tokens.css` (golden-ratio scale) + `:root` in `public/style.css`. Theme: `public/theme-switcher.js` (`twx_theme`). Mobile: `public/mobile.css`.+- **i18n:** `.i18nrc.json` (Groq provider, 11 target locales), `public/locales/*.json`, `src/i18n.js`, `scripts/i18n-extract.mjs` + `i18n-translate.mjs`. Only `en` + `es` live so far.+- **SEO:** `data/pages.json` (source of truth) → `scripts/build-page-index.mjs` → sitemap, `llms.txt`, changelog. Page route audit is strict: every public `.html` route must be in `data/pages.json` or `scripts/audit-page-index.mjs`'s IGNORE set.++---++## Status tracker+Mark each as you go.++| # | Prompt | Phase | Status |+|---|---|---|---|+| 01 | production-readiness-audit | 1 | ☐ |+| 02 | dead-paths-and-broken-links | 1 | ☐ |+| 03 | console-errors-and-warnings | 1 | ☐ |+| 04 | routing-redirects-and-404 | 1 | ☐ |+| 05 | secrets-and-env-hygiene | 2 | ☐ |+| 06 | error-handling-and-failsafes | 2 | ☐ |+| 07 | security-hardening | 2 | ☐ |+| 08 | rate-limiting-and-abuse | 2 | ☐ |+| 09 | resilience-external-calls | 2 | ☐ |+| 10 | observability-and-alerting | 2 | ☐ |+| 11 | backend-caching-and-cdn | 2 | ☐ |+| 12 | test-coverage-unit | 2 | ☐ |+| 13 | e2e-critical-flows | 2 | ☐ |+| 14 | ci-cd-gates | 2 | ☐ |+| 15 | accessibility-wcag | 2 | ☐ |+| 16 | mobile-responsiveness | 2 | ☐ |+| 17 | performance-core-web-vitals | 2 | ☐ |+| 18 | frontend-bundle-performance | 2 | ☐ |+| 19 | 3d-asset-performance | 2 | ☐ |+| 20 | design-system-consistency | 2 | ☐ |+| 21 | forge-text-to-3d-pipeline | 3 | ☐ |+| 22 | avatar-create-edit-rig | 3 | ☐ |+| 23 | selfie-to-avatar | 3 | ☐ |+| 24 | gallery-and-animations | 3 | ☐ |+| 25 | scene-studio | 3 | ☐ |+| 26 | dashboard | 3 | ☐ |+| 27 | search-and-discovery | 3 | ☐ |+| 28 | onboarding-create-wizard | 3 | ☐ |+| 29 | feature-tour-and-demos | 3 | ☐ |+| 30 | social-club-and-city | 3 | ☐ |+| 31 | walk-and-irl | 3 | ☐ |+| 32 | widget-studio-embed | 3 | ☐ |+| 33 | agent-studio-and-brain | 3 | ☐ |+| 34 | launches-feed-and-agent-profiles | 3 | ☐ |+| 35 | x402-payments-hardening | 4 | ☐ |+| 36 | wallet-connect-and-funding | 4 | ☐ |+| 37 | pumpfun-launches | 4 | ☐ |+| 38 | three-holder-gating | 4 | ☐ |+| 39 | mcp-servers | 4 | ☐ |+| 40 | published-sdks-and-docs | 4 | ☐ |+| 41 | onchain-contracts | 4 | ☐ |+| 42 | solana-base-parity | 4 | ☐ |+| 43 | agent-to-agent-payments | 4 | ☐ |+| 44 | money-safety-idempotency | 4 | ☐ |+| 45 | database-migrations-and-integrity | 5 | ☐ |+| 46 | load-and-stress-testing | 5 | ☐ |+| 47 | uptime-health-and-status-page | 5 | ☐ |+| 48 | backup-and-disaster-recovery | 5 | ☐ |+| 49 | secrets-rotation-and-key-management | 5 | ☐ |+| 50 | cron-and-worker-hardening | 5 | ☐ |+| 51 | seo-and-structured-data | 6 | ☐ |+| 52 | i18n-completeness | 6 | ☐ |+| 53 | analytics-and-funnels | 6 | ☐ |+| 54 | legal-compliance-and-consent | 6 | ☐ |+| 55 | pwa-and-offline | 6 | ☐ |+| 56 | notifications-and-email | 6 | ☐ |+| 57 | homepage-and-conversion | 6 | ☐ |+| 58 | docs-completeness | 6 | ☐ |+| 59 | pricing-and-packaging | 6 | ☐ |+| 60 | final-launch-checklist | 6 | ☐ |diff --git a/prompts/production-readiness/01-production-readiness-audit.md b/prompts/production-readiness/01-production-readiness-audit.mdnew file mode 100644index 000000000..7f47990cc--- /dev/null+++ b/prompts/production-readiness/01-production-readiness-audit.md@@ -0,0 +1,45 @@+# 01 — Production-readiness audit (baseline)++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 1 · Audit & baseline+**Owns:** read-only audit — produces `docs/internal/audit/` reports, edits nothing in `src/`/`api/`.+**Pairs with:** every later prompt consumes this output.++## Why this matters for $1B+You cannot harden what you cannot see. A fundable platform starts with an honest,+written inventory of every gap. This audit is the map the entire Road-to-$1B effort+navigates by — it converts "the app feels rough" into a prioritized, assignable list.++## Mission+Produce a complete, severity-ranked inventory of production gaps across the codebase+and write it to `docs/internal/audit/`. **Find and document — do not fix here.** Each+finding must name the exact file/route and map to the prompt that will fix it.++## Map — real anchors+- `STRUCTURE.md` — surface→directory map. Start here.+- `data/pages.json` — every public route (source of truth for what ships).+- `vercel.json` — routes, headers, crons. `api/` (961 functions), `src/` (810 modules), `pages/` (168 HTML).+- `scripts/audit-pages.mjs`, `scripts/audit-handlers.mjs`, `scripts/page-audit.mjs`, `scripts/check-images.mjs` — existing audits to run.++## Do this+1. Run every existing audit and capture output: `npm run audit:pages`, `npm run audit:handlers`, `npm run check:images`, `npm run audit:web`, `npm run audit:deploy`. Record failures.+2. **Stub/mock/TODO sweep:** grep the codebase for `TODO`, `FIXME`, `not implemented`, `throw new Error('not`, `setTimeout(` fake-loading, `const sample`, `mockData`, `placeholder`, commented-out code blocks. List every hit with file:line. (CLAUDE.md forbids all of these.)+3. **Empty-handler sweep:** find `api/` functions that return nothing, 501, or a hardcoded shape instead of real data.+4. **Surface completeness:** walk `STRUCTURE.md`'s surface list; for each, confirm the page loads, has real data, and every CTA/link resolves. Note half-wired surfaces.+5. **Designed-states gap:** for the top 20 routes by importance, note which lack a designed loading / empty / error state.+6. **Coin compliance:** grep for any token reference that is not `$THREE` / CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` (exclude runtime-supplied mints + platform launch directories). Flag each as a hard blocker.+7. Write `docs/internal/audit/README.md` (exec summary + counts) and one file per category (`stubs.md`, `dead-paths.md`, `designed-states.md`, `coin-compliance.md`, `handlers.md`). Each finding: `file:line` · severity (blocker/high/med/low) · which prompt (`NN`) fixes it.++## Must-not+- Do not fix anything here except trivially-safe deletions of dead code you are 100% sure about — this prompt's value is the written inventory.+- Do not under-report. A short audit of a 60-surface platform is a failed audit.++## Definition of done+- [ ] `docs/internal/audit/` exists with an exec summary + per-category reports, every finding tagged with file:line, severity, and owning prompt number.+- [ ] All existing `npm run audit:*` results captured (pass/fail + output).+- [ ] Coin-compliance section is exhaustive (every non-`$THREE` reference, or "none found").+- [ ] Counts roll up in the README (e.g. "47 stubs, 12 dead paths, 9 undesigned error states").++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/02-dead-paths-and-broken-links.md b/prompts/production-readiness/02-dead-paths-and-broken-links.mdnew file mode 100644index 000000000..139925232--- /dev/null+++ b/prompts/production-readiness/02-dead-paths-and-broken-links.md@@ -0,0 +1,45 @@+# 02 — Dead paths & broken links++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 1 · Audit & baseline+**Owns:** navigation, `<a href>`/`<link>`, in-app router targets, CTA buttons across `pages/` + `src/`.+**Depends on:** `01` (audit). **Pairs with:** `04` (routing/404).++## Why this matters for $1B+Every dead link is a visitor hitting a wall — and a signal to investors that nobody is+minding the store. CLAUDE.md is explicit: "If a button exists, it must work. If a link+exists, it must go somewhere." A platform that wants a $1B valuation cannot have a single+404 reachable from its own UI.++## Mission+Find every broken/dead navigation path and **fix it** — either wire it to the real+destination or remove the element. Zero dead ends reachable from the UI.++## Map — real anchors+- Nav/header/footer components in `src/` (search for the shared nav module and `public/style.css` nav classes).+- `data/pages.json` — the canonical list of real routes; any link not resolving to one of these (or a real API/asset) is suspect.+- `vercel.json` routes — source→dest mappings and redirects.+- `scripts/page-audit.mjs` / `npm run audit:web` — existing link/route checks.++## Do this+1. Extract every internal `href`, `window.location` assignment, router `navigate()` target, and CTA click handler destination across `pages/` and `src/`.+2. Cross-check each against `data/pages.json` + `vercel.json` routes + real assets. Anything resolving to a missing page, a `#` placeholder, or `javascript:void(0)` with no handler is a finding.+3. **Fix each:** wire the link to the correct real destination, OR remove the element if the destination genuinely doesn't exist yet (don't leave a dead button). Prefer wiring — most "dead" links point at surfaces that DO exist under a different path.+4. Check the inverse: real, valuable pages in `data/pages.json` that **nothing links to** (orphans). Add navigation to reach them (CLAUDE.md: "If a state exists, there must be a way to reach it").+5. Verify external links open correctly and use `rel="noopener"` where `target="_blank"`.+6. Run the app (`npm run dev`) and click through the primary nav + footer + top 10 surfaces to confirm no console 404s on navigation.++## Must-not+- Do not "fix" a dead link by pointing it at the homepage as a catch-all. Find the real target or remove it.+- Do not add a link to a page that isn't production-ready just to clear an orphan — harden the page first or leave it unlinked with a note.++## Definition of done+- [ ] Every internal link/CTA resolves to a real, working destination (verified in browser).+- [ ] No orphan production pages reachable only by typing the URL — each has a nav path.+- [ ] `target="_blank"` links carry `rel="noopener"`.+- [ ] `npm run audit:web` passes; no navigation 404s in console during a click-through.+- [ ] `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/03-console-errors-and-warnings.md b/prompts/production-readiness/03-console-errors-and-warnings.mdnew file mode 100644index 000000000..529b32a98--- /dev/null+++ b/prompts/production-readiness/03-console-errors-and-warnings.md@@ -0,0 +1,39 @@+# 03 — Console errors & warnings sweep++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 1 · Audit & baseline+**Owns:** runtime console output across all surfaces; the client error reporter.+**Depends on:** `01`. **Pairs with:** `10` (observability).++## Why this matters for $1B+The browser console is the platform's pulse. CLAUDE.md's definition of done requires+"no console errors, no console warnings from your code." Every uncaught error is a+visitor-facing bug waiting to happen and a degraded Core Web Vitals / reliability story.+Clean consoles are table stakes for a serious product.++## Map — real anchors+- `public/error-reporter.js` — first-party reporter, `POST /api/client-errors`; already filters extension noise + ResizeObserver. Use it to find what's actually firing.+- `api/client-errors.js` (or the handler behind `/api/client-errors`) — where client errors land.+- `npm run dev` (port 3000) — exercise surfaces here.++## Do this+1. Start `npm run dev`. Open each of the top ~20 surfaces (home, forge, gallery, marketplace, dashboard, create flow, scene, club, city, walk, agent-studio, brain, etc. — see `STRUCTURE.md`).+2. For each, capture **all** console errors/warnings and failed network requests. Categorize: real bug vs. third-party noise vs. expected-in-dev.+3. **Fix every error and every warning originating from our code:** unhandled promise rejections, `404`/`500` on real assets/APIs, missing keys, deprecated API usage, hydration/render warnings, Three.js warnings (missing textures, NaN transforms, disposed-object access).+4. For genuinely external noise (extensions, blocked trackers), confirm `public/error-reporter.js` already filters it; extend the filter only if a real new source appears.+5. **Failed network requests:** every `4xx`/`5xx` on a request our code initiates is a finding — fix the call or the endpoint. No swallowed failures.+6. Re-run the click-through; confirm zero of our errors/warnings remain.++## Must-not+- Do not silence errors with empty `catch {}` or by disabling logging — fix the root cause (CLAUDE.md: "No errors without solutions").+- Do not suppress a warning you don't understand. Understand it, then fix it.++## Definition of done+- [ ] Top ~20 surfaces produce **zero** errors/warnings from our code in the console.+- [ ] No failed network requests for assets/APIs our code initiates.+- [ ] Any remaining console output is provably third-party and filtered by the reporter.+- [ ] `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/04-routing-redirects-and-404.md b/prompts/production-readiness/04-routing-redirects-and-404.mdnew file mode 100644index 000000000..f967a219f--- /dev/null+++ b/prompts/production-readiness/04-routing-redirects-and-404.md@@ -0,0 +1,41 @@+# 04 — Routing, redirects & 404/500 pages++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 1 · Audit & baseline+**Owns:** `vercel.json` routes/redirects, the 404 + 500 error pages, the page-route audit.+**Depends on:** `01`, `02`. **Pairs with:** `51` (SEO).++## Why this matters for $1B+Routing is the platform's plumbing. Broken redirects leak SEO equity, mis-scoped routes+expose internal pages, and an undesigned 404 turns a recoverable wrong-turn into a bounce.+The strict page-route audit (which already gates the Vercel build) is the contract: every+public `.html` route is either documented or deliberately excluded.++## Map — real anchors+- `vercel.json` — all `routes` (src→dest), redirects, cache + frame headers.+- `data/pages.json` — documented public routes (source of truth).+- `scripts/audit-page-index.mjs` — strict audit; every auditable `.html` route must be in `data/pages.json` or its `IGNORE`/`IGNORE_PREFIXES` set. **This gates `npm run build:vercel`.**+- The 404 page (search `public/` / `pages/` for `404.html`) and any 500/offline page (`public/cz/offline/index.html`).++## Do this+1. Run `node scripts/audit-page-index.mjs --strict`. Resolve every undocumented route: add real landing pages to `data/pages.json` (path, title, description, `added: YYYY-MM-DD`), or add genuine in-flow/noindex shells to the audit's IGNORE set **with a one-line justification comment** (match the existing style, e.g. `/avatar-studio`, `/avatar-edit`).+2. Audit `vercel.json` redirects: confirm each points at a live destination, uses the correct status (301 permanent vs 302/307 temporary), and there are no redirect chains/loops.+3. **404 page:** ensure it exists, is branded, explains what happened, and offers real next steps (search, home, popular surfaces) — not a blank "Not Found." Design loading/empty parity with the rest of the platform.+4. **500 / error boundary:** ensure server/edge failures render a branded, actionable page (retry, status link, support), not a raw stack or Vercel default.+5. Check `noindex` correctness: in-flow/editor shells (`robots: noindex`) must **not** be in `data/pages.json` (those feed the public sitemap) — they belong in the audit IGNORE set instead.+6. Verify trailing-slash + case behavior is consistent (no duplicate-content routes).++## Must-not+- Do not add a `noindex` editor shell to `data/pages.json` — it would be sitemapped against its own directive. Use the audit IGNORE set.+- Do not paper over an undocumented route by deleting it from `vercel.json` if the page is real and reachable — document it instead.++## Definition of done+- [ ] `node scripts/audit-page-index.mjs --strict` exits 0; `npm run build:vercel` passes the page-index step.+- [ ] Every redirect resolves, with correct status codes, no chains/loops.+- [ ] Branded, actionable 404 **and** 500/error pages exist and are reachable.+- [ ] `noindex` shells are excluded from the sitemap (in IGNORE, not in `pages.json`).+- [ ] `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/05-secrets-and-env-hygiene.md b/prompts/production-readiness/05-secrets-and-env-hygiene.mdnew file mode 100644index 000000000..8855da534--- /dev/null+++ b/prompts/production-readiness/05-secrets-and-env-hygiene.md@@ -0,0 +1,38 @@+# 05 — Secrets & env hygiene++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 2 · Cross-cutting hardening+**Owns:** `api/_lib/env.js`, `.env.example`, secret reads across `api/`/`workers/`/`scripts/`, `api/_lib/secret-box.js`.+**Pairs with:** `07` (security), `49` (key rotation).++## Why this matters for $1B+This platform custodies wallets and private keys (`AGENT_RELAYER_KEY`, `THREEWS_SOL_PARENT_SECRET_BASE58`, treasury wallets). A single leaked secret = drained funds = dead company. Investors run secret scanners on day one of diligence.++## Map — real anchors+- `api/_lib/env.js` — lazy getters `req()`/`opt()`/`addr()`/`pem()`; prod fail-closed guards (e.g. `MULTIPLAYER_SHARED_SECRET`, `AGENT_RELAYER_KEY`).+- `api/_lib/secret-box.js` — AES-256-GCM for custodial secrets; `api/_lib/agent-wallet.js` uses it.+- `.env.example` — documents ~150 vars. Must list every var the code reads.+- `api/_lib/http.js` — already redacts lat/lng/token from logs before Sentry/alerts.++## Do this+1. **No committed secrets:** scan the full git working tree + history for leaked keys (private keys, API tokens, base58 secrets, connection strings). `git secrets` / `trufflehog`-style scan. Any real secret in history → rotate it and document in `49`.+2. **Env completeness:** diff every `process.env.X` / `req('X')` / `opt('X')` read in `api/`, `workers/`, `scripts/` against `.env.example`. Add every missing var with a one-line description + example placeholder (never a real value).+3. **Fail-closed in prod:** every secret that, if unset, would silently degrade security (signing keys, shared secrets, encryption keys) must throw in production when missing — extend the `env.js` guard pattern. Optional-with-fallback is only for genuinely optional features.+4. **No secrets to client:** confirm no secret-bearing var is read in `src/` (client bundles). Only `VITE_`-prefixed public values may reach the browser. Grep `src/` for sensitive var names.+5. **No secrets in logs:** audit `console.log`/error and alert payloads for secret leakage; extend the `http.js` redaction list as needed.+6. **Encryption at rest:** confirm all custodial secrets (wallet keys) go through `secret-box.js` (per-record salt), never plaintext in DB.++## Must-not+- Never put a real secret value in `.env.example`, a test fixture, a comment, or a commit message.+- Do not weaken a fail-closed guard to make local dev easier — use a documented dev default that is obviously non-production.++## Definition of done+- [ ] Secret scan over working tree + history is clean (or every hit rotated + documented).+- [ ] `.env.example` lists every var the code reads, with placeholders only.+- [ ] All security-critical secrets fail closed in prod when unset.+- [ ] No secret reaches the client bundle; no secret appears in logs/alerts.+- [ ] `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/06-error-handling-and-failsafes.md b/prompts/production-readiness/06-error-handling-and-failsafes.mdnew file mode 100644index 000000000..2332fbff8--- /dev/null+++ b/prompts/production-readiness/06-error-handling-and-failsafes.md@@ -0,0 +1,41 @@+# 06 — Error handling & failsafes++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 2 · Cross-cutting hardening+**Owns:** error boundaries across `api/` + `src/`; the shared HTTP error helpers; user-facing error states.+**Depends on:** `01`, `03`. **Pairs with:** `09` (external-call resilience).++## Why this matters for $1B+CLAUDE.md: "No errors without solutions. There is always a correct answer — find it." A+platform earns trust by failing gracefully: every failure is caught at a boundary, logged,+and rendered to the user as something they can act on — never a blank screen, infinite+spinner, or raw stack trace.++## Map — real anchors+- `api/_lib/http.js` — `json()` / `error(res, status, code, message, extra)` / `serverError()` (auto-captures to Sentry + sends ops alert). Standard `{ error, error_description, ...extra }` shape.+- `api/_lib/sentry.js` — custom HTTP envelope (2.5s timeout so reporting never hangs).+- `public/error-reporter.js` — client-side uncaught error + rejection capture.+- Frontend surfaces in `src/` — each needs designed error UI.++## Do this+1. **Boundaries, not internals:** confirm errors are handled where the world is untrusted (network, user input, RPC, wallet, payment) and internal code trusts itself. Remove defensive noise inside trusted code; add real handling at the edges.+2. **Every API handler:** wraps its logic so unexpected throws go through `serverError()` (logged + alerted) and return a clean `{ error, error_description }` with the right status — never a leaked stack or hung request. Validate inputs early and return 400 with a specific code.+3. **Every async UI action:** has explicit `loading → success → error` handling. On failure, render a designed, **actionable** error (what failed + how to retry/recover), wired to real retry logic — not a toast that dead-ends.+4. **Failsafe fallbacks:** for non-critical features (a feed that fails, a price that won't load), degrade gracefully with a real fallback path or a clear "couldn't load — retry" affordance. No white screens.+5. **Promise rejections:** no unhandled rejections (verify via `03`'s console sweep). Every `.then()` has a `.catch`, every `await` is guarded where it can throw.+6. **Idempotent retries:** where a user can retry a failed mutation, ensure retries are safe (see `44` for money paths).++## Must-not+- No empty `catch {}` swallowing. No `console.error` as the only handling for a user-facing failure.+- No infinite spinners: every loading state has a timeout → error path.+- Do not expose internal error detail (stack, SQL, secrets) to the client.++## Definition of done+- [ ] Every `api/` handler routes unexpected errors through `serverError()` and returns a clean shape with correct status.+- [ ] Every async UI action has a designed, actionable error state wired to real retry.+- [ ] No unhandled promise rejections; no infinite spinners; no leaked internals.+- [ ] Regression tests cover the main failure paths; `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/07-security-hardening.md b/prompts/production-readiness/07-security-hardening.mdnew file mode 100644index 000000000..3a2b67097--- /dev/null+++ b/prompts/production-readiness/07-security-hardening.md@@ -0,0 +1,42 @@+# 07 — Security hardening++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 2 · Cross-cutting hardening+**Owns:** authn/authz across `api/`, input validation, security headers in `vercel.json`, CORS, money-path invariants.+**Depends on:** `05` (secrets), `06` (errors). **Pairs with:** `08` (rate limits), `44` (money safety).++## Why this matters for $1B+This platform custodies wallets and moves money (x402, $THREE, skill purchases, pump.fun). One authz bug = drained funds = dead company. Security is the difference between a fundable platform and a liability. Run a real review; fix what it finds.++## Map — real anchors+- Auth/ownership: agent identities have an immutable owner; only the owner may withdraw / set limits / rebrand. Money paths: `api/x402*`, `api/x402/*`, `api/payments/*`, `api/pump/*`, `api/_lib/agent-wallet.js`, `api/_lib/skill-license-onchain.js`.+- `api/_lib/http.js` — already sets nosniff, frame-ancestors deny, strict CSP defaults on responses.+- `vercel.json` — global CSP/HSTS/permissions-policy + per-route frame-ancestors. CSP currently allows `'unsafe-inline'`/`'unsafe-eval'` for scripts with a CDN allow-list.+- `/security-review` skill — run it.++## Do this+1. Run the repo's `/security-review` over the current branch; triage findings by severity.+2. **AuthZ on every mutating endpoint:** confirm the caller owns the resource before any write/withdraw/rebrand/spend. Audit `api/` for endpoints trusting a client-supplied `user_id`/`agent_id` without verifying the session. Fix every one.+3. **Input validation at boundaries:** validate/normalize every body, query, and path param (length, type, range, address format, amount bounds). Reject early with 400. Close injection (SQL/NoSQL/command), path traversal, and SSRF (anywhere a URL is fetched on the user's behalf — forge image inputs, avatar URL import).+4. **Money-path invariants:** amount sanity bounds; idempotency keys on transfers/mints (see `44`); replay protection on signed requests; **server-side price recomputation** — never trust client-sent amounts.+5. **Security headers:** tighten CSP toward removing `'unsafe-inline'`/`'unsafe-eval'` where feasible (move inline handlers to modules); keep HSTS, nosniff, referrer-policy, permissions-policy. Confirm embed routes relax frame-ancestors **only** for intended embed surfaces.+6. **CORS:** lock API CORS to known origins; never reflect arbitrary `Origin`.+7. **Dependency audit:** `npm audit` + `npm audit --workspaces`; fix high/critical by upgrade; document any accepted advisory with rationale.+8. Add regression tests for each fixed authz/validation hole.++## Must-not+- Never trust client-supplied identity, amount, or price.+- Do not weaken CSP "to make something work" — fix the inline/eval cause.+- Do not replay money-moving requests without idempotency.++## Definition of done+- [ ] `/security-review` findings resolved or risk-accepted with written rationale.+- [ ] Every mutating endpoint verifies ownership/session server-side.+- [ ] All inputs validated at the boundary; injection/traversal/SSRF closed.+- [ ] Money paths: amount bounds + idempotency + server-side price recompute.+- [ ] Headers tightened, CORS locked; `npm audit` clean of high/critical (or documented).+- [ ] Regression tests added; `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/08-rate-limiting-and-abuse.md b/prompts/production-readiness/08-rate-limiting-and-abuse.mdnew file mode 100644index 000000000..d9a0fcf70--- /dev/null+++ b/prompts/production-readiness/08-rate-limiting-and-abuse.md@@ -0,0 +1,36 @@+# 08 — Rate limiting & abuse controls++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 2 · Cross-cutting hardening+**Owns:** `api/_lib/rate-limit.js` and its call sites; abuse caps on expensive + money + write endpoints.+**Depends on:** `07`. **Pairs with:** `09`, `35` (x402), `21` (forge).++## Why this matters for $1B+Every expensive endpoint (forge GPU, paid x402 verify, pump.fun launches, LLM proxies) is a budget bomb if unbounded — one abuser can run up a five-figure bill or DoS the service. Rate limiting is how the platform survives going viral.++## Map — real anchors+- `api/_lib/rate-limit.js` — Upstash Redis–backed (`@upstash/ratelimit`), in-memory fallback for dev/tests, **fail-closed in prod when Redis unset**. Existing limits: `FORGE_PAID_GLOBAL_HOURLY` (~600/h GPU circuit breaker), `X402_VERIFY_GLOBAL_PER_HOUR` (~12k/h). Returns 429 with `rate_limited` + `retry_after`.+- ~20 handlers already import it (agent-skills, newsletter, forge-*, x402-pay, pump/safety).++## Do this+1. **Inventory expensive/abusable endpoints:** GPU/forge (`api/x402/forge*`, `api/forge*`), LLM proxies, image/3D generation, pump.fun launch/trade, wallet funding, vanity grinding, search, newsletter/signup, anything that writes to DB or spends money. List which already have limits and which don't.+2. **Apply per-IP + per-user limits** to every endpoint on that list, using the existing `rate-limit.js` helper. Tune thresholds to real usage + cost ceilings; keep a **global circuit breaker** on the most expensive lanes (GPU, paid verify).+3. **Graceful 429s:** ensure every limited endpoint returns the standard 429 with `retry_after`, and the **frontend renders it as a designed, friendly "slow down / try again in Ns" state** — not a generic error.+4. **Abuse vectors beyond rate:** signup/email enumeration, content spam in user-generated surfaces (gallery, marketplace, club), referral fraud, free-tier farming. Add the right control (captcha challenge on suspicious patterns, dedupe, holder-gating where appropriate).+5. **Confirm fail-closed:** in production, missing Redis must block (not silently allow unlimited). Verify the startup warning + behavior.+6. Add tests that assert limits trigger and the 429 shape is correct.++## Must-not+- Do not leave any GPU/paid/money/write endpoint unbounded.+- Do not fail open in production when the limiter backend is down.+- Do not surface a raw 429 to users — design the throttle state.++## Definition of done+- [ ] Every expensive/money/write endpoint has per-IP + per-user limits; costliest lanes have a global breaker.+- [ ] 429s carry `retry_after` and render as a friendly frontend state.+- [ ] Limiter fails closed in prod; abuse vectors (enumeration, spam, referral fraud) addressed.+- [ ] Tests cover limit-trigger + 429 shape; `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/09-resilience-external-calls.md b/prompts/production-readiness/09-resilience-external-calls.mdnew file mode 100644index 000000000..d225f807c--- /dev/null+++ b/prompts/production-readiness/09-resilience-external-calls.md@@ -0,0 +1,42 @@+# 09 — Resilience of external calls++> **Road to $1B · Production-Readiness track.** Paste this whole file into a fresh chat at `/workspaces/three.ws`. Read `CLAUDE.md` + `STRUCTURE.md` first — they override defaults.++**Phase:** 2 · Cross-cutting hardening+**Owns:** every outbound call to a third party (Solana/EVM RPC, pump.fun, OpenAI/Anthropic proxies, NVIDIA NIM/Meshy/Tripo, Upstash, Neon, R2).+**Depends on:** `06`. **Pairs with:** `10` (observability), `47` (status).++## Why this matters for $1B+The platform's uptime is a function of its weakest upstream. RPCs rate-limit, model+providers 503, pump.fun hiccups. Without timeouts, retries, and failover, one slow+dependency cascades into a platform-wide hang. Resilient external calls are what let the+product stay up when the internet doesn't.++## Map — real anchors+- `api/_lib/solana/connection.js` — Solana RPC with fallback logic. `api/_lib/evm/rpc.js` — EVM fallback provider.+- `api/_lib/pump.js`, `api/_lib/pump-quote.js` — pump.fun client.+- Worker proxies for OpenAI/Anthropic in `workers/`. Forge engines (TRELLIS/NIM, Meshy, Tripo, Stability) behind `api/forge*` / `api/x402/forge*`.+- **Memory:** prefer vetted OSS — there's a `cockatiel` resilience helper available; adopt it rather than hand-rolling retry/breaker logic. Add to new/unprotected call sites; don't refactor working code needlessly.++## Do this+1. **Inventory** every outbound third-party call across `api/` + `workers/`. For each note: timeout? retry? failover? circuit breaker? idempotency on retry?+2. **Timeouts everywhere:** no unbounded `fetch`/RPC. Set per-call timeouts sized to the dependency. A hung upstream must never hang our function to its `maxDuration`.+3. **Retry with backoff** on transient failures (429/5xx/network), with jitter and a cap. Use `cockatiel` (or the existing helper) for consistent retry + circuit-breaker policy. **Only retry idempotent operations** — never blindly retry a money move (coordinate with `44`).+4. **Failover:** RPC and model providers should fail over to a secondary on persistent failure (extend the existing `connection.js`/`rpc.js` fallback pattern). Confirm the failover path itself is validated before use (don't forward an unvalidated RPC body — see commit `fa82d3c8a`).+5. **Circuit breakers** on flaky upstreams so a dead provider sheds load fast instead of timing out every request.+6. **Graceful degradation:** when a non-critical upstream is down, return a real fallback or a clear "temporarily unavailable" — never a 500 cascade.+7. Add tests simulating upstream timeout / 5xx / failover.++## Must-not+- No unbounded external calls. No retry of non-idempotent money operations.+- Do not forward an unvalidated upstream response body through failover.+- Do not hand-roll a bespoke breaker if the vetted helper fits.++## Definition of done+- [ ] Every external call has a timeout; transient failures retry with backoff (idempotent only).+- [ ] RPC + model providers fail over to a secondary; flaky upstreams have breakers.+- [ ] Non-critical upstream failures degrade gracefully, not as 500s.+- [ ] Tests cover timeout/5xx/failover; `npm test` green; `git diff` reviewed.++---+**Non-negotiables (CLAUDE.md):** No mocks / fake data / TODOs / stubs — real APIs only. **`$THREE` is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never reference any other token anywhere. Concurrent agents share this worktree → **stage explicit paths** (never `git add -A`); re-check `git status`/`git diff --staged` before commit. Never commit `api/*.js` starting with `__defProp`/`createRequire` (esbuild trap → `git restore -- api/ public/`). User-visible change → `data/changelog.json` + `npm run build:pages`. Push to BOTH remotes (`threeD`, `threews`) when asked; never pull/fetch from `threeD`.diff --git a/prompts/production-readiness/INDEX.md b/prompts/production-readiness/INDEX.mdnew file mode 100644index 000000000..7debf6227--- /dev/null+++ b/prompts/production-readiness/INDEX.md@@ -0,0 +1,169 @@+# three.ws → Production-Ready · Prompt Library++A sequenced set of **self-contained prompts**. Run each one in a **fresh chat**. Each+file is written so an agent with zero prior context can read it, orient itself in the+repo, and ship the work end-to-end at the bar set by `CLAUDE.md`.++This library is the plan to take three.ws from "technically strong on core paths" to+**production-grade and category-leading** — the work that compounds into a credible+$1B platform: reliability, security, a complete revenue engine, finished product+surfaces, a growth/conversion funnel, developer experience, and the test/ops+discipline that lets all of it scale.++---++## How to use this++1. Open a new chat in this repo.+2. Paste the contents of one `Pxx-*.md` file (or say "run `prompts/production-readiness/Pxx-*.md`").+3. The agent executes that one workstream to done, including tests and a changelog+ entry where user-visible.+4. Commit/push when you're satisfied (the agent will not push unless you ask).++Run roughly in priority order (P0 → P1 → P2). Within a priority, the `Depends on:`+field tells you what must land first. Many P1/P2 prompts are independent and can run+in parallel across separate chats.++---++## The shape of every prompt++Each file follows the same template so they're predictable to run:++- **Header** — workstream, priority, effort, dependencies.+- **Before you start** — fresh-chat orientation (read `CLAUDE.md` + `STRUCTURE.md`; the $THREE-only rule).+- **Context** — what the system is and the exact files involved.+- **Problem / opportunity** — the evidence-based gap.+- **Mission** — what to ship.+- **Scope** — in/out.+- **Implementation guide** — concrete, file-by-file.+- **Definition of done** — checklist aligned to `CLAUDE.md`.+- **Verification** — how to prove it works.+- **Guardrails** — the non-negotiables (no mocks, $THREE only, both remotes, etc.).++---++## Workstreams++### A · Backend reliability & observability (`api/`, `workers/`)+| # | Prompt | Priority |+|---|--------|----------|+| P01 | Cron idempotency & money-moving safety | P0 |+| P02 | x402 settlement reliability & stuck-payment recovery | P0 |+| P03 | Forge backend availability probes & config validation | P0 |+| P04 | Solana RPC circuit breaker & resilient fallback | P1 |+| P05 | Rate-limit resilience under Redis outage + per-client x402 verify cap | P1 |+| P06 | Idempotency-Key support on create/mutation endpoints | P1 |+| P07 | Observability: metrics, tracing, real-time dashboards | P1 |+| P08 | Database query observability & connection-pool monitoring | P1 |+| P09 | Session security hardening | P1 |+| P10 | Secrets rotation strategy & vault integration | P1 |++### B · Security & compliance+| # | Prompt | Priority |+|---|--------|----------|+| P11 | Dependency scanning in CI + fix `legacy-peer-deps` risk | P0 |+| P12 | SAST + secret scanning in CI | P0 |+| P13 | CSRF protection on state-changing endpoints | P0 |+| P14 | CSP tightening (nonces, drop `unsafe-inline`/`unsafe-eval`) | P1 |+| P15 | Threat model + external security-audit prep | P1 |+| P16 | Privacy center, data export/delete, retention policy | P1 |+| P17 | Legal: Terms, Privacy, Acceptable Use, Payment Terms | P1 |++### C · Monetization completion (revenue engine)+| # | Prompt | Priority |+|---|--------|----------|+| P18 | Subscriptions / time-pass settlement | P0 |+| P19 | Agent revenue payouts + per-agent earnings ledger | P0 |+| P20 | Enforce remaining $THREE tier perks | P1 |+| P21 | Revenue analytics dashboards (per-endpoint / creator / agent) | P1 |+| P22 | EVM x402 lane scale validation (Base Permit2, Arbitrum) | P0 |+| P23 | Pricing page, plans & clear rate cards | P1 |+| P24 | Referral revenue engine, end-to-end | P1 |++### D · Product surface completion+| # | Prompt | Priority |+|---|--------|----------|+| P25 | Marketplace reviews & ratings | P1 |+| P26 | Inline chat integration (agent detail + marketplace) | P1 |+| P27 | Scene Studio persistence + scene gallery | P1 |+| P28 | Avatar gallery 3D previews | P1 |+| P29 | Avatar rig fallback UX | P1 |+| P30 | Dashboard analytics charts (real visualizations) | P1 |+| P31 | Bounties, end-to-end (detail, submit, escrow) | P1 |+| P32 | Dashboard x402 payment history | P1 |+| P33 | Custom 404 + designed error pages | P1 |+| P34 | Real-time leaderboards | P2 |+| P35 | Agent skills preview modals | P2 |+| P36 | Create-Agent wizard onboarding polish | P1 |++### E · Growth, conversion & retention+| # | Prompt | Priority |+|---|--------|----------|+| P37 | Role-based landing architecture | P1 |+| P38 | Progressive / guest onboarding (try before signup) | P1 |+| P39 | Public metrics dashboard (platform stats) | P1 |+| P40 | Gamified leaderboards | P2 |+| P41 | Viral share loops (create→share in one step) | P1 |+| P42 | Social proof: testimonials & success metrics | P2 |+| P43 | Competitive positioning / comparison page | P2 |+| P44 | Empty-state & microinteraction polish pass | P1 |+| P45 | Product-tour / video landing | P2 |+| P46 | Notifications & retention hooks | P2 |++### F · SEO, content & developer experience+| # | Prompt | Priority |+|---|--------|----------|+| P47 | Developer portal / docs homepage | P1 |+| P48 | Interactive OpenAPI explorer | P2 |+| P49 | Blog index + content strategy | P2 |+| P50 | SDK docs, per-package CHANGELOGs & examples | P1 |+| P51 | SEO + structured-data audit & internal linking | P2 |+| P52 | `llms.txt` + agent discoverability | P2 |++### G · Testing, CI & quality+| # | Prompt | Priority |+|---|--------|----------|+| P53 | API endpoint test-coverage expansion | P1 |+| P54 | E2E coverage for revenue paths | P1 |+| P55 | Load & stress testing harness | P2 |+| P56 | Lighthouse in CI + perf budgets + RUM | P1 |+| P57 | Typecheck as a hard gate | P2 |+| P58 | Coverage instrumentation & thresholds | P2 |++### H · On-chain & contracts+| # | Prompt | Priority |+|---|--------|----------|+| P59 | Deploy AgentPayments (EVM) multi-chain + wire SDK | P0 |+| P60 | Contract third-party audit prep | P1 |+| P61 | Upgrade-authority migration to multisig/cold keys | P1 |++### I · Ops, deploy & incident response+| # | Prompt | Priority |+|---|--------|----------|+| P62 | Runbooks + incident response + on-call | P0 |+| P63 | Canary/blue-green deploy + automated rollback | P1 |+| P64 | DB migration versioning & safe rollback | P0 |+| P65 | Uptime alerting & escalation | P1 |++---++## Suggested first wave (the P0s)++Land these before anything else — they de-risk money movement, security, and the+ability to recover from incidents:++`P01` `P02` `P03` `P11` `P12` `P13` `P18` `P19` `P22` `P59` `P62` `P64`++---++## Non-negotiables baked into every prompt++These come from `CLAUDE.md` and are restated in each file because each runs fresh:++- **$THREE is the only coin.** CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never name, link, or recommend any other.+- **No mocks, fake data, stubs, TODOs, or commented-out code.** Real APIs, real integrations, finished work.+- **Every state designed** (loading/empty/error/populated), accessible, responsive.+- **Changelog discipline** — user-visible changes get a `data/changelog.json` entry; `npm run build:pages` validates it.+- **Two remotes** — push to both `threeD` and `threews`, only when asked. Never pull/fetch from `threeD`.+- **Concurrent agents share this worktree** — stage explicit paths, re-check `git status` before committing.diff --git a/prompts/production-readiness/P11-ci-dependency-scanning.md b/prompts/production-readiness/P11-ci-dependency-scanning.mdnew file mode 100644index 000000000..dd063bbfe--- /dev/null+++ b/prompts/production-readiness/P11-ci-dependency-scanning.md@@ -0,0 +1,57 @@+# P11 · CI dependency scanning + Dependabot + legacy-peer-deps de-risk++> **Workstream:** Security & compliance · **Priority:** P0 · **Effort:** M · **Depends on:** none++## Before you start+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (surface map).+2. three.ws monorepo: vanilla JS + Vite frontend, Vercel functions in `api/`, Cloudflare workers in `workers/`, tests via `vitest` + Playwright (`npm test`), CI in `.github/workflows/`.+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never reference any other coin.++## Context+- CI lives in a single file, `.github/workflows/ci.yml`. Jobs today: `lint` (`npx eslint .`), `test` (`npx vitest run`), `guards` (`node scripts/check-api-not-bundled.mjs`, `npm run check:images`, `npm run build:pages`), `typecheck` (`npm run typecheck`), `pages` (`npm run test:pages`), `e2e` (`npx playwright test`). All run `npm ci` on Node 24. There is **no** dependency vulnerability scan anywhere.+- Repo root `.npmrc` contains exactly one line: `legacy-peer-deps=true`. This is load-bearing for the workspace install but dangerous — see below.+- This is an npm-workspaces monorepo: 20 workspaces declared in `package.json` (`agent-payments-sdk`, `avatar-sdk`, `mcp-server`, `walk-sdk`, `tour-sdk`, `packages/*`, etc.). `package.json` `engines.node` = `24.x`.+- A real prod outage on 2026-06-11 (465 consecutive 500s, 90 min of failed deploys) was partly caused by `legacy-peer-deps=true`: when `helius-sdk` 3.0 moved `@solana-program/stake` to peerDependencies, npm silently did not install it and every `/api/cron/*` died at module load with `ERR_MODULE_NOT_FOUND`. `scripts/audit-deploy-artifacts.mjs` is the **post-hoc** backstop (runs standalone, as phase 1 of `scripts/build-vercel.mjs`, and via `tests/deploy-artifacts.test.js`): it verifies every non-optional peerDependency in the prod lock tree resolves and every bare import in `api/**/*.js` is declared. There is no CI gate that runs it, and no scan that would have flagged a known-vuln dependency before it shipped.++## Problem / opportunity+Real money rides on this code (the CI header says so). A high/critical CVE in a transitive dependency would ship unflagged today, and `legacy-peer-deps=true` masks broken dependency trees until runtime. We need a gate that (a) fails the build on high/critical advisories, (b) keeps deps patched automatically, and (c) reduces the blast radius of `legacy-peer-deps`.++## Mission+Add a CI dependency-scan job that rejects high/critical vulnerabilities, add Dependabot config for npm + GitHub Actions, and add a CI gate that runs the existing `audit-deploy-artifacts.mjs` peer-dep check so legacy-peer-deps breakage is caught at PR time, not in prod.++## Scope+**In scope:** new `audit` job in `ci.yml`; `.github/dependabot.yml`; wiring `scripts/audit-deploy-artifacts.mjs` into CI; an allowlist mechanism for accepted/unfixable advisories.+**Out of scope:** rewriting dependencies, removing `legacy-peer-deps` outright (document the path; don't break the install), container/Trivy image scanning (no Docker images shipped here).++## Implementation guide+1. **`audit` job in `.github/workflows/ci.yml`.** Mirror the existing job shape (checkout@v4, setup-node@v4 node 24 + `cache: npm`, `npm ci`). Add:+ - `npm audit --audit-level=high` against the production tree. Because workspaces + `legacy-peer-deps` make raw `npm audit` noisy, prefer a deterministic wrapper: add `scripts/audit-deps.mjs` that runs `npm audit --json --omit=dev`, parses `vulnerabilities`, and exits 1 only if any advisory severity is `high` or `critical` AND its module is not in an allowlist. Keep the allowlist in `scripts/audit-deps-allowlist.json` as `{ "<advisoryId-or-ghsa>": { "reason": "...", "expires": "YYYY-MM-DD" } }`; treat an expired entry as not-allowlisted (fail). Print a table of what passed/blocked. Reference how `scripts/audit-deploy-artifacts.mjs` already shells `npm`/`git` via `node:child_process` and reads the lockfile for the style to match.+ - Wire `npm run audit:deps` into `package.json` scripts next to the existing `audit:deploy`.+2. **Run the existing peer-dep backstop in CI.** In the same `audit` job (or the `guards` job), add `- run: node scripts/audit-deploy-artifacts.mjs`. This is the check that would have caught the 2026-06-11 outage. Confirm it runs clean today first (`node scripts/audit-deploy-artifacts.mjs`) so you don't land a red gate; if it flags something real, fix the dep, don't disable the check.+3. **`.github/dependabot.yml`.** Two `package-ecosystem` blocks:+ - `npm`, `directory: "/"`, weekly, grouped minor+patch into one PR (`groups:`), `open-pull-requests-limit: 5`, `versioning-strategy: increase`. Because this is a workspaces root, the single `/` entry covers all workspaces via the root lockfile. Ignore major bumps for the fragile pinned forks (`helius-sdk`, anything under `agent-payments-sdk`'s declared deps) so a surprise major can't auto-merge into the legacy-peer-deps tree.+ - `github-actions`, `directory: "/"`, weekly — keeps `actions/checkout`, `actions/setup-node`, `actions/cache` patched.+4. **De-risk `legacy-peer-deps`.** Do NOT silently remove the `.npmrc` line — it will break `npm ci`. Instead: (a) add a comment to `.npmrc` explaining why it exists and the risk; (b) ensure `scripts/audit-deploy-artifacts.mjs` runs in CI (step 2) so the failure mode it guards is caught pre-merge; (c) in `docs/security.md` or a new `docs/dependency-policy.md`, document the path off legacy-peer-deps (audit which workspace forces it via `npm ls` / `npm install --no-legacy-peer-deps` dry run, list the offending peer conflicts) as a tracked follow-up. Picking the minimal real reduction (e.g. moving the flag from global to only the workspace that needs it, if feasible) is in scope; a full removal is not.+5. **Permissions.** The new job needs only `contents: read` (already the workflow default). Do not add write scopes.++## Definition of done+- [ ] `ci.yml` has an `audit` job that fails on high/critical advisories (not in allowlist) and runs `audit-deploy-artifacts.mjs`.+- [ ] `.github/dependabot.yml` covers npm (`/`) + github-actions, with majors ignored for the fragile forks.+- [ ] `scripts/audit-deps.mjs` + allowlist exist; `npm run audit:deps` works locally and is green on the current tree.+- [ ] `.npmrc` documented; dependency-policy doc records the legacy-peer-deps exit path.+- [ ] Existing tests pass (`npm test`); new logic has new tests (a `tests/audit-deps.test.js` covering allowlist-honored, expired-entry-fails, high-blocks).+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages` (security work counts — tag `security`).+- [ ] `git diff` self-reviewed.++## Verification+- `node scripts/audit-deps.mjs` → exits 0 on clean tree, exits 1 when you temporarily seed a fake high advisory id outside the allowlist.+- `node scripts/audit-deploy-artifacts.mjs` → exits 0.+- `npx vitest run tests/audit-deps.test.js` passes.+- `actionlint .github/workflows/ci.yml` (or paste into GitHub's workflow editor) — no syntax errors; YAML parses.+- Validate `dependabot.yml` against schema (e.g. open a PR and confirm GitHub renders no config error in the Insights → Dependency graph → Dependabot tab).++## Guardrails+- No mocks, fake data, stubs, `TODO`s, or commented-out code. Real APIs; handle errors at boundaries with working fallbacks.+- Stage explicit paths only; concurrent agents share this worktree — re-check `git status` before committing.+- Push only when asked, to BOTH remotes: `git push threeD main` && `git push threews main`. Never pull/fetch from `threeD`.+- Never commit secrets. Watch the `npx vercel build` trap: never commit esbuild-bundled `api/*.js` (check `head -1` for `__defProp`).diff --git a/prompts/production-readiness/P12-ci-sast-secrets-scanning.md b/prompts/production-readiness/P12-ci-sast-secrets-scanning.mdnew file mode 100644index 000000000..3add7f3b0--- /dev/null+++ b/prompts/production-readiness/P12-ci-sast-secrets-scanning.md@@ -0,0 +1,52 @@+# P12 · CI SAST + secret scanning + pre-commit secret hook++> **Workstream:** Security & compliance · **Priority:** P0 · **Effort:** M · **Depends on:** none++## Before you start+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (surface map).+2. three.ws monorepo: vanilla JS + Vite frontend, Vercel functions in `api/`, Cloudflare workers in `workers/`, tests via `vitest` + Playwright (`npm test`), CI in `.github/workflows/`.+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never reference any other coin.++## Context+- CI is one file, `.github/workflows/ci.yml`, with jobs `lint`, `test`, `guards`, `typecheck`, `pages`, `e2e`. The `lint` job runs `npx eslint .` only. There is **no** SAST (no CodeQL, no `eslint-plugin-security`) and **no** secret scanning (no gitleaks/trufflehog) anywhere.+- ESLint is flat-config (`eslint.config.js`, ESLint 10). It scopes first-party root JS and ignores vendored/generated trees (`character-studio/**`, `**/vendor/**`, `chat/**`, `agent-payments-sdk/**`, build output, minified bundles). Rules are mostly `warn` (the file documents a "warn-baseline, ratchet to error" strategy); high-value structural rules (`no-dupe-keys`, `no-func-assign`) are `error`. No security plugin is loaded.+- `.githooks/pre-push` already exists (runs `npm run typecheck`; wired via `git config core.hooksPath .githooks`, set by `npm run setup`). There is no `pre-commit` hook. The hook respects `SKIP_HOOKS=1` and `--no-verify`.+- This repo handles real secrets at runtime (`HELIUS_API_KEY`, `TELEGRAM_BOT_TOKEN`, `THREEWS_SOL_PARENT_SECRET_BASE58`, Privy/JWT signing keys, R2 creds). `api/_lib/http.js` already goes to lengths to keep keyed RPC URLs and device tokens out of logs — but nothing stops a key from being committed in source.++## Problem / opportunity+A committed secret or an injectable code pattern (e.g. unsanitized `child_process`, `eval`, prototype pollution, ReDoS) would ship undetected. SAST + secret scanning are table stakes for a platform moving real money. We add both to CI plus a local pre-commit secret hook so leaks are caught before they ever reach a remote.++## Mission+Add a SAST gate (GitHub CodeQL for JS/TS, plus `eslint-plugin-security` rules in the existing eslint flat config) and a secret-scanning gate (gitleaks) to CI, and add a `.githooks/pre-commit` hook that runs gitleaks on staged changes before commit.++## Scope+**In scope:** new CodeQL workflow; secret-scan job (gitleaks) in CI; `eslint-plugin-security` wired into `eslint.config.js` at warn-then-targeted-error; `gitleaks.toml` config; `.githooks/pre-commit`; updating `npm run setup` docs so the hook is active.+**Out of scope:** rewriting flagged code en masse (fix only true positives you surface; allowlist documented false positives), rotating real secrets (separate ops task), container scanning.++## Implementation guide+1. **CodeQL workflow — `.github/workflows/codeql.yml`.** Use `github/codeql-action` (`init` → `autobuild`/manual → `analyze`) with `languages: javascript-typescript`. Trigger on `pull_request`, `push: branches: [main]`, and a weekly `schedule`. Permissions: `security-events: write`, `contents: read`, `actions: read`. Exclude vendored/generated paths via a `paths-ignore` in a `.github/codeql/codeql-config.yml` that mirrors the `ignores` list in `eslint.config.js` (`character-studio/**`, `**/vendor/**`, `**/dist/**`, `public/scene-studio/libs/**`, `**/*.min.js`, `data/_generated/**`, `src/solana/vanity/wasm/**`). Keep it a separate workflow file (CodeQL conventionally lives apart from `ci.yml`).+2. **`eslint-plugin-security` in `eslint.config.js`.** Add the plugin to the existing flat-config array (it ships a flat preset: `pluginSecurity.configs.recommended`). Install it as a devDependency. Because the repo runs a warn-baseline, land its rules at `warn` first so the gate stays green, then promote the unambiguous, currently-clean ones to `error` (`security/detect-child-process` is high-signal given `audit-deploy-artifacts.mjs`/`check-api-not-bundled.mjs` shell out; `security/detect-non-literal-fs-filename` will be noisy — keep warn). Do not change the existing ignore globs.+3. **Secret-scan job in `.github/workflows/ci.yml`.** Add a `secrets` job: checkout@v4 with `fetch-depth: 0` (gitleaks needs history for `--log-opts`), then `gitleaks/gitleaks-action@v2` (or pin a release and run the binary) over the full repo and the PR diff. Config in `.gitleaks.toml` at repo root: extend the default ruleset, add an `[allowlist]` for known-safe synthetic placeholders this repo uses on purpose — the `$THREE` CA (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) and clearly-synthetic test fixtures like `THREEsynthetic1111…` are public/non-secret and must not trip the scan; allowlist by path for fixture/test dirs and by regex for these tokens. Fail the job on any real finding.+4. **`.githooks/pre-commit`.** Mirror the style of `.githooks/pre-push` (POSIX `sh`, `SKIP_HOOKS=1` + `--no-verify` bypass, clear failure message pointing at the fix). It should run `gitleaks protect --staged --config .gitleaks.toml` (scans only staged changes — fast, pre-commit-appropriate). If the `gitleaks` binary is absent locally, print a one-line install hint and exit 0 (don't block contributors who haven't installed it; CI is the hard gate). Ensure `npm run setup` / `scripts/setup-dev.mjs` still points `core.hooksPath` at `.githooks` (it already does for pre-push — confirm the new hook is picked up automatically since it's the same dir).+5. **Triage.** Run all three locally first. For each true positive, fix it (move a key to env, sanitize a `child_process` arg). For each documented false positive, allowlist it narrowly with a `// eslint-disable-next-line security/... -- reason` or a scoped `.gitleaks.toml` allowlist entry — never blanket-disable.++## Definition of done+- [ ] `codeql.yml` runs CodeQL JS/TS on PR + push + weekly, scoped by `codeql-config.yml`.+- [ ] `ci.yml` has a `secrets` job (gitleaks) that fails on real findings; `$THREE` CA + synthetic fixtures allowlisted.+- [ ] `eslint-plugin-security` wired into `eslint.config.js`; gate stays green; `detect-child-process` at error and clean.+- [ ] `.githooks/pre-commit` runs gitleaks on staged files, bypassable, degrades gracefully when binary missing.+- [ ] Existing tests pass (`npm test`); any code fixed for true positives has/keeps tests.+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages` (security work counts — tag `security`).+- [ ] `git diff` self-reviewed.++## Verification+- `npx eslint .` → no new errors (security plugin loaded; check with a deliberate `child_process` test snippet that it flags, then remove it).+- `gitleaks detect --config .gitleaks.toml --no-banner` → no findings; then add a fake `AKIA...` string to a scratch file and confirm it's caught, and confirm the `$THREE` CA does NOT trip it.+- `gitleaks protect --staged` via the pre-commit hook: stage a fake secret → commit blocked; `SKIP_HOOKS=1 git commit` → bypasses.+- Paste `codeql.yml` and the edited `ci.yml` through `actionlint` (or GitHub's editor) — valid.++## Guardrails+- No mocks, fake data, stubs, `TODO`s, or commented-out code. Real APIs; handle errors at boundaries with working fallbacks.+- Stage explicit paths only; concurrent agents share this worktree — re-check `git status` before committing.+- Push only when asked, to BOTH remotes: `git push threeD main` && `git push threews main`. Never pull/fetch from `threeD`.+- Never commit secrets. Watch the `npx vercel build` trap: never commit esbuild-bundled `api/*.js` (check `head -1` for `__defProp`).diff --git a/prompts/production-readiness/P18-subscriptions-timepass-settlement.md b/prompts/production-readiness/P18-subscriptions-timepass-settlement.mdnew file mode 100644index 000000000..d1a3e3801--- /dev/null+++ b/prompts/production-readiness/P18-subscriptions-timepass-settlement.md@@ -0,0 +1,54 @@+# P18 · Subscriptions & Time-Pass Settlement++> **Workstream:** Monetization (revenue engine) · **Priority:** P0 · **Effort:** L · **Depends on:** none++## Before you start+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (surface map). Note the $THREE-only rule and the two coin-agnostic exceptions.+2. three.ws monorepo: vanilla JS + Vite frontend, Vercel functions in `api/`, tests via `vitest` + Playwright (`npm test`), dev server `npm run dev`.+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.++## Context+The skill marketplace already advertises three purchase shapes per listing but only one is fully wired:++- `api/x402/skill-marketplace.js` — the Bazaar-cataloged listing endpoint. `rowToListing()` (line 103) surfaces `trial_uses`, `time_pass_hours`, and `time_pass_amount` columns from `agent_skill_prices`. **These terms are advertised but never enforced into a grant.**+- `api/_lib/skill-access.js` — `hasSkillAccess(userId, agentId, skill)` is the single source of truth for "may this user run this skill". It already honors: a confirmed `skill_purchases` row (with `valid_until` time-pass expiry, lines 50-57), an agent-level `user_agent_subscriptions` flat sub, a `creator_subscriptions`→`subscription_plans.included_skills` tier sub, and a trial via `consumeTrialUse()`. The read path for time-passes exists; **the write/grant path that sets `valid_until` from `time_pass_hours` does not.**+- `api/_lib/purchase-confirm.js` — confirms a skill/asset purchase, accrues the marketplace split + referral commission, and writes the `skill_purchases` row. This is where a confirmed payment becomes a grant.+- `api/cron/[name].js` → `handleRunSubscriptions` (line 2598) charges EVM USDC recurring subs via `agent_subscriptions` + `agent_delegations` (Base/Sepolia EIP-7710 delegation rail). `handleProcessSubscriptions` (line 2951) charges `creator_subscriptions` priced in `subscription_plans.price_usd`, counting `subscription_payments` failures to flip to `past_due` after 3. Both crons exist; quota tracking on a granted pass does not.+- `api/_lib/token/payments.js` — `verifyAndSettlePayment()` / `recordAllowancePayment()` settle into `token_payments` with UNIQUE(nonce) + UNIQUE(tx_signature) idempotency. `creatorEarnings()` reads the `seller` split leg back out. The marketplace split policy is `marketplace_sale` (90% seller / 5% treasury / 5% rewards) in `api/_lib/token/config.js`.+- `vercel.json` schedules `run-distribute-payments` (`30 * * * *`), `expire-pending-purchases` (`*/5 * * * *`), etc. **There is no cron entry for `run-subscriptions` or `process-subscriptions`** — the handlers are reachable by dispatch but unscheduled.++## Problem / opportunity+A creator can set a 24h `time_pass_hours` + `time_pass_amount` on a listing, the marketplace advertises it, an agent pays it — and nothing grants a time-boxed window or tracks remaining quota. Time-pass terms are decorative. Recurring subscription handlers exist but aren't on a schedule, so renewals never fire in production. The hold-or-pay economy is half-built: the read side checks expiry the write side never sets.++## Mission+Make time-passes and recurring subscriptions real end to end: a paid time-pass becomes a `valid_until`-bounded grant with optional per-pass call quota; recurring subs charge, renew, and expire on a schedule; every grant and charge is idempotent and settles through the existing `token_payments` ledger.++## Scope+**In scope:** time-pass purchase→grant→quota; quota decrement at the skill-execution boundary; recurring `creator_subscriptions` + `agent_subscriptions` renewal/expiry on a cron schedule; idempotent settlement; changelog entry.+**Out of scope:** new pricing UI redesign (a minimal "buy time-pass" affordance on the existing listing card is fine), new chains, EVM delegation rail changes beyond what `handleRunSubscriptions` already does.++## Implementation guide+1. **Schema (`api/_lib/migrations/<date>_timepass-quota.sql`).** Add to `skill_purchases` (if absent): `pass_kind` enum/text (`one_time` | `time_pass`), `calls_total int null`, `calls_used int not null default 0`. Add a partial UNIQUE index keyed on the settling payment reference (e.g. `token_payments` nonce or `skill_purchases.payment_ref`) so a replayed settlement can't mint two grants. Reuse the existing `valid_until`.+2. **Grant on confirm (`api/_lib/purchase-confirm.js`).** When the confirmed listing row has `time_pass_hours > 0`, set `status='confirmed'`, `pass_kind='time_pass'`, `valid_until = now() + (time_pass_hours || ' hours')::interval`, and `calls_total` from a new optional `time_pass_calls` column (null = unlimited within the window). Keep the existing marketplace split + referral accrual. Make the grant write idempotent on the payment reference — re-running confirm for the same settled payment must not extend the window or reset quota.+3. **Quota enforcement (`api/_lib/skill-access.js`).** In `hasSkillAccess`, when a confirmed `time_pass` grant is matched, also return `calls_remaining` (null = unlimited). Add `consumeTimePassUse(userId, agentId, skill)` mirroring `consumeTrialUse`: atomic `UPDATE … SET calls_used = calls_used + 1 WHERE status='confirmed' AND pass_kind='time_pass' AND valid_until > now() AND (calls_total IS NULL OR calls_used < calls_total) RETURNING calls_total - calls_used`. The skill-execution endpoints that already call `consumeTrialUse` on success must call this on a time-pass hit. Expiry is honored by the existing `valid_until` check; quota-exhausted returns `owned:false, reason:'pass_exhausted'`.+4. **Settlement path.** A time-pass is a `marketplace_sale` priced at `time_pass_amount` atomics. Route it through the same quote→`verifyAndSettlePayment` path used for a one-time skill purchase (the existing `api/payments/purchase-skill.js` / `api/_lib/x402.js` flow), with `refType='time_pass'`, `refId=<purchase id>` so `creatorEarnings()` attributes it. Never invent a second settlement path.+5. **Recurring renewal/expiry.** Confirm `handleProcessSubscriptions` advances `current_period_end` by the plan period on a successful charge and flips to `expired`/`past_due` correctly; add an explicit expiry sweep (`UPDATE creator_subscriptions SET status='expired' WHERE status IN ('active','past_due') AND current_period_end < now() - grace`). Add both jobs to `vercel.json` crons: `process-subscriptions` hourly (`5 * * * *`), `run-subscriptions` hourly (`15 * * * *`). Keep the `requireCron` constant-time secret check — never weaken it.+6. **Frontend.** On the listing/skill card (dashboard skill view), when `time_pass_hours` is set show a "Buy <N>h pass — <amount> $THREE" action and, post-purchase, a live "expires in / N calls left" badge read from `hasSkillAccess`. Design loading, empty (no pass), active, and expired states.++## Definition of done+- [ ] Time-pass purchase grants a `valid_until` window + optional call quota; expiry and quota-exhaustion both deny with distinct reasons.+- [ ] `process-subscriptions` + `run-subscriptions` are scheduled in `vercel.json` and renew/expire correctly.+- [ ] Money paths covered by tests (verify, settle, split, idempotency); `npm test` passes.+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages`.+- [ ] `git diff` self-reviewed; revenue math validated.++## Verification+- `vitest run` a new `tests/skill-access-timepass.test.js`: grant a pass, assert `calls_remaining` counts down, assert deny after `valid_until` and after quota exhaustion, assert double-confirm of one settled payment yields one grant.+- `curl` the marketplace listing → confirm `time_pass_hours`/`time_pass_amount` surface; drive a real `purchase-skill` → confirm flow on devnet and assert one `token_payments` row + one `skill_purchases` grant.+- Invoke `/api/cron/process-subscriptions` with the cron bearer; assert a due sub advances its period and a 3-fail sub flips `past_due`.++## Guardrails+- No mocks/fake data. Real on-chain verification + settlement. Idempotent (no double-charge / double-payout).+- $THREE only in copy; never hardcode a non-$THREE mint.+- Stage explicit paths; re-check `git status` before commit. Push only when asked, to BOTH remotes (`threeD`, `threews`).+- Watch the `npx vercel build` trap: never commit bundled `api/*.js`.diff --git a/prompts/production-readiness/P19-agent-revenue-payouts-ledger.md b/prompts/production-readiness/P19-agent-revenue-payouts-ledger.mdnew file mode 100644index 000000000..10d281b59--- /dev/null+++ b/prompts/production-readiness/P19-agent-revenue-payouts-ledger.md@@ -0,0 +1,53 @@+# P19 · Agent Revenue Ledger & Automated Payouts++> **Workstream:** Monetization (revenue engine) · **Priority:** P0 · **Effort:** L · **Depends on:** P18++## Before you start+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (surface map). Note the $THREE-only rule and the two coin-agnostic exceptions.+2. three.ws monorepo: vanilla JS + Vite frontend, Vercel functions in `api/`, tests via `vitest` + Playwright (`npm test`), dev server `npm run dev`.+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.++## Context+A marketplace sale already routes 90% to the seller, but earnings live in two disconnected places and the per-agent rollup + automated payout are missing:++- `api/_lib/token/config.js` — `SPLIT_POLICIES.marketplace_sale` = `seller 9000 / treasury 500 / rewards 500` bps. `applySplit()` distributes atomics with the remainder to the highest-bps leg (no dust). $THREE sales settle this way.+- `api/_lib/token/payments.js` — `settlePayment()` writes `token_payments` with a `splits` jsonb array (`{role,bps,address,atomics}`), `ref_type`, `ref_id`, UNIQUE(nonce)+UNIQUE(tx_signature). `creatorEarnings({ sellerWallet })` already sums the `seller` leg across all sales via `splits @> [{role:'seller',address}]` jsonb containment — this is the $THREE-settled earnings read. It's a per-WALLET read with no per-AGENT attribution.+- `api/_lib/agent-wallet.js` — `triggerSkillPayment()` is the EVM rail: it charges an agent for a paid skill, paying `marketplace_skills.price_per_call_usd` to the author's `user_wallets` primary EVM address via `delegatedSpend()`, recording in `agent_payments` (status pending→confirmed/failed). A separate, USD/wei-denominated revenue stream from the $THREE rail.+- `api/agents/[id].js` dispatches `sub === 'wallet' && action === 'withdraw'` to the wallet handler; `api/agents/solana-wallet.js` owns the custodial Solana wallet (provision, balance, spend-limit-guarded withdraw via `agent-trade-guards.js`). `getOrCreateAgentSolanaWallet` / `ensureAgentWallet` provision custodial keys.+- Existing payout plumbing to reuse, not reinvent: `api/cron/[name].js` → `handleProcessWithdrawals` (line 3191, also aliased `monetization-payouts`) already pulls `agent_withdrawals` rows (status `pending`→`processing`→`completed`), pages ops on rows stranded in `processing` >15m (no blind retry — double-pay risk), and sends via `transferSolanaUSDC` / `sendEvmUsdc`. `api/_lib/monetization.js`, `api/billing/withdrawals/`, `api/monetization/withdrawals.js`, and migration `20260621120000_revenue-integrity.sql` define the withdrawal model.++## Problem / opportunity+A seller's $THREE earnings are computable only per-wallet (`creatorEarnings`), but the product surface is the agent. There's no per-agent earnings rollup, no "this agent earned X this week" view, and no automated payout that sweeps an agent's accrued seller-leg balance to its owner. The EVM `agent_payments` stream and the $THREE `token_payments` stream never reconcile into one earnings number. Creators can't see or collect what their agents made without manual SQL.++## Mission+Ship a per-agent earnings ledger (a materialized rollup keyed by agent, sourced from the existing settle ledgers), a payout that sweeps accrued earnings to the owner through the existing `agent_withdrawals` rail, and an agent-earnings dashboard view — all idempotent, no second source of truth for the underlying sales.++## Scope+**In scope:** per-agent earnings rollup reads, an agent-earnings API + dashboard panel, a payout that creates `agent_withdrawals` rows from accrued unpaid earnings and lets the existing `handleProcessWithdrawals` cron settle them, idempotency so a sale is paid out once.+**Out of scope:** changing split ratios, new withdrawal transport (reuse `transferSolanaUSDC`/`sendEvmUsdc`), the buyback/distribute loop (`run-distribute-payments` is separate).++## Implementation guide+1. **Attribution key.** Every settle write must carry the agent. Audit the marketplace settle call sites (`api/payments/purchase-confirm.js`, `api/_lib/x402.js`, the P18 time-pass path) and ensure `ref_type` distinguishes the sale kind and `ref_id` resolves to an agent. Add `agent_id` to the quote/settle metadata so `token_payments` can be grouped by agent without re-parsing `splits`. Backfill via the existing `ref_id`→agent mapping where derivable.+2. **Ledger read (`api/_lib/token/payments.js`).** Add `agentEarnings({ agentId, sellerWallet, limit, before })` next to `creatorEarnings`: sum the `seller` leg for sales attributed to this agent (join on the new `agent_id` or via `ref_id`). Return `{ total_atomics, paid_atomics, unpaid_atomics, sale_count, mint, decimals, items[] }`. `paid_atomics` is the sum already covered by `agent_withdrawals` so `unpaid_atomics` is the sweepable balance.+3. **Reconcile EVM stream.** Have `agentEarnings` also surface the `agent_payments` (EVM) confirmed inflows for the agent so the dashboard shows both rails, clearly labelled by currency ($THREE vs USDC). Do not merge the numbers — show both, never invent a converted total.+4. **Payout creation (`api/_lib/monetization.js` or new `api/agents/[id]/payout.js`).** Owner-authorized (session/bearer + agent-ownership check, mirror `skill-prices.js`). Computes `unpaid_atomics`, applies the agent's spend limits (`agent-trade-guards.js`), inserts an `agent_withdrawals` row (status `pending`, destination = owner's payout wallet from `billing/payout-wallets`). Idempotency: a `UNIQUE` claim keyed on the agent + a settlement watermark (e.g. last paid `token_payments.created_at`) so two concurrent payout calls create one withdrawal. The existing `handleProcessWithdrawals` cron settles it — do not send funds inline.+5. **Payout cron.** Add an optional auto-sweep: extend `handleProcessWithdrawals` (or a thin sibling) to also enqueue payouts for agents whose `unpaid_atomics` crosses a per-agent threshold. Reuse the stranded-row ops alert and the no-blind-retry rule already in that handler. Schedule it in `vercel.json` if not already covered by `monetization-payouts`.+6. **Dashboard (`src/dashboard-next/pages/monetize.js`).** It already fetches `/api/billing/revenue`, `/api/billing/withdrawals`, `/api/billing/payout-wallets`, `/api/billing/summary`. Add a per-agent earnings card: lifetime + window earned, unpaid balance, a "Withdraw to owner wallet" action calling the payout endpoint, and a recent-sales table from `agentEarnings.items`. Design loading (skeleton), empty (no sales → "list a skill to start earning"), populated, and in-flight-withdrawal states.++## Definition of done+- [ ] `agentEarnings` returns correct total / paid / unpaid sourced from the existing ledgers (no new sales table).+- [ ] Payout creates exactly one `agent_withdrawals` row per sweepable balance; the existing cron settles it; a sale is paid out at most once.+- [ ] Money paths covered by tests (verify, settle, split, idempotency); `npm test` passes.+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages`.+- [ ] `git diff` self-reviewed; revenue math validated (sum of seller legs == total earned; unpaid == total − paid).++## Verification+- `vitest run tests/agent-earnings.test.js`: seed `token_payments` with seller legs for an agent, assert totals; create a payout twice concurrently, assert one `agent_withdrawals` row; mark it completed, assert `unpaid_atomics` drops to 0.+- `npm run dev`, open `/dashboard/monetize` for an agent with sales: network tab shows real `agentEarnings` data; trigger withdraw, confirm a `pending` row appears.+- Invoke `/api/cron/process-withdrawals` (cron bearer) on devnet; confirm it claims the row, settles, and writes `completed` with a tx signature.++## Guardrails+- No mocks/fake data. Real on-chain verification + settlement. Idempotent (no double-charge / double-payout).+- $THREE only in copy; never hardcode a non-$THREE mint.+- Stage explicit paths; re-check `git status` before commit. Push only when asked, to BOTH remotes (`threeD`, `threews`).+- Watch the `npx vercel build` trap: never commit bundled `api/*.js`.diff --git a/prompts/production-readiness/P59-deploy-agentpayments-evm.md b/prompts/production-readiness/P59-deploy-agentpayments-evm.mdnew file mode 100644index 000000000..3f207109b--- /dev/null+++ b/prompts/production-readiness/P59-deploy-agentpayments-evm.md@@ -0,0 +1,91 @@+# P59 · Deploy AgentPayments across EVM chains++> **Workstream:** On-chain & contracts · **Priority:** P0 · **Effort:** L · **Depends on:** none++## Before you start+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (on-chain section).+2. three.ws monorepo: EVM contracts via Foundry in `contracts/`; Solana programs via Anchor in `contracts/agent-invocation/` and `contracts/skill-license/`. EVM SDK addresses live in `agent-payments-sdk/src/evm/`. ERC-8004 deploy metadata in `contracts/` + `api/_lib/erc8004-chains.js`.+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never reference any other coin/token.++## Context+`contracts/src/AgentPayments.sol` (406 lines) is the EVM port of the Solana `pump_agent_payments` program. It is the on-chain engine behind three.ws **agent tokens**: a payer pays an agent in any ERC-20 (or native via the EIP-7528 sentinel `0xEeee…EEeE`), `distributePayments` splits the vault by `buybackBps`, the agent authority `withdraw`s its share, and `buybackTrigger` (owner-only) swaps the buyback slice into the agent token via an allow-listed router and burns it to `0x…dEaD`.++State so far:+- **Tested, not deployed.** `contracts/test/AgentPayments.t.sol` — 16 tests, all passing (`forge test --match-contract AgentPaymentsTest`). Foundry profile in `contracts/foundry.toml`: solc `0.8.24`, optimizer 200 runs, `via_ir = false`.+- **Deploy script ready:** `contracts/script/DeployAgentPayments.s.sol:DeployAgentPayments` — `new AgentPayments(owner)` where `owner = vm.envOr("AGENT_PAYMENTS_OWNER", msg.sender)`. Owner is the protocol/global buyback authority — must be the platform multisig in production, never a hot EOA.+- **CREATE2 deployer exists:** `ThreeWSFactory` at `0x00000000d49195ae81759cd247cfedd9d0b479df` (verified on Base/BSC/Arbitrum, bytecode SHA-256 `424e78aad2b19a37…`). Because `AgentPayments`'s constructor takes only `owner` (no chain-specific immutable), a CREATE2 deploy with a shared salt yields the **same** address on every chain — unlike `ThreeWSPayments`, whose per-chain USDC immutable broke address parity (`contracts/DEPLOYMENTS.md`).+- **SDK is waiting:** `agent-payments-sdk/src/evm/addresses.ts` defines `EVM_CHAINS` for chain IDs `1, 8453, 42161, 137, 56, 43114` with every `agentPayments` set to `UNDEPLOYED` (= `ZERO_ADDRESS`). `isAgentPaymentsDeployed(chainId)` returns `false` everywhere, and `new EvmAgent(token, chainId)` throws `"AgentPayments contract is not deployed on chain N"` at construction.+- Full guide already written: `contracts/AGENT_PAYMENTS.md`. Deployment ledger: the **AgentPayments** table in `contracts/DEPLOYMENTS.md` (all rows `TODO`).++## Problem / opportunity+The entire EVM agent-token path is dark. The SDK client (`EvmAgent`, `EvmAgentOffline`, `AGENT_PAYMENTS_ABI`) ships, but every call throws because no contract exists on-chain. Deploying once per chain, bytecode-verifying, allow-listing the buyback router, and filling six addresses into the SDK flips EVM agent payments live across Base, Arbitrum, BSC, Polygon, Ethereum, and Avalanche.++## Mission+Deploy `AgentPayments` to all six SDK-supported EVM chains (testnet first, then mainnet), bytecode-verify each, allow-list the canonical swap router per chain, wire every address into the SDK, record each deployment, and announce it in the changelog.++## Scope+**In scope:** Testnet dry-run (Base Sepolia + at least one other testnet); mainnet deploys to chains 1/8453/42161/137/56/43114; explorer bytecode verification; `setRouterAllowed` per chain; updating `agent-payments-sdk/src/evm/addresses.ts` + SDK rebuild; filling the `contracts/DEPLOYMENTS.md` AgentPayments table; changelog entry.++**Out of scope:** Any Solana-side work (the Solana path binds to pump.fun's live `AgenTMiC2…` — no deploy needed). Changing the contract logic. ERC-8004 registry redeploys.++## Implementation guide+1. **Decide on CREATE2 vs. plain `new`.** Prefer CREATE2 via `ThreeWSFactory` for one identical address on all six chains — operationally cleaner and matches the existing factory pattern. Compute the init code as `type(AgentPayments).creationCode` ABI-encoded with the `owner` constructor arg; grind/choose a salt and call `factory.predict(salt, initCodeHash)` to confirm the cross-chain address before broadcasting. If you instead use plain `new` (script as-is), addresses will differ per chain (nonce-dependent) — that is acceptable, just record each.+2. **Install + sanity check.**+ ```bash+ curl -L https://foundry.paradigm.xyz | bash && foundryup+ cd contracts && cp .env.example .env+ # Fill DEPLOYER_PK (gas EOA), AGENT_PAYMENTS_OWNER (platform multisig),+ # BASESCAN_API_KEY / per-chain scan keys, and RPC URLs.+ forge test --match-contract AgentPaymentsTest # expect 16 passing+ ```+3. **Testnet dry-run first** (never mainnet before testnet — Guardrails):+ ```bash+ source .env+ forge script script/DeployAgentPayments.s.sol:DeployAgentPayments \+ --rpc-url $BASE_SEPOLIA_RPC_URL --private-key $DEPLOYER_PK --broadcast --verify+ ```+ Note: `foundry.toml` only declares `base_sepolia` / `base` rpc endpoints + etherscan keys. Add `[rpc_endpoints]` and `[etherscan]` entries for arbitrum, polygon, bsc, ethereum, avalanche before mainnet, or pass `--rpc-url`/`--verifier-url`/`--etherscan-api-key` inline.+4. **Mainnet, one per chain** (swap `--rpc-url`):++ | Chain | Chain ID | USDC (from `addresses.ts`) | Canonical router to allow-list |+ | --- | --- | --- | --- |+ | Base | 8453 | `0x8335…02913` | chain's 0x Exchange Proxy / Uniswap Universal Router |+ | Arbitrum One | 42161 | `0xaf88…5831` | same family |+ | Polygon | 137 | `0x3c49…3359` | same family |+ | BNB Smart Chain | 56 | `0x8AC7…580d` | same family |+ | Ethereum | 1 | `0xA0b8…eB48` | same family |+ | Avalanche | 43114 | `0xB97E…8a6E` | same family |++ ```bash+ forge script script/DeployAgentPayments.s.sol:DeployAgentPayments \+ --rpc-url $BASE_RPC_URL --private-key $DEPLOYER_PK --broadcast --verify+ ```+5. **Allow-list the buyback router per chain.** Buybacks revert with `RouterNotAllowed` until set; the contract also forbids the currency/agent token as the "router" (closes the only path to abuse payer `maxUint256` allowances). Use the **real canonical** DEX router for each chain — never a synthetic address here (it is a live mainnet integration), but never market any non-$THREE mint.+ ```bash+ cast send <AGENT_PAYMENTS_ADDR> "setRouterAllowed(address,bool)" <ROUTER> true \+ --rpc-url $BASE_RPC_URL --private-key $DEPLOYER_PK+ ```+6. **Wire the SDK.** In `agent-payments-sdk/src/evm/addresses.ts`, replace `UNDEPLOYED` with the deployed address for each of the six chains, then:+ ```bash+ cd agent-payments-sdk && npm run build+ ```+ Confirm `isAgentPaymentsDeployed(8453) === true` and `new EvmAgent(token, 8453)` no longer throws.+7. **Record + announce.** Fill the AgentPayments table in `contracts/DEPLOYMENTS.md` (address, chain ID, owner, routers allow-listed, tx hash) per chain. Append a `data/changelog.json` entry (tags: `infra`, `sdk`) — holder-readable: EVM agent payments are live across six chains — then `npm run build:pages`.++## Definition of done+- [ ] Contract tests pass (`forge test` / `anchor test`); changes documented.+- [ ] Deployed addresses recorded + bytecode-verified where applicable; SDK address files updated.+- [ ] User-visible/holder-relevant → `data/changelog.json` entry + `npm run build:pages`.+- [ ] `git diff` self-reviewed.++## Verification+- `forge test --match-contract AgentPaymentsTest` — 16 passing.+- Per chain: `cast code <ADDR> --rpc-url <RPC>` returns non-empty runtime bytecode; explorer shows "Contract Source Code Verified".+- On-chain read: `cast call <ADDR> "allowedRouters(address)(bool)" <ROUTER>` → `true`; `cast call <ADDR> "owner()(address)"` → the multisig.+- SDK roundtrip: in `agent-payments-sdk`, construct `new EvmAgent(<$THREE-or-synthetic-token>, 8453)` and call a read (`getAgentConfig`) against the live contract — it must return without throwing the "not deployed" error.+- After all six rows are filled, confirm no `UNDEPLOYED` remains in `addresses.ts` and `dist/` rebuilt.++## Guardrails+- No mocks. Real testnet first, then mainnet. Never paste a real third-party mint/creator/holder address; use $THREE CA or a synthetic placeholder.+- Never commit private keys/secrets. Stage explicit paths; re-check `git status`. Push only when asked, to BOTH remotes.+- Treat upgrade authority and minter keys as secrets; document rotation. `AGENT_PAYMENTS_OWNER` must be the platform multisig, not the deployer EOA — record which address owns each deployment.diff --git a/prompts/production-readiness/P60-contract-audit-prep.md b/prompts/production-readiness/P60-contract-audit-prep.mdnew file mode 100644index 000000000..f47f06ad4--- /dev/null+++ b/prompts/production-readiness/P60-contract-audit-prep.md@@ -0,0 +1,71 @@+# P60 · External contract audit package++> **Workstream:** On-chain & contracts · **Priority:** P1 · **Effort:** L · **Depends on:** P59 (AgentPayments deployed/recorded)++## Before you start+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (on-chain section).+2. three.ws monorepo: EVM contracts via Foundry in `contracts/`; Solana programs via Anchor in `contracts/agent-invocation/` and `contracts/skill-license/`. EVM SDK addresses live in `agent-payments-sdk/src/evm/`. ERC-8004 deploy metadata in `contracts/` + `api/_lib/erc8004-chains.js`.+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Never reference any other coin/token.++## Context+The platform's on-chain surface has strong in-house tests but **no external audit**. The contracts under audit:++**EVM (Foundry, `contracts/`, solc 0.8.24, optimizer 200):**+- `src/AgentPayments.sol` (406 LOC) — agent-token payment/buyback engine; `ReentrancyGuard` + `Ownable`; owner = global buyback authority; per-agent authority for withdraw/config; router allow-list; invoice replay guard. Tests: `test/AgentPayments.t.sol` (16).+- `src/IdentityRegistry.sol` (292) — ERC-8004 identity NFT. Live on mainnet at `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` (CREATE2). Tests: `test/IdentityRegistry.t.sol` (11).+- `src/ReputationRegistry.sol` (214) — one score per (reviewer, agent). Live at `0x8004BAa17C55a88189AE136b182e5fdA19dE9b63`. Tests (7).+- `src/ValidationRegistry.sol` (163) — validator-attested pass/fail; testnet live `0x8004Cb1BF31DAf7788923b405b754f57acEB4272`, mainnet pending. Tests (7).++**Solana (Anchor, `contracts/`):**+- `agent-invocation/src/lib.rs` (129) — program `AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo`. Non-trust-bearing: emits `SkillInvoked`; both agent accounts are constrained PDAs (`[AGENT_SEED, authority]`), length-bounds on `skill_name`/`parameters`.+- `skill-license/src/lib.rs` (464) — program `EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8`. Singleton `Marketplace` (admin `authority` + rotatable `minter`); `mint_skill_license` locks supply at 1 and removes mint authority (keeps freeze authority for revoke); `set_minter`, `revoke_skill_license` (freeze-based), `burn_skill_license`. Deploy/key model in `skill-license/DEPLOYMENT.md`.++Existing threat material: `specs/SECURITY.md` (vectors V1–V10 with status, several **OPEN** — notably V8 NSFW moderation, V4 validator key expiry) and its governance roadmap (registry owner is still the deployer EOA; migrate to a 3-of-5 Safe before public registration).++## Problem / opportunity+In-house tests prove the happy path and known edge cases, but external capital and serious integrators expect a third-party audit. Auditors lose days reconstructing scope, architecture, invariants, and known risks from raw source. A clean, complete audit package shortens the engagement, lowers cost, and surfaces gaps before the auditor (or an attacker) does.++## Mission+Assemble a hand-off-ready external audit package: scope manifest, architecture overview, invariant catalog, known-risk register, test/coverage report, and threat model — plus a fixes tracker the team and auditor share. Do not change contract logic; this is documentation + measurement.++## Scope+**In scope:** A new `docs/audit/` (or `contracts/audit/`) package: `SCOPE.md`, `ARCHITECTURE.md`, `INVARIANTS.md`, `KNOWN_RISKS.md`, `THREAT_MODEL.md` (consolidating `specs/SECURITY.md` V1–V10 + Solana/EVM-specific vectors), `COVERAGE.md` (real `forge coverage` + `anchor test` output), and `FINDINGS.md` fixes tracker. Pin exact commit, compiler versions, deployed addresses (from `contracts/DEPLOYMENTS.md`).++**Out of scope:** Fixing findings (that becomes follow-up tasks tracked in `FINDINGS.md`); engaging the auditor; changing contract behavior; new features.++## Implementation guide+1. **Pin the artifact.** Record the audit commit hash, solc `0.8.24`/optimizer 200 (from `foundry.toml`), Anchor/Rust toolchain versions, and the live + pending deployed addresses (pull from `contracts/DEPLOYMENTS.md`, `api/_lib/erc8004-chains.js`, and `agent-payments-sdk/src/evm/addresses.ts` after P59).+2. **`SCOPE.md`** — table of every file in scope with LOC and one-line purpose: the four EVM `src/*.sol`, the two Anchor `lib.rs`. Explicitly mark out-of-scope: SDK TS, `api/`, `ThreeWSFactory.sol` (already verified, trivial CREATE2 wrapper), `ThreeWSPayments.sol` (separate x402 receiver). Note which contracts are already live mainnet vs. testnet-only vs. undeployed.+3. **`ARCHITECTURE.md`** — for each contract: roles/authorities, state layout, external entrypoints, trust boundaries, and the off-chain components that call it (e.g. `AgentPayments` ↔ `EvmAgent`; `ValidationRegistry` ↔ platform validator key + `recordValidation`; `skill_license` ↔ backend `SKILL_LICENSE_MINTER_KEY`). Draw the AgentPayments money flow: `acceptPayment → distributePayments → {buybackTrigger | withdraw}`.+4. **`INVARIANTS.md`** — enumerate what must always hold, e.g.:+ - AgentPayments: `paymentVault + Σ(buybackVault, withdrawVault distributed)` conserves received funds; an invoice ID settles at most once (`isInvoicePaid`); `buybackTrigger` only ever calls allow-listed routers and leaves zero standing allowance; only `authority` withdraws; balance-diff accounting never over-credits (fee-on-transfer safe).+ - skill_license: supply locked at exactly 1 post-mint; only `marketplace.minter` mints; only admin `authority` rotates minter; revoke uses retained freeze authority only.+ - Registries: one ReputationRegistry score per (reviewer, agent); only allow-listed validators write ValidationRegistry. Map each invariant to the test(s) that exercise it (or flag "no direct test").+5. **`THREAT_MODEL.md`** — fold in `specs/SECURITY.md` V1–V10 verbatim by reference, then add contract-level vectors auditors expect: reentrancy on the three `nonReentrant` paths, owner-key compromise blast radius (AgentPayments owner can trigger arbitrary buybacks on allow-listed routers), router allow-list poisoning, Solana account-substitution / missing-signer / arithmetic, IDL/`declare_id` drift. State each vector's current mitigation and residual risk.+6. **`KNOWN_RISKS.md`** — the honest register: registry owner is still the deployer EOA (governance roadmap → 3-of-5 Safe); upgrade authority migration pending (see the multisig task); validator keys have no on-chain expiry (V4 OPEN); NSFW moderation hook unwired (V8 OPEN). Disclose these up front so the auditor doesn't "discover" them as findings.+7. **`COVERAGE.md`** — run and paste real numbers:+ ```bash+ cd contracts && forge coverage --report summary+ cd contracts/agent-invocation && anchor test+ cd contracts/skill-license && anchor test+ ```+ Note any contract/branch below a target threshold and list the missing cases as pre-audit test debt.+8. **`FINDINGS.md`** — empty tracker with the format the auditor will fill: ID, severity (Critical/High/Medium/Low/Info), title, location, status (Open/Fixed/Acknowledged), fix commit. Pre-seed it with the self-identified items from `KNOWN_RISKS.md` marked `Acknowledged`.+9. **Changelog?** This is internal audit prep — **no `data/changelog.json` entry** unless a user-visible change ships (per CLAUDE.md, internal-only chores get none). If a fix from `FINDINGS.md` later changes behavior, that fix's task adds the entry.++## Definition of done+- [ ] Contract tests pass (`forge test` / `anchor test`); changes documented.+- [ ] Deployed addresses recorded + bytecode-verified where applicable; SDK address files updated.+- [ ] User-visible/holder-relevant → `data/changelog.json` entry + `npm run build:pages`.+- [ ] `git diff` self-reviewed.++## Verification+- `forge test` and both `anchor test` suites green; `forge coverage --report summary` produces the numbers pasted in `COVERAGE.md`.+- Every contract listed in `SCOPE.md` exists at the stated path/LOC; every address in the package resolves on-chain (`cast code` / `solana program show`).+- Cross-check: every `specs/SECURITY.md` vector appears in `THREAT_MODEL.md`; every OPEN status appears in `KNOWN_RISKS.md`.+- A peer skim of the package can reconstruct scope + invariants without opening the source.++## Guardrails+- No mocks. Real testnet first, then mainnet. Never paste a real third-party mint/creator/holder address; use $THREE CA or a synthetic placeholder.+- Never commit private keys/secrets. Stage explicit paths; re-check `git status`. Push only when asked, to BOTH remotes.+- Treat upgrade authority and minter keys as secrets; document rotation. The audit package names key *roles and rotation procedures*, never key material.diff --git a/prompts/production-ready/24-sdk-publishing-and-docs.md b/prompts/production-ready/24-sdk-publishing-and-docs.mdnew file mode 100644index 000000000..01bee2b85--- /dev/null+++ b/prompts/production-ready/24-sdk-publishing-and-docs.md@@ -0,0 +1,55 @@+# 24 — SDK publishing & docs++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 2 — Product surface completeness+**Owns:** all published packages — `avatar-sdk/`, `walk-sdk/`, `tour-sdk/`, `page-agent-sdk/`, `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`, `agent-protocol-sdk/`, `agent-ui-sdk/`, `packages/*`.+**Depends on:** `15`, `18`, `19`, `21`, `23`. Pairs with `34`.++## Why this matters for $1B+Every SDK someone installs is a distribution endpoint and a lock-in surface. A+platform valued at $1B has SDKs that "just work" — installable, typed, documented,+versioned, with copy-paste examples. Developer trust is earned in the first 5 minutes.++## Map+- npm workspaces + top-level SDKs (see `STRUCTURE.md`). Publish scripts:+ `publish:packages`(`:dry`), `publish:lib`, `publish:mcp`(`:dry`), `release:lib`.+ Promotion path + publishing notes in `STRUCTURE.md`, `page-agent-sdk/PUBLISHING.md`.++## Do this+1. **Build integrity:** every package builds cleanly from a fresh install+ (`npm ci`), with correct `main`/`module`/`exports`/`types`, `files` allowlist+ (no source-only leakage, no junk), and working ESM/CJS as declared.+2. **Types:** ship accurate type declarations (`.d.ts`) for every public API. No+ `any`-leaks at the boundary. `npm run typecheck` clean.+3. **Versioning:** consistent semver, accurate `peerDependencies`, no phantom/extra+ deps, deduped lockfile. Confirm `publish:packages:dry` and `publish:mcp:dry` are+ clean for all.+4. **READMEs:** every package has a README with: what it is, install, a 30-second+ quickstart that actually runs, the full API surface, framework variants (web+ component + React for avatar; embed snippets for walk/tour/page-agent), and a link+ to live examples.+5. **Examples:** `examples/` has a runnable example per SDK (web component, React,+ two-agents, minimal, embed). Each is exercised and works against the live site.+6. **Changelogs:** each published package has a CHANGELOG; an SDK release also gets a+ holder-facing entry in `data/changelog.json` (tag `sdk`).+7. **CDN/embed:** the script-tag/CDN embed paths (avatar viewer, walk companion, page+ agent) are documented with integrity-pinned snippets that work copy-paste.+8. **License/attribution:** licenses present and correct; forks (CharacterStudio,+ three.js editor) keep upstream attribution.+9. Do a real consumer test: in a scratch project outside the repo, `npm install` the+ packed tarball (`npm pack`) and run each quickstart. Fix anything that doesn't work.++## Must-not+- Do not publish a package whose quickstart doesn't run as written.+- Do not leak source/test files or secrets via a missing `files` allowlist.+- Do not reference any coin other than $THREE in SDK docs/examples.++## Acceptance+- [ ] Every package builds from `npm ci`; correct exports/types/files; ESM/CJS as declared.+- [ ] Accurate `.d.ts` for all public APIs; typecheck clean.+- [ ] Consistent semver + correct peer deps; `publish:*:dry` clean.+- [ ] Every package README has a runnable quickstart + full API + example links.+- [ ] One runnable example per SDK in `examples/`, exercised against live.+- [ ] `npm pack` → install-in-scratch-project quickstart works for each SDK.+- [ ] SDK release changelog entries added (tag `sdk`).diff --git a/prompts/production-ready/25-observability-logging-metrics.md b/prompts/production-ready/25-observability-logging-metrics.mdnew file mode 100644index 000000000..eb6a9ceeb--- /dev/null+++ b/prompts/production-ready/25-observability-logging-metrics.md@@ -0,0 +1,59 @@+# 25 — Observability (logging, metrics, error tracking)++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Scale & infra+**Owns:** `api/`, `workers/`, `api/_lib/sentry.js`, `api/_lib/usage.js`, `api/_lib/redis-usage.js`, `public/error-reporter.js`.+**Depends on:** `06`, `08`. Pairs with `27`, `28`.++## Why this matters for $1B+You cannot operate or scale what you cannot see. At $1B-trajectory volume, you need to+know within seconds when payments fail, RPC degrades, or a deploy regresses. Observable+systems are the difference between a 5-minute incident and a 5-hour one.++## Mission+End-to-end observability: structured logs, error tracking with alerting, key business++ system metrics on dashboards, and request tracing across api/workers.++## Map+- Error tracking is already wired: **`api/_lib/sentry.js`** (server) ++ **`public/error-reporter.js`** (client). Usage/metering: `api/_lib/usage.js`,+ `api/_lib/redis-usage.js`. Health probes: `api/_lib/forge-health.js`,+ `llm-health.js`, `provider-health.js`, `api/healthz.js`.+- Extend what exists; don't introduce a parallel stack. Additive, per memory guidance.++## Do this+1. **Structured logging:** adopt one structured logger (JSON) across `api/` + workers+ with a request id, route, latency, status, and identity (no secrets/PII — prompt+ `05`/`07`). Replace ad-hoc `console.log`. Log levels respected per env.+2. **Error tracking:** confirm `sentry.js` + `error-reporter.js` capture server ++ client errors with source maps, grouping, release tagging, and alerting on new/+ spiking errors. Ensure the happy path is silent (cross-check prompt `03`).+3. **Metrics:** instrument the metrics that matter — request rate/latency/error per+ route, payment success/failure + GMV, generation jobs (queued/succeeded/failed/+ p95 duration), RPC/AI upstream latency + error + spend, rate-limit hits, signups/+ activations. Build on `usage.js`/`redis-usage.js` for per-upstream cost meters+ (ties to prompt `08`).+4. **Tracing:** propagate a request/trace id through API → upstreams → workers so a+ slow payment can be traced end-to-end.+5. **Dashboards:** a system dashboard (latency/errors/saturation/cost) and a business+ dashboard (signups, activation, GMV, generations, MCP calls). Document where they+ live in `docs/`.+6. **Alerting:** actionable alerts (not noise) for: payment failure rate, 5xx spike,+ upstream-spend approaching cap, worker down, error spike, latency SLO breach.+ Route to the right channel; define ownership/runbook links.+7. **SLOs:** define SLOs for the critical paths (checkout, forge, page load) and track+ error budgets.++## Must-not+- Do not log secrets, private keys, or PII.+- Do not alert on everything — every alert must be actionable.+- Do not hand-roll a metrics backend when a vetted one fits.++## Acceptance+- [ ] One structured logger across api + workers with request ids; no secret/PII logging.+- [ ] Server + client errors flow to the tracker with source maps, grouping, alerting.+- [ ] Key system + business metrics instrumented, incl. per-upstream cost meters.+- [ ] Trace ids propagate API → upstream → worker.+- [ ] System + business dashboards exist and are documented.+- [ ] Actionable alerts with runbooks; SLOs defined for critical paths.diff --git a/prompts/production-ready/26-database-integrity-and-migrations.md b/prompts/production-ready/26-database-integrity-and-migrations.mdnew file mode 100644index 000000000..77c817221--- /dev/null+++ b/prompts/production-ready/26-database-integrity-and-migrations.md@@ -0,0 +1,61 @@+# 26 — Database integrity & migrations++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Scale & infra+**Owns:** `api/_lib/db.js`, `api/_lib/schema.sql`, `api/_lib/migrations/`, `api/_lib/db-retry.js`, data-access in `api/_lib/`, tables like `agent_identities`, `pump_agent_mints`, skill/license/purchase tables.+**Depends on:** `05`, `07`. Pairs with `18`, `27`.++## Why this matters for $1B+Data integrity is existential when the data is wallets, ownership, and money. Corrupt+or lost data destroys trust and is often unrecoverable. Clean migrations let you ship+fast without breaking production.++## Mission+A documented, versioned schema with safe forward-migrations, enforced integrity+constraints, backups with tested restore, and no orphaned or inconsistent records.++## Map+- DB client: `api/_lib/db.js` (+ retry wrapper `db-retry.js`). Schema: `api/_lib/+ schema.sql`. Migrations: `api/_lib/migrations/` (e.g.+ `20260616130000_oracle_copy_fanout.sql`). Tooling: `npm run db:migrate`,+ `npm run db:status`. Core invariants: `agent_identities.user_id` immutable, one+ agent = one owner; launch records in `pump_agent_mints`; skill/license/purchase rows.++## Do this+1. **Schema audit:** document every table, column, type, and relationship in+ `docs/data-model.md` (derive from `schema.sql` + `migrations/`). Identify missing+ constraints: primary keys, foreign keys, uniqueness (e.g. one wallet per agent),+ not-null, check constraints (amount ≥ 0), and indexes on hot query paths.+2. **Add the constraints** that enforce the invariants the app assumes — especially+ the ownership and money invariants (prompt `07`). Backfill/clean any existing rows+ that would violate them first, via a migration.+3. **Migrations:** ensure every schema change goes through a versioned, ordered,+ idempotent migration in `api/_lib/migrations/`; `db:status` reflects reality;+ migrations are forward-safe and reversible where possible. No manual prod schema+ edits.+4. **Integrity sweep:** scan for orphans (records pointing to deleted parents),+ duplicates, and inconsistent states (purchase confirmed but no license; mint+ recorded but no agent). Fix the data and add the constraint/job that prevents+ recurrence.+5. **Transactions:** money/ownership mutations that touch multiple rows run in+ transactions so they can't partially apply (ties to prompt `18` idempotency).+6. **Backups & restore:** confirm automated backups exist, are encrypted, and — most+ importantly — **test a restore** into a scratch environment. Document RPO/RTO.+7. **Performance:** add indexes for slow queries surfaced by observability (prompt+ `25`); paginate large reads (prompt `10`); use `db-retry.js` on transient failures.+8. Add data-integrity tests/checks that can run against a seeded DB in CI.++## Must-not+- Do not edit production schema outside a migration.+- Do not add a destructive migration without a tested backup and a reversal plan.+- Do not weaken an invariant constraint to make a write succeed — fix the write.++## Acceptance+- [ ] `docs/data-model.md` documents schema + relationships from `schema.sql`/migrations.+- [ ] Integrity constraints (PK/FK/unique/not-null/check) + hot-path indexes added; offending data cleaned.+- [ ] All schema changes are versioned, idempotent migrations in `api/_lib/migrations/`; `db:status` accurate.+- [ ] Orphan/duplicate/inconsistent-state sweep clean; preventer in place.+- [ ] Multi-row money/ownership mutations are transactional.+- [ ] Backups verified by a successful test restore; RPO/RTO documented.+- [ ] Data-integrity checks runnable in CI.diff --git a/prompts/production-ready/27-deploy-pipeline-and-rollback.md b/prompts/production-ready/27-deploy-pipeline-and-rollback.mdnew file mode 100644index 000000000..4d6e8fbf9--- /dev/null+++ b/prompts/production-ready/27-deploy-pipeline-and-rollback.md@@ -0,0 +1,57 @@+# 27 — Deploy pipeline & rollback safety++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Scale & infra+**Owns:** `vercel.json`, build scripts (`build`, `build:vercel`, `build:all`), `deploy/`, CI/CD, `npm run audit:deploy`, the two git remotes.+**Depends on:** `01`, `05`, `25`. Pairs with `28`.++## Why this matters for $1B+Shipping safely and reverting instantly is what lets a team move fast without breaking+trust. A bad deploy that can't be rolled back is an outage. Repeatable, gated deploys+are an engineering-maturity signal in diligence.++## Map+- `vercel.json` (buildCommand, outputDirectory, installCommand, env, functions,+ routes, crons). Build pipeline scripts in `package.json`. `npm run audit:deploy`.+- **Two remotes** (`/CLAUDE.md`): `threeD` (push-only mirror) + `threews` (canonical).+ Never pull/fetch/merge from `threeD`. Watch the `npx vercel build` trap that+ overwrites `api/*.js` in place — guard against committing esbuild bundles.++## Do this+1. **Reproducible build:** `npm ci` from a clean tree builds deterministically;+ document the exact build/deploy steps in `docs/deploy.md`. Confirm `audit:deploy`+ passes and what it checks.+2. **Pipeline gates:** deploys to production require green lint + typecheck + tests+ (prompt `01`). Wire CI so `main` deploys only on green; PRs get preview deploys.+3. **Source-bundle trap guard:** add a pre-commit/CI check that fails if any committed+ `api/*.js` or `public/*` begins with esbuild markers (`__defProp`/`createRequire`),+ per the known trap. Document the recovery (`git restore -- api/ public/`).+4. **Both-remotes discipline:** document and (where possible) script the dual push+ (`threeD` + `threews`) so neither deploy target falls behind; never force-push;+ never pull from `threeD`.+5. **Migrations in deploy:** DB migrations (prompt `26`) run as an ordered, gated step+ with a clear order relative to code deploy (backward-compatible migrate → deploy →+ cleanup). No deploy that assumes an unrun migration.+6. **Rollback:** verify instant rollback to the previous good deployment works (Vercel+ promote/rollback), and document the exact steps + when to use it. Practice one.+7. **Crons:** audit `vercel.json` crons (incl. the auto-rig sweep) — each has a clear+ purpose, idempotency, failure alerting (prompt `25`), and won't stampede.+8. **Env parity:** preview/staging mirrors prod env keys (prompt `05`); no+ prod-only surprises.+9. **Post-deploy smoke:** an automated post-deploy smoke (`smoke:onchain`,+ `smoke:mcp`, key page loads) gates promotion and pages on failure.++## Must-not+- Do not commit esbuild-bundled `api/*.js` source (run the guard).+- Do not pull/fetch/merge from `threeD`; do not force-push either remote.+- Do not deploy code that depends on an unrun migration.++## Acceptance+- [ ] `docs/deploy.md` documents reproducible build + deploy + rollback steps.+- [ ] Production deploy gated on green CI; PRs get previews.+- [ ] CI guard blocks committed esbuild-bundled source files.+- [ ] Dual-remote push documented/scripted; no pulls from `threeD`.+- [ ] Migrations run as a gated, ordered, backward-compatible step.+- [ ] Rollback verified by an actual practice run; documented.+- [ ] Crons audited (purpose/idempotency/alerting); post-deploy smoke gates promotion.diff --git a/prompts/production-ready/28-uptime-monitoring-and-status-page.md b/prompts/production-ready/28-uptime-monitoring-and-status-page.mdnew file mode 100644index 000000000..7d4410666--- /dev/null+++ b/prompts/production-ready/28-uptime-monitoring-and-status-page.md@@ -0,0 +1,58 @@+# 28 — Uptime monitoring & public status page++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Scale & infra+**Owns:** health endpoints (`api/healthz.js`, `api/_lib/forge-health.js`, `llm-health.js`, `provider-health.js`), external uptime monitoring, a public status page.+**Depends on:** `25`. Pairs with `27`, `29`.++## Why this matters for $1B+Enterprise buyers and serious developers expect a status page and a track record of+uptime. Knowing about outages before users do — and being transparent when they+happen — builds the trust a platform handling money requires.++## Mission+Real health checks for every critical dependency, external synthetic monitoring of+the user-critical flows, and a public status page with incident history.++## Map+- Existing: `api/healthz.js` (liveness), `api/_lib/forge-health.js` (probes the+ rate-limiter store / paid-lane health), `llm-health.js`, `provider-health.js`.+ Extend these into a deep readiness check.+- Critical deps to probe: DB (prompt `26`), Solana RPC, pump.fun feed, AI worker+ proxies, x402 facilitator, R2/CDN for GLBs.+- Observability sinks from prompt `25` feed the monitors/alerts.++## Do this+1. **Health endpoints:** keep `healthz.js` as a fast liveness check; add a deeper+ readiness check that verifies each critical dependency (DB connectivity, RPC+ reachable, AI proxy up via `llm-health.js`/`provider-health.js`, payment facilitator+ up, rate-limit store via `forge-health.js`) and returns a structured per-dependency+ status. No secrets in output.+2. **Synthetic monitoring:** external uptime checks (multi-region) for the homepage,+ forge generate path, a sample MCP call, and a checkout prepare — i.e. the flows+ that lose money/users when down, not just "is the site up."+3. **Alerting:** down/degraded triggers the on-call alert (prompt `25`) with the+ failing dependency named. Distinguish degraded (one dep slow) from down.+4. **Public status page:** a branded status page (own page or a vetted provider) showing+ component status (web, forge, payments, MCP, launches), uptime history, and incident+ posts. Linkable from the footer.+5. **Incident process:** document a lightweight incident runbook in `docs/`: detect →+ declare → communicate (status page) → mitigate → resolve → postmortem. Templates+ included.+6. **Cron/worker liveness:** monitor the crons + workers (oracle/sniper, auto-rig+ sweep) — alert if a scheduled run is missed or fails (prompt `27`).++## Must-not+- Do not expose secrets, internal hostnames, or stack details in health output.+- Do not let the deep health check be so heavy it becomes a self-inflicted load source+ — rate-limit/cache it.+- Do not alert without naming the failing component.++## Acceptance+- [ ] Liveness (`healthz.js`) + deep readiness endpoint report per-dependency status, no leaks.+- [ ] External multi-region synthetic checks cover homepage, forge, MCP, checkout.+- [ ] Down/degraded alerts fire with the failing dependency named.+- [ ] Public branded status page with component status + uptime + incident history, linked in footer.+- [ ] Incident runbook + templates in `docs/`.+- [ ] Cron/worker liveness monitored with missed-run alerts.diff --git a/prompts/production-ready/29-load-and-stress-testing.md b/prompts/production-ready/29-load-and-stress-testing.mdnew file mode 100644index 000000000..6c812cd8c--- /dev/null+++ b/prompts/production-ready/29-load-and-stress-testing.md@@ -0,0 +1,60 @@+# 29 — Load & stress testing++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 3 — Scale & infra+**Owns:** load-test harness (in `scripts/` or `tests/load/`), `api/`, `workers/`, caching/CDN config.+**Depends on:** `06`, `08`, `25`, `26`. Pairs with `27`, `28`.++## Why this matters for $1B+A platform that goes viral and falls over wasted the moment. You need to know the real+ceiling of each critical path, where it breaks first, and that autoscaling + rate+limits + caching hold under a launch-day spike. Capacity confidence is fundability.++## Mission+Establish load profiles for the critical paths, find the breaking points, fix the+first bottlenecks, and document headroom + scaling behavior.++## Map+- Critical paths: homepage + key pages (static/CDN), forge generation (expensive,+ upstream-bound), checkout/x402 (money, DB + RPC), MCP tool calls, launch feed reads,+ agent profile reads.+- Use a vetted tool (k6 / Artillery). Run against a staging/preview env, never prod,+ with synthetic data — and **never** real third-party mints (prompt `22`).++## Do this+1. **Define profiles:** realistic mixes — steady-state, a marketing-spike ramp, and a+ sustained soak — with target RPS/concurrency per path based on growth goals.+2. **Build the harness** in `scripts/` or `tests/load/` (kept, documented, not+ throwaway), parameterized by env + RPS, with auth handled. Cover read paths and at+ least one safe write path (idempotent, against staging).+3. **Run & measure:** capture p50/p95/p99 latency, error rate, throughput, and+ upstream/DB saturation (via prompt `25` dashboards). Identify the first bottleneck+ on each path.+4. **Fix the top bottlenecks:** add/verify caching (CDN for static + GLBs, query+ caching for hot reads), connection pooling/limits for DB + RPC, queueing/+ backpressure for generation, and confirm rate limits (prompt `08`) shed load+ gracefully instead of collapsing.+5. **Autoscaling:** verify serverless function concurrency limits and worker scaling+ behave under spike; no cold-start cliff on the money path; no unbounded fan-out to+ a single RPC node.+6. **Failure-mode under load:** confirm that when an upstream degrades under load, the+ resilience patterns (prompt `06`) and circuit breakers keep the rest of the site up+ (graceful degradation, designed error states — prompt `12`).+7. **Document capacity:** record measured headroom per path, the breaking point, and+ the scaling levers in `docs/capacity.md`. Set alert thresholds (prompt `28`) below+ the breaking point.++## Must-not+- Do not load-test production or use real third-party mints/addresses.+- Do not "fix" a bottleneck by removing a rate limit or a safety check.+- Do not leave the harness as an undocumented throwaway in the repo root (use `scripts/`).++## Acceptance+- [ ] Documented load profiles (steady/spike/soak) with growth-based targets.+- [ ] Repeatable, parameterized load harness in `scripts/` or `tests/load/`.+- [ ] p50/p95/p99 + error rate + saturation measured per critical path; bottlenecks identified.+- [ ] Top bottlenecks fixed (caching, pooling, queueing); rate limits shed load gracefully.+- [ ] Autoscaling verified under spike; no cold-start cliff on checkout.+- [ ] Graceful degradation confirmed when an upstream fails under load.+- [ ] `docs/capacity.md` records headroom, breaking points, levers; alerts set below them.diff --git a/prompts/production-ready/30-onboarding-and-activation.md b/prompts/production-ready/30-onboarding-and-activation.mdnew file mode 100644index 000000000..138c382ca--- /dev/null+++ b/prompts/production-ready/30-onboarding-and-activation.md@@ -0,0 +1,52 @@+# 30 — Onboarding & activation funnel++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** first-run experience across `pages/`, signup/auth, the path from landing → first "aha", `src/feature-tour/`, empty states.+**Depends on:** `12`, `15`, `19`. Pairs with `31`, `33`.++## Why this matters for $1B+Activation rate — the share of new users who reach the "aha" (a forged 3D model, a+created agent) — is the single biggest lever on growth-loop velocity and therefore+valuation. Most signups are won or lost in the first 60 seconds.++## Mission+Design and build a first-run experience that gets a brand-new visitor to a real,+shareable "aha" moment as fast as possible, with zero confusion and zero dead ends.++## Do this+1. **Define the aha + the funnel:** pick the primary activation event (likely: first+ forged/created 3D model, or first agent). Map every step from landing →+ aha and instrument each (prompt `33`) to find drop-off.+2. **Reduce time-to-value:** let users experience the magic *before* signup where+ possible (the free `forge_free` lane, the live tour) — capture the account *after*+ they've felt value, not before. No wall in front of the wow.+3. **Guided first run:** a focused, skippable first-run flow (lean on the feature tour,+ prompt `19`) that points at the one next action, not a feature dump. Progressive+ disclosure.+4. **Empty states as onboarding:** every first-visit empty state (profile, wallet,+ marketplace, dashboard) teaches the next step with a working CTA (prompt `12`).+5. **Account creation:** frictionless auth; if a custodial wallet is provisioned,+ explain it simply and reassuringly. Clear value for signing up.+6. **First-win reinforcement:** when the user hits the aha, celebrate it and offer the+ natural next step (share it, list it, make another, give it a wallet) — chain into+ the growth loop (prompt `35`).+7. **Re-engagement:** a sensible welcome/first-steps message (email/notification per+ prompt `39`) for users who leave before activating.+8. **Measure:** activation rate, time-to-aha, and step drop-off visible on the growth+ dashboard (prompt `25`/`33`). Set a baseline and a target.++## Must-not+- Do not gate the core "wow" behind signup if a no-account path exists.+- Do not dump every feature on a new user — one next action at a time.+- Do not ship empty states that are dead ends.++## Acceptance+- [ ] Activation event defined; full landing→aha funnel instrumented with drop-off visibility.+- [ ] A no-signup path to the core wow exists; account captured after value.+- [ ] Skippable guided first-run points at one next action; progressive disclosure.+- [ ] Every first-visit empty state teaches + has a working CTA.+- [ ] First-win celebration chains into share/create-again/wallet.+- [ ] Re-engagement message for pre-activation drop-offs.+- [ ] Activation rate + time-to-aha tracked with a baseline and target.diff --git a/prompts/production-ready/31-home-and-landing-conversion.md b/prompts/production-ready/31-home-and-landing-conversion.mdnew file mode 100644index 000000000..02e004ce5--- /dev/null+++ b/prompts/production-ready/31-home-and-landing-conversion.md@@ -0,0 +1,57 @@+# 31 — Home / landing conversion++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** `pages/home.html`, top-of-funnel landing pages, hero, primary CTAs, social proof.+**Depends on:** `10`, `13`, `14`. Pairs with `30`, `33`.++## Why this matters for $1B+The homepage is the highest-traffic, highest-leverage page. A few points of conversion+lift compounds across every channel. It must instantly communicate what three.ws is,+why it's special, and what to do next — and it must be screenshot-worthy.++## Map+- `pages/home.html` (was modified in the working tree — review before editing).+ Pulls from `data/features.json` / `public/features.json`. Global tokens (prompt+ `13`).++## Do this+1. **Message clarity:** above the fold answers "what is this / who is it for / why+ care" in one glance, with a single dominant CTA toward the activation event (prompt+ `30`). No jargon, no ambiguity.+2. **Show, don't tell:** lead with the product's magic — a live, interactive 3D+ moment (a real model the visitor can orbit, the walking guide, a forge demo) rather+ than a static screenshot. It must load fast (prompt `10`) and never block first+ paint.+3. **Proof:** real social proof — usage numbers, notable creations, launches, SDK+ installs, testimonials — all truthful and live where possible. No fabricated+ metrics.+4. **Narrative flow:** the page tells a story — magic → how it works → what you can+ build (forge, agents, marketplace, SDKs) → proof → CTA. Each section links into the+ relevant surface (cross-wiring, `/CLAUDE.md`).+5. **CTAs everywhere sensible:** primary CTA repeated at natural decision points;+ secondary paths (developers → SDKs/docs, traders → launches, creators →+ marketplace) routed clearly.+6. **Polish to screenshot bar:** microinteractions, gradients, motion-with-intent+ (reduced-motion safe), perfect spacing/type (prompt `13`), flawless on mobile+ (prompt `11`) and both themes.+7. **Performance + SEO:** great LCP/CLS (prompt `10`), complete meta + OG + JSON-LD+ (prompt `14`).+8. **Experiment-ready:** structure the hero/CTA so they can be A/B tested (prompt+ `33`); instrument CTA clicks and scroll depth.++## Must-not+- Do not show fabricated stats or testimonials.+- Do not block first paint on the 3D hero — lazy/progressive load it.+- Do not bury the primary CTA or present competing equal CTAs that paralyze.+- Do not reference any coin other than $THREE.++## Acceptance+- [ ] Above-the-fold communicates what/who/why + one dominant CTA at a glance.+- [ ] Live interactive 3D moment that loads fast and doesn't block first paint.+- [ ] Truthful, live social proof.+- [ ] Narrative sections cross-link to forge/agents/marketplace/SDKs.+- [ ] Screenshot-grade polish; flawless mobile + both themes; reduced-motion safe.+- [ ] Strong LCP/CLS + complete meta/OG/JSON-LD.+- [ ] CTA clicks + scroll depth instrumented; hero/CTA A/B-ready.diff --git a/prompts/production-ready/32-pricing-and-monetization-surfaces.md b/prompts/production-ready/32-pricing-and-monetization-surfaces.mdnew file mode 100644index 000000000..c20ad2de8--- /dev/null+++ b/prompts/production-ready/32-pricing-and-monetization-surfaces.md@@ -0,0 +1,53 @@+# 32 — Pricing & monetization surfaces++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** pricing page(s), upgrade/paywall surfaces, paid lanes (forge, MCP, skills), `prompts/monetization/` outcomes, billing/receipts.+**Depends on:** `08`, `16`, `18`, `23`. Pairs with `30`, `33`.++## Why this matters for $1B+Revenue is the numerator of valuation. Clear pricing, frictionless upgrade, and+multiple monetization surfaces (paid generation, paid MCP calls, marketplace take,+skill sales, premium features) are what turn engagement into a $1B business.++## Map+- Paid lanes already exist: paid MCP tools (USDC via x402, prompt `23`), skill+ purchases + on-chain licenses (prompt `16`), the free vs paid forge lanes (prompt+ `15`/`08`). Pricing libs: `api/_lib/skill-pricing-rules.js`, `skill-price-cache.js`,+ `x402-prices.js`. Monetization design work: `prompts/monetization/`.++## Do this+1. **Pricing page:** a clear, honest pricing page — what's free, what's paid, what+ each tier/credit unlocks, in plain language. Per-call USDC prices for MCP/forge+ lanes surfaced. Designed for both human users and agent developers.+2. **Upgrade moments:** when a user hits a free-lane limit (prompt `08`), present a+ contextual, non-annoying upgrade with the exact value they're about to get — not a+ hard wall. Track conversion on these moments.+3. **Frictionless checkout:** upgrades/credits use the hardened payment flow (prompt+ `18`) with clear confirmation, instant unlock, and a receipt. No dead ends.+4. **Monetization surfaces wired:** marketplace take-rate on sales (prompt `16`),+ paid MCP calls (prompt `23`), paid generation credits (prompt `15`), premium+ features, and creator payouts — each accounted correctly (prompt `26`) and visible+ on the business dashboard (prompt `25`).+5. **Receipts & billing history:** users/creators see their purchases, balances,+ payouts, and downloadable receipts. Real data, designed empty states.+6. **Creator economics:** make it obvious how creators earn (sell skills/avatars/+ scenes, get tipped, launch) and show real earnings — the supply-side flywheel.+7. **Experiment:** price points and packaging are configurable (source from the+ pricing libs, not hardcoded across the UI) so they can be tested; instrument+ upgrade funnel + LTV inputs (prompt `33`).++## Must-not+- Do not hardcode prices in scattered UI strings — source from the pricing config/libs.+- Do not hard-wall the core wow; convert with value at the limit instead.+- Do not show fabricated revenue/earnings; real accounting only.+- Do not reference any coin other than $THREE (USDC pricing for services is fine).++## Acceptance+- [ ] Clear, honest pricing page (free vs paid, per-call USDC prices) for users + devs.+- [ ] Contextual upgrade moments at free-lane limits with conversion tracking.+- [ ] Frictionless upgrade/credit checkout with instant unlock + receipt.+- [ ] All monetization surfaces wired + accounted + on the business dashboard.+- [ ] Receipts/billing history + creator earnings show real data with designed states.+- [ ] Prices/packaging sourced from one config; upgrade funnel instrumented.diff --git a/prompts/production-ready/33-growth-analytics-instrumentation.md b/prompts/production-ready/33-growth-analytics-instrumentation.mdnew file mode 100644index 000000000..543348b9f--- /dev/null+++ b/prompts/production-ready/33-growth-analytics-instrumentation.md@@ -0,0 +1,56 @@+# 33 — Growth analytics instrumentation++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** product analytics, event taxonomy, funnels, A/B framework, consent/privacy.+**Depends on:** `25`, `30`, `31`, `32`. Pairs with `35`, `37`.++## Why this matters for $1B+You can't grow what you don't measure. A clean event taxonomy + funnels + experiment+framework is how every growth decision (prompts `30`–`35`) gets validated instead of+guessed. Investors expect to see the funnel and the levers.++## Mission+Instrument the product with a consistent, privacy-respecting analytics layer: a typed+event taxonomy, the core funnels, retention/cohort views, and an A/B testing+capability — all feeding dashboards.++## Map+- A vetted product-analytics tool (privacy-friendly, e.g. PostHog-class) over+ hand-rolling. Distinguish from system observability (prompt `25`) — this is product/+ growth events. Respect consent (prompt `37`).++## Do this+1. **Event taxonomy:** define a documented, typed event schema (`docs/analytics.md`):+ consistent names, properties, and identity model (anon → authed stitching). Cover+ the funnel: landing view, CTA click, signup, first generation, first agent, first+ purchase, share, return. No ad-hoc one-off event names.+2. **Funnels:** build the core funnels — acquisition → activation (prompt `30`) →+ revenue (prompt `32`) → retention → referral (prompt `35`) — with step drop-off+ visible.+3. **Retention & cohorts:** D1/D7/D30 retention and cohort curves; identify the+ behaviors that correlate with retention (the "north-star input" — e.g. created N+ agents in week 1).+4. **A/B framework:** a lightweight experiment system (feature-flag + assignment ++ metric readout) so hero/CTA/pricing/onboarding variants (prompts `30`–`32`) can be+ tested with statistical rigor. Document how to run an experiment.+5. **Dashboards:** a growth dashboard (acquisition, activation, retention, revenue,+ referral, north-star) alongside the system/business dashboards (prompt `25`).+6. **Privacy & consent:** consent management, IP/PII minimization, honoring+ do-not-track and opt-out (prompt `37`). No PII in event payloads.+7. **Validate:** verify events fire correctly across key flows (no double-counting,+ correct identity stitching) before trusting the numbers.++## Must-not+- Do not collect PII in events or track without consent where required.+- Do not invent inconsistent event names per page — follow the taxonomy.+- Do not ship dashboards built on unvalidated/double-counted events.++## Acceptance+- [ ] Documented typed event taxonomy + identity model in `docs/analytics.md`.+- [ ] Core funnels (acq→activation→revenue→retention→referral) with drop-off.+- [ ] Retention/cohort views + identified north-star input metric.+- [ ] A/B framework usable for hero/CTA/pricing/onboarding experiments; documented.+- [ ] Growth dashboard live alongside system/business dashboards.+- [ ] Consent + PII-minimization in place; events validated for accuracy.diff --git a/prompts/production-ready/34-developer-experience-and-docs-site.md b/prompts/production-ready/34-developer-experience-and-docs-site.mdnew file mode 100644index 000000000..315bb9dd4--- /dev/null+++ b/prompts/production-ready/34-developer-experience-and-docs-site.md@@ -0,0 +1,55 @@+# 34 — Developer experience & docs site++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** `docs/`, a public docs site, API reference, SDK guides, MCP setup guides, `examples/`, quickstarts.+**Depends on:** `23`, `24`. Pairs with `14`, `31`.++## Why this matters for $1B+three.ws is a platform other developers and agents build on. Documentation is the+product for them. World-class docs (Stripe/Vercel-grade) are a growth channel, a+moat, and a credibility signal that justifies a platform multiple.++## Mission+A polished, public developer hub: getting-started, SDK guides, full API + MCP+reference, runnable examples, and recipes — accurate, searchable, and maintained.++## Map+- `docs/` (internal + reference), `examples/` (`embed-test`, `web-component`,+ `two-agents`, `minimal`, etc.), `STRUCTURE.md`, per-package READMEs (prompt `24`),+ `page-agent-sdk/PUBLISHING.md`, `docs/3d-asset-pipeline.md`.++## Do this+1. **Docs site:** a public, branded, searchable docs site (own route or a vetted+ docs framework) with clear IA: Get Started, Guides, SDK Reference, API Reference,+ MCP, Recipes, Changelog. Themed to match the platform (prompt `13`).+2. **Quickstarts that run:** a "5-minute" quickstart per primary surface (embed an+ avatar, add the walk companion, call a paid MCP tool, make an x402 payment, mint+ an agent). Each is copy-paste and verified to work (prompt `24`).+3. **API reference:** generate/maintain reference for the public `api/` surface+ (endpoints, params, auth, errors, examples). Keep it in sync with the code (derive+ from the handlers where possible, not hand-typed drift).+4. **MCP setup:** clear setup for Claude Desktop/Code and other clients, the free+ `forge_free` quickstart as the wedge, and the paid-tool x402 flow (prompt `23`).+5. **Examples gallery:** `examples/` is curated, each runnable against live, linked+ from the docs. Add the missing common recipes.+6. **Consistency & accuracy:** every code sample is tested (a CI check that runs/lints+ doc snippets where feasible); no stale endpoints/flags (cross-check the codebase+ before publishing — verify referenced files/flags still exist).+7. **Discoverability:** docs are crawlable + in llms.txt (prompt `14`); searchable;+ linked from home (prompt `31`) and the footer.+8. **Feedback loop:** a "was this helpful / edit this page" path so docs improve.++## Must-not+- Do not publish a sample that doesn't run as written.+- Do not let docs drift from code — prefer generated/tested references.+- Do not reference any coin other than $THREE in docs/examples.++## Acceptance+- [ ] Public, branded, searchable docs site with clear IA, themed to the platform.+- [ ] Verified 5-minute quickstart per primary surface.+- [ ] API + MCP reference accurate and kept in sync with code.+- [ ] Curated `examples/` gallery, each runnable against live, linked from docs.+- [ ] Doc code samples tested in CI; no stale endpoints/flags.+- [ ] Docs crawlable + in llms.txt + linked from home/footer; feedback path present.diff --git a/prompts/production-ready/35-referral-and-virality.md b/prompts/production-ready/35-referral-and-virality.mdnew file mode 100644index 000000000..18b81c3ee--- /dev/null+++ b/prompts/production-ready/35-referral-and-virality.md@@ -0,0 +1,55 @@+# 35 — Referral & virality loops++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** sharing surfaces, OG image generation (`api/forge-og.js` + a general OG service), embeds, referral mechanics, public/embeddable artifacts.+**Depends on:** `14`, `17`, `24`, `30`, `33`. Pairs with `31`.++## Why this matters for $1B+Paid acquisition can't get you to $1B alone — viral loops (k-factor > sharing friction)+do. three.ws is unusually shareable: every output is a 3D model, an agent, a launch.+Engineering the loops so creations spread is the highest-leverage growth work.++## Mission+Make every creation effortlessly shareable and embeddable, with attribution that+pulls viewers back, plus referral mechanics that reward bringing others in.++## Do this+1. **Share everywhere:** every artifact (forged model, agent profile, scene, launch,+ marketplace listing) has a one-tap Share with a great destination URL, copy, and a+ real, dynamic OG/Twitter image (prompt `14`) that renders the actual 3D+ output. Verify cards on the major platforms.+2. **Embeds as a loop:** the `<agent-3d>`, walk companion, and page-agent embeds+ (prompt `24`) carry tasteful, non-spammy attribution back to three.ws — every embed+ on the web is a billboard. One-click "embed this" with copy-paste code.+3. **Dynamic OG image service:** a real endpoint that renders share images for agents/+ models/launches on the fly (extend `api/forge-og.js`; cached, fast, resilient —+ prompt `06`). No generic placeholder image.+4. **Referral mechanics:** a referral program where inviting a user who activates+ (prompt `30`) rewards both sides (credits toward paid lanes, etc. — accounted per+ prompt `26`). Track invites → signups → activations (prompt `33`). Abuse-guarded+ (prompt `08`).+5. **Built-in share prompts:** at the first-win moment (prompt `30`) and other natural+ peaks, invite the user to share — without being naggy. Make sharing feel good, not+ transactional.+6. **Public galleries:** the launches feed, a community/creations gallery, and agent+ directories are public, indexable (prompt `14`), and link inward — discovery+ surfaces that also pull SEO traffic.+7. **Measure k-factor:** instrument shares → visits → signups so the loop's+ coefficient is visible and improvable (prompt `33`).++## Must-not+- Do not ship a generic/static OG image where a dynamic one belongs.+- Do not make embeds spammy or attribution obnoxious — tasteful only.+- Do not allow self-referral/abuse to drain rewards (guard it).+- Do not reference any coin other than $THREE in share copy.++## Acceptance+- [ ] Every artifact has one-tap share with great copy + dynamic 3D OG image (cards validated).+- [ ] Embeds carry tasteful inbound attribution; one-click embed-code copy.+- [ ] Real, cached, resilient dynamic OG-image service (no placeholders).+- [ ] Referral program rewards both sides on activation; tracked + abuse-guarded.+- [ ] First-win + peak-moment share prompts (non-naggy).+- [ ] Public indexable galleries that link inward.+- [ ] Share→visit→signup instrumented; k-factor visible.diff --git a/prompts/production-ready/36-trust-safety-and-moderation.md b/prompts/production-ready/36-trust-safety-and-moderation.mdnew file mode 100644index 000000000..79afe92b4--- /dev/null+++ b/prompts/production-ready/36-trust-safety-and-moderation.md@@ -0,0 +1,61 @@+# 36 — Trust, safety & moderation++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** content moderation for user generations (text prompts, images, avatars, names, listings), reporting/abuse handling, moderation tooling.+**Depends on:** `07`, `08`, `16`. Pairs with `37`.++## Why this matters for $1B+A platform where anyone generates 3D content from arbitrary prompts and lists it for+sale will attract abuse. Unmoderated abuse kills app-store distribution, payment-+processor relationships, brand, and enterprise deals. Trust & safety is a+prerequisite for scale, not an afterthought.++## Mission+Prevent, detect, and act on harmful content across every user-generated surface, with+clear policies, real moderation tooling, and user reporting — without crushing+legitimate creation.++## Map+- UGC surfaces: forge prompts/images (prompt `15`), avatars/names (prompt `21`),+ marketplace listings (prompt `16`), agent bios, communities, scenes, launch metadata.++## Do this+1. **Policy:** write clear, public content guidelines + acceptable-use policy (what's+ not allowed: illegal content, CSAM, hate, harassment, impersonation, IP theft,+ scams). Link in footer + onboarding (coordinate with prompt `37`).+2. **Input moderation:** screen generation prompts and uploaded images before+ generation (a vetted moderation API / classifier) and block disallowed requests+ with a clear, non-leaky message. Screen names/handles/bios/listing text for slurs/+ scams/impersonation.+3. **Output moderation:** scan generated images/models and listing media; quarantine+ or block violations; keep an audit trail.+4. **Reporting:** a real "report" flow on every public artifact (agent, listing,+ scene, launch, community post) that creates a triage-able case.+5. **Moderation tooling:** an internal queue/dashboard to review reports + flagged+ content, take action (warn/remove/ban), and record decisions. Role-gated (prompt+ `07`).+6. **Enforcement:** graduated actions (content removal, rate-limit, suspension, ban)+ with user notification and an appeal path. Tie repeat abuse to the rate-limit/abuse+ system (prompt `08`).+7. **Impersonation & scams:** specific guards for fake "official" agents/launches and+ $THREE-impersonation scams; verified badges where appropriate. Reinforce the+ one-coin rule (prompt `22`) — no other coin is ever promoted.+8. **CSAM/illegal escalation:** a documented, legally-aware escalation path (preserve+ evidence, report to authorities/NCMEC as required) — never just silently delete.++## Must-not+- Do not ship UGC surfaces with no moderation or no reporting.+- Do not let moderation messages leak internal details or the exact classifier rules.+- Do not over-block legitimate creation — tune for precision + appeal.+- Do not allow impersonation of three.ws/$THREE or promotion of other coins.++## Acceptance+- [ ] Public content guidelines + AUP, linked in footer + onboarding.+- [ ] Input (prompt/image/name) + output (model/media) moderation with clear blocks + audit trail.+- [ ] Report flow on every public artifact creating triage-able cases.+- [ ] Role-gated moderation queue/dashboard with action logging.+- [ ] Graduated enforcement + notification + appeal, tied to abuse system.+- [ ] Impersonation/scam guards; one-coin rule reinforced.+- [ ] Documented CSAM/illegal escalation path.diff --git a/prompts/production-ready/37-legal-compliance-tos-privacy.md b/prompts/production-ready/37-legal-compliance-tos-privacy.mdnew file mode 100644index 000000000..6579af409--- /dev/null+++ b/prompts/production-ready/37-legal-compliance-tos-privacy.md@@ -0,0 +1,63 @@+# 37 — Legal, compliance, ToS & privacy++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** Terms of Service, Privacy Policy, cookie/consent, licenses/attribution, financial/crypto disclosures, data-rights flows.+**Depends on:** `05`, `33`, `36`. Pairs with `26`.++## Why this matters for $1B+A platform that custodies wallets, processes payments, hosts UGC, and uses AI must be+legally defensible to raise, to sell to enterprises, and to survive scrutiny. Missing+ToS/privacy/disclosures is a hard blocker in diligence and an existential risk given+the money and crypto involved.++> You are an engineer, not a lawyer. Build the surfaces, wire the flows, and flag+> exactly where qualified legal counsel must review/author the binding text. Do not+> invent legal guarantees.++## Map+- Forks/vendored code attribution already tracked: `character-studio/LICENSE`,+ `src/scene-studio/vendor/LICENSE`, `public/animations/LICENSES.md`, per-asset+ `LICENSES.md` under `public/club/`. Custodial wallets + payments (prompts `17`,+ `18`). Analytics/PII (prompt `33`).++## Do this+1. **ToS + Privacy + AUP pages:** real, reachable pages (linked in footer + signup ++ onboarding). Draft thorough content covering accounts, custodial wallets, payments,+ UGC + moderation (prompt `36`), AI-generated content + IP/ownership, disclaimers,+ liability, and termination — clearly marked for counsel review where binding.+2. **Privacy specifics:** what data is collected (derive from prompt `33` taxonomy ++ prompt `05` env), why, retention, processors/subprocessors, and user rights+ (access, export, delete). Build the **data export + deletion** flows (real, wired —+ not a mailto), respecting the data model (prompt `26`).+3. **Consent management:** cookie/analytics consent banner honoring opt-out and+ do-not-track (ties to prompt `33`); no non-essential tracking before consent.+4. **Crypto/financial disclosures:** clear, non-misleading disclosures for the+ custodial wallet, payments, token activity, and risk — no investment advice, no+ guaranteed returns. Reinforce the one-coin rule: $THREE is the only coin; no+ promotion of others (prompt `22`).+5. **Licenses & attribution:** confirm all forks/vendored/3rd-party assets keep+ correct licenses + attribution (the files above); generate a third-party-notices+ page. Confirm the platform's own license posture.+6. **Compliance posture:** document the platform's stance on the regimes that apply+ (GDPR/CCPA-style data rights, age gating, geo-restrictions if any, KYC/AML+ considerations for money movement) and where counsel sign-off is required. Flag, do+ not fabricate.+7. **Records:** terms-acceptance is recorded per user with version + timestamp+ (prompt `26`).++## Must-not+- Do not invent legal text as if it were vetted — mark counsel-review points explicitly.+- Do not collect/track without the required consent.+- Do not make financial guarantees or give investment advice anywhere.+- Do not strip third-party license/attribution.++## Acceptance+- [ ] ToS, Privacy, AUP pages live + linked (footer/signup/onboarding), with counsel-review flags.+- [ ] Privacy policy reflects real data practices; working data export + deletion flows.+- [ ] Consent management honoring opt-out/DNT; no pre-consent non-essential tracking.+- [ ] Crypto/financial + AI-content disclosures present, non-misleading; one-coin rule reinforced.+- [ ] All third-party licenses/attribution correct; third-party-notices page generated.+- [ ] Compliance posture documented with counsel sign-off points flagged.+- [ ] Versioned terms-acceptance recorded per user.diff --git a/prompts/production-ready/38-i18n-completion.md b/prompts/production-ready/38-i18n-completion.mdnew file mode 100644index 000000000..c45b4eeb1--- /dev/null+++ b/prompts/production-ready/38-i18n-completion.md@@ -0,0 +1,54 @@+# 38 — Internationalization (i18n) completion++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** i18n pipeline (`npm run i18n`, `i18n:extract`, `i18n:translate`, `i18n:lint`), locale files (`en.json`, `es.json`), all user-facing copy.+**Depends on:** `13`, `14`. Pairs with `31`, `34`.++## Why this matters for $1B+A $1B platform is global. Crypto + AI-agent audiences are heavily international. Full+i18n unlocks entire markets at low marginal cost and improves SEO per locale. The+pipeline already exists (`en`, `es`) — finish and expand it.++## Map+- Scripts: `i18n`, `i18n:extract`, `i18n:translate`, `i18n:lint` (recent git log:+ "i18n extraction/translation pipeline"). Locales today: `en.json`, `es.json` (++ `manifest.json`). 125 pages with significant inline copy.++## Do this+1. **Extraction coverage:** run `i18n:extract` and find untranslated/hardcoded+ strings across `pages/`, `src/`, `public/`. Externalize every user-facing string+ into the catalog with stable keys. `i18n:lint` clean (no missing keys, no+ hardcoded UI text).+2. **Complete existing locales:** fill all gaps in `es.json` so Spanish is 100%, not+ partial. Use `i18n:translate` then review for quality/context (not literal MT+ where it reads wrong).+3. **Add priority locales:** expand beyond en/es to the highest-value markets for the+ audience (e.g. add a few more major languages). Each new locale goes through+ extract → translate → review → lint.+4. **Locale-aware formatting:** numbers, dates, currencies (USDC amounts), and+ pluralization use locale-aware formatting (Intl APIs) — not hardcoded formats.+5. **RTL readiness:** if any RTL locale is added, the layout supports `dir="rtl"`+ (logical CSS properties, mirrored components) — coordinate with prompt `13`.+6. **Locale routing + SEO:** language switching is discoverable + persistent;+ per-locale URLs with `hreflang` tags and locale-specific meta (prompt `14`); the+ sitemap includes locale variants.+7. **No untranslated leaks:** every state (incl. errors, empty states, emails/+ notifications — prompts `12`, `39`) is localized. Pseudo-localize to catch+ truncation/overflow before shipping.+8. Wire `i18n:lint` into CI so new hardcoded strings fail the build.++## Must-not+- Do not ship hardcoded user-facing strings — externalize to the catalog.+- Do not leave a locale partially translated and selectable as if complete.+- Do not hardcode number/date/currency formats.++## Acceptance+- [ ] `i18n:lint` clean; all user-facing strings externalized with stable keys.+- [ ] `es.json` 100% complete and reviewed; priority new locales added via the pipeline.+- [ ] Locale-aware number/date/currency/plural formatting via Intl.+- [ ] RTL support if an RTL locale is added.+- [ ] Discoverable persistent language switch; `hreflang` + per-locale meta + sitemap.+- [ ] Errors/empty states/emails localized; pseudo-loc overflow check done.+- [ ] `i18n:lint` enforced in CI.diff --git a/prompts/production-ready/39-pwa-and-notifications.md b/prompts/production-ready/39-pwa-and-notifications.mdnew file mode 100644index 000000000..03525d3e5--- /dev/null+++ b/prompts/production-ready/39-pwa-and-notifications.md@@ -0,0 +1,57 @@+# 39 — PWA & notifications++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth+**Owns:** PWA manifest + service worker, install experience, push/email/Telegram notifications, `api/newsletter-subscribe.js`, changelog Telegram push.+**Depends on:** `10`, `25`, `33`, `37`. Pairs with `30`, `35`.++## Why this matters for $1B+Re-engagement is retention, and retention is valuation. An installable PWA + a+well-built notification system (a launch filled, a skill sold, a tip received, an+agent mentioned) brings users back without paid spend. The platform already pushes the+changelog to a $THREE-holder Telegram channel — extend that muscle into real product+notifications.++## Map+- Existing: `api/newsletter-subscribe.js`, changelog Telegram push+ (`npm run changelog:push`, `TELEGRAM_BOT_TOKEN` + `TELEGRAM_CHANGELOG_CHAT_ID`).+ `public/error-reporter.js` + `npm run generate-icons` show client + icon infra to+ build on.++## Do this+1. **PWA:** add/validate a complete web app manifest (name, icons across sizes, theme/+ background colors, display mode, start URL) so the app is installable on mobile ++ desktop. `npm run generate-icons` covers icon sizes.+2. **Service worker:** offline-friendly shell + smart caching for static assets/GLBs+ (coordinate with prompt `10` cache policy); cache-first for immutable assets,+ network-first for data; a clean offline page. Versioned SW with safe update flow+ (no stale-forever bug).+3. **Push notifications:** real web-push (with permission requested at a *good* moment,+ not on first load) for high-value events: your launch filled, skill sold, tip+ received, payout ready, agent mentioned/forked. User-controllable per category.+4. **Email:** transactional emails (welcome/onboarding — prompt `30`, receipts —+ prompt `32`, security alerts) via a real provider; double-opt-in newsletter built+ on `newsletter-subscribe.js`. Localized (prompt `38`).+5. **Telegram:** keep the holder changelog push; optionally let users opt into+ per-account Telegram alerts for their agents/launches. Reuse the existing bot infra.+6. **Preference center:** one place to manage every notification channel + category,+ with easy unsubscribe (and honoring it — prompt `37`). No notification without a+ real off switch.+7. **Instrument:** track notification sent → opened → returned (prompt `33`) so the+ re-engagement loop is measurable and tuned, not spammy.++## Must-not+- Do not request push/notification permission on first load — ask at a value moment.+- Do not send a notification type the user can't turn off.+- Do not cache so aggressively that users get stuck on a stale build (safe SW updates).+- Do not reference any coin other than $THREE in any notification copy.++## Acceptance+- [ ] Complete PWA manifest; app installable on mobile + desktop.+- [ ] Versioned service worker with smart caching, offline page, safe update flow.+- [ ] Web-push for high-value events, permission asked at a good moment, per-category control.+- [ ] Transactional emails + double-opt-in newsletter via a real provider, localized.+- [ ] Telegram changelog retained; optional per-account alerts.+- [ ] Unified preference center with honored unsubscribe.+- [ ] Notification sent→opened→returned instrumented.diff --git a/prompts/production-ready/40-launch-readiness-review.md b/prompts/production-ready/40-launch-readiness-review.mdnew file mode 100644index 000000000..47e321e5e--- /dev/null+++ b/prompts/production-ready/40-launch-readiness-review.md@@ -0,0 +1,61 @@+# 40 — Launch-readiness review (the final gate)++> Part of **Production-Ready** (`prompts/production-ready/`). Read `00-README.md` and `/CLAUDE.md` first.++**Phase:** 4 — Growth (final gate)+**Owns:** the whole platform — a top-to-bottom verification that prompts `01`–`39` actually landed.+**Depends on:** all prior prompts.++## Why this matters for $1B+This is the gate that ensures the program produced a platform you'd actually stake the+company on. It's the difference between "we did a lot of work" and "we are+production-ready." Run it as an adversarial reviewer, not a cheerleader.++## Mission+Verify, end to end, that the platform meets the production + growth bar set by this+program and by `/CLAUDE.md`'s Definition of Done — and produce a single, honest+readiness report with any remaining gaps and their owners.++## Do this+1. **Re-verify each phase against reality, not claims.** For prompts `01`–`39`, spend+ a few minutes confirming the Acceptance checklist actually holds in the live app/+ code today (things regress). Note any that slipped.+2. **Critical-path walkthrough in a real browser** (desktop + mobile, both themes):+ land → onboard → forge a model → create/own an agent → buy a skill → make an x402+ payment → launch → share. Every step works, every state designed, zero console+ errors, zero dead ends.+3. **Money paths, adversarially:** attempt double-charge, replay, price tampering,+ and unauthorized withdrawal — confirm each is blocked (prompts `07`, `18`).+4. **Quality gates green:** `npm run lint`, `npm run typecheck`, `npm run test:all`,+ `npm run audit:deploy`, `audit:pages`, `audit:web`, `audit:mcp`, `seo:meta`,+ `check:images`, `verify`, `smoke:onchain`, `smoke:mcp` — run them; all pass.+5. **Cross-cutting spot-audit:** a11y (axe on top flows), Lighthouse perf on key+ pages, mobile at 320/768/1440, secret scan, `npm audit` — confirm prompts `05`,+ `07`, `09`, `10`, `11` held.+6. **The one-coin rule:** final grep across code/copy/tests/docs/metadata — only+ $THREE, plus the two runtime-data exceptions. Zero other coins (prompt `22`).+7. **Observability + ops:** dashboards live, alerts wired, status page up, rollback+ practiced, backups restore-tested (prompts `25`–`28`).+8. **Growth instrumentation:** activation/retention/revenue funnels reporting real+ numbers; referral + notifications working (prompts `30`–`35`, `39`).+9. **Legal/safety:** ToS/privacy/AUP live, consent working, moderation + reporting+ live, data export/delete working (prompts `36`, `37`).+10. **Produce `docs/launch-readiness.md`:** a dated report with a per-area+ GREEN/YELLOW/RED status, the evidence checked, every remaining gap, its severity,+ and a clear owner/next step. Be honest — RED where it's RED. Do not claim done for+ anything you could not verify (`/CLAUDE.md`).++## Must-not+- Do not rubber-stamp. If you can't verify something, mark it unverified — never green.+- Do not skip the adversarial money-path checks.+- Do not let the one-coin grep slide.++## Acceptance+- [ ] Prompts `01`–`39` Acceptance re-verified against the live app/code; slips logged.+- [ ] Full critical-path walkthrough passes desktop + mobile + both themes, zero console errors / dead ends.+- [ ] Adversarial money-path checks all blocked.+- [ ] All quality gates + audit scripts green.+- [ ] Cross-cutting spot-audit (a11y/perf/mobile/secrets/`npm audit`) passes.+- [ ] One-coin grep clean (only $THREE + the two runtime exceptions).+- [ ] Observability/ops + growth + legal/safety verified live.+- [ ] `docs/launch-readiness.md` written: dated, per-area RAG status, gaps, owners.diff --git a/public/changelog.json b/public/changelog.jsonindex 7fa3b1d84..e68aa3e37 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T12:19:55.830Z",+ "generated_at": "2026-06-21T13:16:39.824Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"launch"]},+ {+ "date": "2026-06-21",+ "type": "launch",+ "title": "Credits",+ "summary": "Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.",+ "link": "/credits",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-21","type": "launch",@@ -97,6 +107,16 @@"infra"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "13 new step-by-step tutorials — Walk, IRL, Scene Studio, voice, vanity names and more",+ "summary": "The tutorial library got a big fill-in: every major part of three.ws that didn't have a walkthrough now has one. New guides cover putting a walking 3D avatar on your own site, placing your agent in your real room with IRL, building a scene in Scene Studio, animating any avatar, turning a selfie into a rigged avatar, importing an avatar by link, viewing a model in AR, giving an agent a real voice with lip-sync, paying for an x402 service from your agent, claiming a .threews.sol name and getting paid by it, reading an agent's on-chain reputation, mining a Solana vanity address, and a no-code getting-started. Every tutorial is grounded in the live product, with copy-paste steps and troubleshooting.",+ "link": "/tutorials",+ "tags": [+ "docs"+ ]+ },{"date": "2026-06-21","type": "update",@@ -181,6 +201,16 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Credits: top up with SOL or $THREE, spend on generation and agents",+ "summary": "You can now keep a prepaid balance on three.ws. Deposit SOL or $THREE from your wallet and it's credited to your account at the live USD value; spend those credits on paid compute like High-quality 3D generation — no per-action wallet popup each time. Holding $THREE still discounts every spend (up to 30%), so the credits you buy go further the bigger your bag. Deposits are verified on-chain and bound to a wallet linked to your account, your balance and full history live at /credits, and a failed generation is automatically refunded. Forge High now accepts credits as a payment option alongside holding $THREE or paying per generation.",+ "link": "/credits",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",@@ -372,6 +402,16 @@"improvement"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Game-Ready export is now a $THREE perk — hold, or pay per export",+ "summary": "Turning a generated or uploaded model into a clean, engine-ready asset — one-click retopology to a poly budget with a PBR texture re-bake, delivered as a GLB plus an FBX for Unity and Unreal — is now a $THREE benefit. Hold $THREE and every Game-Ready export is free; if you don't hold, pay once per export in $THREE without leaving the result view, then the export runs immediately. Text→3D generation at Draft and Standard stays free for everyone. The export runs real GPU retopology on our remesh service, so holders fund it by holding rather than us metering everyone — the same hold-or-pay model already used for High-quality generation.",+ "link": "/forge",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex ed37f8632..810ac79e9 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>launch</category><description>Configure your 3D agent to trade Oracle conviction automatically: set the minimum score, position size, daily and open-position caps, narrative filters and Telegram alerts, then arm it in simulate or live mode. Every action is graded against the outcome.</description></item>+ <item>+ <title>Credits</title>+ <link>https://three.ws/credits</link>+ <guid isPermaLink="false">2026-06-21:Credits</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.</description>+ </item><item><title>Docs · Walk Avatar</title><link>https://three.ws/docs/walk</link>@@ -78,6 +86,14 @@<category>improvement</category><description>The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.</description></item>+ <item>+ <title>13 new step-by-step tutorials — Walk, IRL, Scene Studio, voice, vanity names and more</title>+ <link>https://three.ws/tutorials</link>+ <guid isPermaLink="false">2026-06-21:13 new step-by-step tutorials — Walk, IRL, Scene Studio, voice, vanity names and more</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>docs</category>+ <description>The tutorial library got a big fill-in: every major part of three.ws that didn't have a walkthrough now has one. New guides cover putting a walking 3D avatar on your own site, placing your agent in your real room with IRL, building a scene in Scene Studio, animating any avatar, turning a selfie into a rigged avatar, importing an avatar by link, viewing a model in AR, giving an agent a real voice with lip-sync, paying for an x402 service from your agent, claiming a .threews.sol name and getting paid by it, reading an agent's on-chain reputation, mining a Solana vanity address, and a no-code getting-started. Every tutorial is grounded in the live product, with copy-paste steps and troubleshooting.</description>+ </item><item><title>Affiliate dashboard now shows who you referred</title><link>https://three.ws/dashboard/referrals</link>@@ -142,6 +158,14 @@<category>infra</category><description>The /launches coin page pulls creator fee-sharing earnings live from pump.fun. We put that call behind a circuit breaker (built on the well-tested cockatiel library rather than home-grown code): if pump.fun slows down or errors, the breaker trips after a few failures and the page instantly skips that one enrichment instead of every visitor waiting out the timeout. The earnings simply show as unavailable until pump.fun recovers, and the rest of the page — registry, intel, outcome, trader record — was never affected. Same approach is now available platform-wide for other third-party data sources.</description></item>+ <item>+ <title>Credits: top up with SOL or $THREE, spend on generation and agents</title>+ <link>https://three.ws/credits</link>+ <guid isPermaLink="false">2026-06-21:Credits: top up with SOL or $THREE, spend on generation and agents</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>You can now keep a prepaid balance on three.ws. Deposit SOL or $THREE from your wallet and it's credited to your account at the live USD value; spend those credits on paid compute like High-quality 3D generation — no per-action wallet popup each time. Holding $THREE still discounts every spend (up to 30%), so the credits you buy go further the bigger your bag. Deposits are verified on-chain and bound to a wallet linked to your account, your balance and full history live at /credits, and a failed generation is automatically refunded. Forge High now accepts credits as a payment option alongside holding $THREE or paying per generation.</description>+ </item><item><title>Describe-it-to-3D no longer shows a confusing third-party billing error</title><link>https://three.ws/create/prompt</link>@@ -286,6 +310,14 @@<category>feature</category><description>The guided tour now has a free-roam mode (the 🧭 button, or press R). Click anywhere on the page and the 3D guide walks there; grab it and drag it around; drag it to the top or bottom edge and the page scrolls so you can walk it up and down the whole page. Press play to drop right back into the tour where you left off. We also stopped the corner walking companion from doubling up: while the guided tour is running, the corner companion steps aside so there's only ever one avatar on screen, and it returns the moment the tour ends.</description></item>+ <item>+ <title>Game-Ready export is now a $THREE perk — hold, or pay per export</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-21:Game-Ready export is now a $THREE perk — hold, or pay per export</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Turning a generated or uploaded model into a clean, engine-ready asset — one-click retopology to a poly budget with a PBR texture re-bake, delivered as a GLB plus an FBX for Unity and Unreal — is now a $THREE benefit. Hold $THREE and every Game-Ready export is free; if you don't hold, pay once per export in $THREE without leaving the result view, then the export runs immediately. Text→3D generation at Draft and Standard stays free for everyone. The export runs real GPU retopology on our remesh service, so holders fund it by holding rather than us metering everyone — the same hold-or-pay model already used for High-quality generation.</description>+ </item><item><title>Grind an agent's vanity wallet right on its page — with your CPU cores</title><link>https://three.ws/changelog</link>diff --git a/public/docs/index.html b/public/docs/index.htmlnew file mode 100644index 000000000..b719f588b--- /dev/null+++ b/public/docs/index.html@@ -0,0 +1,275 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Docs · three.ws</title>+ <link rel="icon" href="/favicon.ico" />+ <meta name="description" content="Documentation for three.ws — build, embed, and monetise 3D AI agents. Guides, tutorials, API reference, and SDK docs." />+ <link rel="canonical" href="https://three.ws/docs" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Documentation · three.ws" />+ <meta property="og:description" content="Guides, tutorials, API reference, and SDK docs for building 3D AI agents." />+ <meta property="og:url" content="https://three.ws/docs" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=docs&t=Documentation&d=Build%2C+embed%2C+and+monetise+3D+AI+agents.&p=%2Fdocs" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <style>+ :root { color-scheme: dark; --bg:#000; --panel:#0a0a0b; --line:#1c1c1f; --fg:#e7e7ea; --mut:#8a8a93; --dim:#5a5a62; --brand:#69e16f; --link:#9ad7ff; }+ * { box-sizing: border-box; }+ html, body { margin: 0; }+ body { font: 15px/1.7 -apple-system, system-ui, 'Segoe UI', sans-serif; background: var(--bg); color: var(--fg); }+ a { color: var(--link); text-decoration: none; }+ a:hover { text-decoration: underline; }+ .topbar { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 14px; padding: 12px 18px; background: rgba(0,0,0,.82); backdrop-filter: blur(10px); border-bottom: 1px solid var(--line); }+ .brand { display: flex; align-items: center; gap: 8px; color: #fff; font-weight: 600; letter-spacing: -.01em; }+ .brand img { width: 16px; height: 16px; }+ .brand small { color: var(--mut); font-weight: 500; }+ .menu-btn { display: none; margin-left: auto; background: #141417; color: var(--fg); border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px; cursor: pointer; font: inherit; }+ .search { margin-left: auto; flex: 0 1 260px; }+ .search input { width: 100%; background: #141417; border: 1px solid var(--line); border-radius: 8px; color: var(--fg); padding: 7px 11px; font: inherit; outline: none; }+ .search input:focus { border-color: #2f2f35; }+ .layout { display: grid; grid-template-columns: 264px minmax(0,1fr); max-width: 1180px; margin: 0 auto; }+ .sidebar { border-right: 1px solid var(--line); padding: 22px 14px 80px; height: calc(100vh - 53px); position: sticky; top: 53px; overflow-y: auto; }+ .grp { margin: 0 0 18px; }+ .grp h3 { font-size: 11px; text-transform: uppercase; letter-spacing: .08em; color: var(--dim); margin: 0 0 7px; padding: 0 10px; }+ .sidebar a { display: block; color: var(--mut); padding: 5px 10px; border-radius: 7px; font-size: 13.5px; }+ .sidebar a:hover { color: var(--fg); background: #111114; text-decoration: none; }+ .sidebar a.active { color: var(--brand); background: rgba(105,225,111,.08); }+ main { padding: 34px 40px 120px; min-height: calc(100vh - 53px); }+ .content { max-width: 760px; }+ .content h1 { font-size: 30px; letter-spacing: -.02em; margin: 0 0 18px; color: #fff; }+ .content h2 { font-size: 21px; margin: 38px 0 12px; padding-top: 10px; border-top: 1px solid var(--line); color: #f2f2f4; }+ .content h3 { font-size: 16px; margin: 26px 0 8px; color: #f2f2f4; }+ .content p, .content li { color: #c4c4ca; }+ .content ul, .content ol { padding-left: 22px; }+ .content li { margin: 4px 0; }+ .content code { background: #141417; border: 1px solid var(--line); border-radius: 5px; padding: 1.5px 5px; font-size: 13px; font-family: ui-monospace, 'SF Mono', Menlo, monospace; color: #e6c07b; }+ .content pre { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; padding: 16px; overflow-x: auto; }+ .content pre code { background: none; border: none; padding: 0; color: #cdd6e4; }+ .content blockquote { border-left: 3px solid #2a2a30; margin: 16px 0; padding: 2px 16px; color: var(--mut); }+ .content table { border-collapse: collapse; width: 100%; margin: 16px 0; font-size: 14px; }+ .content th, .content td { border: 1px solid var(--line); padding: 8px 12px; text-align: left; }+ .content th { background: #111114; }+ .content img { max-width: 100%; border-radius: 8px; }+ .content hr { border: none; border-top: 1px solid var(--line); margin: 32px 0; }+ .crumbs { font-size: 13px; color: var(--dim); margin: 0 0 18px; }+ .crumbs a { color: var(--mut); }+ .skeleton span { display: block; height: 14px; background: linear-gradient(90deg,#101013,#17171b,#101013); background-size: 200% 100%; border-radius: 6px; margin: 14px 0; animation: sh 1.2s infinite; }+ @keyframes sh { 0%{background-position:200% 0} 100%{background-position:-200% 0} }+ .error { border: 1px solid #3a2326; background: #160d0f; border-radius: 12px; padding: 24px; }+ .error h1 { font-size: 22px; margin: 0 0 8px; }+ .hero-cards { display: grid; grid-template-columns: repeat(auto-fill,minmax(220px,1fr)); gap: 12px; margin: 22px 0 0; }+ .card { display: block; border: 1px solid var(--line); border-radius: 12px; padding: 16px; background: var(--panel); transition: border-color .15s, transform .15s; }+ .card:hover { border-color: #2f2f35; transform: translateY(-2px); text-decoration: none; }+ .card b { color: #fff; display: block; margin-bottom: 4px; }+ .card span { color: var(--mut); font-size: 13px; }+ .toc-empty { color: var(--mut); }+ @media (max-width: 860px) {+ .layout { grid-template-columns: 1fr; }+ .menu-btn { display: block; }+ .search { display: none; }+ .sidebar { position: fixed; inset: 53px 0 auto 0; height: auto; max-height: calc(100vh - 53px); background: #050506; z-index: 15; transform: translateY(-120%); transition: transform .2s; }+ .sidebar.open { transform: translateY(0); }+ main { padding: 24px 20px 100px; }+ }+ </style>+</head>+<body>+ <header class="topbar">+ <a class="brand" href="/"><img src="/three.svg" alt="" />three.ws <small>docs</small></a>+ <div class="search"><input id="filter" type="search" placeholder="Filter docs…" aria-label="Filter docs" autocomplete="off" /></div>+ <button class="menu-btn" id="menuBtn" aria-expanded="false">Menu</button>+ </header>+ <div class="layout">+ <nav class="sidebar" id="sidebar" aria-label="Documentation"></nav>+ <main>+ <div class="content" id="content"></div>+ </main>+ </div>++ <script type="module">+ import { marked } from 'https://cdn.jsdelivr.net/npm/marked@12/lib/marked.esm.js';++ // Curated registry — group → [slug, title, blurb]. Tutorial slugs resolve from+ // /docs/tutorials/<slug>.md via fallback, so they share the flat /docs/<slug> URL.+ const GROUPS = [+ ['Getting started', [+ ['introduction', 'Introduction', 'What three.ws is and who it is for.'],+ ['quick-start', 'Quick start', 'Ship your first 3D agent in minutes.'],+ ['how-it-works', 'How it works', 'The pipeline from selfie to embedded agent.'],+ ['agents-vs-avatars', 'Agents vs avatars', 'The two primitives and how they relate.'],+ ]],+ ['Tutorials', [+ ['getting-started', 'Getting started', 'Hands-on walkthrough of the platform.'],+ ['first-agent', 'Build your first agent', 'Create, configure, and publish an agent.'],+ ['custom-skill', 'Write a custom skill', 'Give an agent a new paid capability.'],+ ['embed-on-website', 'Embed on a website', 'Drop an agent into any site.'],+ ['personal-ai-site', 'Personal AI site', 'Your own agent at yourname.three.ws.'],+ ['register-onchain', 'Register on-chain', 'Put an agent on ERC-8004.'],+ ]],+ ['Core concepts', [+ ['agent-system', 'Agent system', 'Identity, wallet, persona, and tools.'],+ ['architecture', 'Architecture', 'How the platform is put together.'],+ ['layers', 'Layers', 'The stack from rendering to payments.'],+ ['memory', 'Memory', 'How agents remember across sessions.'],+ ['multi-agent', 'Multi-agent', 'Agents coordinating with agents.'],+ ['permissions', 'Permissions', 'Scopes, keys, and what agents may do.'],+ ['skills', 'Skills', 'Reusable, monetisable agent capabilities.'],+ ]],+ ['Avatars & 3D', [+ ['avatar-creation', 'Avatar creation', 'Selfie to rigged 3D avatar.'],+ ['character-studio', 'Character studio', 'Author and pose characters.'],+ ['ar', 'AR', 'View agents in augmented reality.'],+ ['viewer', 'Viewer', 'The 3D viewer and its controls.'],+ ['editor', 'Editor', 'Editing meshes, materials, and scenes.'],+ ['validation', 'Validation', 'glTF validation and quality gates.'],+ ]],+ ['Embed & SDK', [+ ['embedding', 'Embedding', 'The <agent-3d> embed model.'],+ ['web-component', 'Web component', 'Using the custom element.'],+ ['widget-api', 'Widget API', 'Programmatic widget control.'],+ ['widget-studio', 'Widget studio', 'Design embeds without code.'],+ ['widgets', 'Widgets', 'Chat widgets and transcripts.'],+ ['js-api', 'JavaScript API', 'The browser SDK surface.'],+ ['sdk', 'SDK', 'Server and agent SDKs.'],+ ]],+ ['API & deploy', [+ ['api-reference', 'REST API', 'Endpoints, params, and responses.'],+ ['authentication', 'Authentication', 'Sessions, keys, and bearer auth.'],+ ['configuration', 'Configuration', 'Environment and platform settings.'],+ ['mcp', 'MCP', 'Model Context Protocol integration.'],+ ['deployment', 'Deployment', 'Shipping agents to production.'],+ ]],+ ['On-chain', [+ ['erc8004', 'ERC-8004', 'On-chain agent registration.'],+ ['reputation', 'Reputation', 'Reviews, attestations, trust scores.'],+ ['smart-contracts', 'Smart contracts', 'The contracts behind the platform.'],+ ['security', 'Security', 'Threat model and protections.'],+ ]],+ ['Reference', [+ ['agent-manifest', 'Agent manifest', 'The agent descriptor format.'],+ ['examples', 'Examples', 'Copy-paste recipes.'],+ ['troubleshooting', 'Troubleshooting', 'Fixes for common issues.'],+ ['contributing', 'Contributing', 'How to contribute.'],+ ['changelog', 'Changelog', 'Documentation changes.'],+ ['popular-3d-github-repos', 'Popular 3D repos', 'Useful open-source 3D projects.'],+ ]],+ ];+ const TUTORIAL_SLUGS = new Set(['getting-started', 'first-agent', 'custom-skill', 'embed-on-website', 'personal-ai-site', 'register-onchain']);+ const TITLES = Object.fromEntries(GROUPS.flatMap(([, items]) => items.map(([s, t]) => [s, t])));++ const sidebar = document.getElementById('sidebar');+ const content = document.getElementById('content');+ const filter = document.getElementById('filter');+ const menuBtn = document.getElementById('menuBtn');++ function buildSidebar() {+ sidebar.innerHTML = GROUPS.map(([grp, items]) => `+ <div class="grp" data-grp="${grp.toLowerCase()}">+ <h3>${grp}</h3>+ ${items.map(([slug, title]) => `<a href="/docs/${slug}" data-slug="${slug}" data-title="${title.toLowerCase()}">${title}</a>`).join('')}+ </div>`).join('');+ }++ function slugFromPath() {+ const m = location.pathname.replace(/\/+$/, '').match(/^\/docs\/(.+)$/);+ return m ? decodeURIComponent(m[1]) : '';+ }++ function setActive(slug) {+ sidebar.querySelectorAll('a').forEach((a) => a.classList.toggle('active', a.dataset.slug === slug));+ }++ async function fetchDoc(slug) {+ const tries = TUTORIAL_SLUGS.has(slug)+ ? [`/docs/tutorials/${slug}.md`, `/docs/${slug}.md`]+ : [`/docs/${slug}.md`, `/docs/tutorials/${slug}.md`];+ for (const url of tries) {+ const res = await fetch(url);+ if (res.ok) return res.text();+ }+ return null;+ }++ function renderIndex() {+ document.title = 'Docs · three.ws';+ setActive(null);+ content.innerHTML = `+ <h1>Documentation</h1>+ <p>Everything you need to build, embed, and monetise 3D AI agents on three.ws. New here? Start with the <a href="/docs/quick-start">quick start</a>.</p>+ ${GROUPS.map(([grp, items]) => `+ <h2>${grp}</h2>+ <div class="hero-cards">+ ${items.map(([slug, title, blurb]) => `<a class="card" href="/docs/${slug}"><b>${title}</b><span>${blurb}</span></a>`).join('')}+ </div>`).join('')}`;+ }++ function renderError(slug) {+ document.title = 'Not found · three.ws docs';+ content.innerHTML = `+ <div class="error">+ <h1>That doc doesn't exist</h1>+ <p>We couldn't find a page for <code>${slug.replace(/[<>&]/g, '')}</code>. It may have moved or been renamed.</p>+ <p><a href="/docs">← Back to all docs</a></p>+ </div>`;+ }++ async function renderDoc(slug, { push } = {}) {+ setActive(slug);+ content.innerHTML = '<div class="skeleton"><span style="width:40%"></span><span style="width:90%"></span><span style="width:80%"></span><span style="width:85%"></span><span style="width:60%"></span></div>';+ const md = await fetchDoc(slug);+ if (md == null) { renderError(slug); return; }+ const html = marked.parse(md, { breaks: false, gfm: true });+ content.innerHTML = `<div class="crumbs"><a href="/docs">Docs</a> / ${TITLES[slug] || slug}</div>` + html;+ // Rewrite intra-doc relative .md links to client-side doc routes.+ content.querySelectorAll('a[href$=".md"]').forEach((a) => {+ const leaf = a.getAttribute('href').replace(/^\.?\/?/, '').replace(/^tutorials\//, '').replace(/\.md$/, '');+ a.setAttribute('href', `/docs/${leaf}`);+ });+ document.title = `${TITLES[slug] || slug} · three.ws docs`;+ content.scrollIntoView({ block: 'start' });+ if (push) history.pushState({ slug }, '', `/docs/${slug}`);+ }++ function route(opts) {+ const slug = slugFromPath();+ if (!slug) renderIndex();+ else renderDoc(slug, opts);+ }++ // Intercept sidebar / in-content doc links for SPA navigation.+ document.addEventListener('click', (e) => {+ const a = e.target.closest('a[href^="/docs/"]');+ if (!a || a.target === '_blank' || e.metaKey || e.ctrlKey) return;+ e.preventDefault();+ const slug = a.getAttribute('href').replace(/^\/docs\//, '').replace(/\/+$/, '');+ sidebar.classList.remove('open');+ renderDoc(slug, { push: true });+ });+ window.addEventListener('popstate', () => route());++ filter.addEventListener('input', () => {+ const q = filter.value.trim().toLowerCase();+ sidebar.querySelectorAll('.grp').forEach((grp) => {+ let any = false;+ grp.querySelectorAll('a').forEach((a) => {+ const hit = !q || a.dataset.title.includes(q) || a.dataset.slug.includes(q);+ a.style.display = hit ? '' : 'none';+ if (hit) any = true;+ });+ grp.style.display = any ? '' : 'none';+ });+ });+ menuBtn.addEventListener('click', () => {+ const open = sidebar.classList.toggle('open');+ menuBtn.setAttribute('aria-expanded', String(open));+ });++ buildSidebar();+ route();+ </script>+ <script src="/brand.js" defer></script>+</body>+</html>diff --git a/public/features.json b/public/features.jsonindex a5be1d27a..3180eab3c 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T12:19:55.764Z",+ "generated_at": "2026-06-21T13:16:39.652Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1180,6 +1180,16 @@"title": "Account","description": "Sign-in, dashboard, billing.","pages": [+ {+ "path": "/credits",+ "title": "Credits",+ "description": "Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.",+ "added": "2026-06-21",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/login","title": "Sign in",diff --git a/public/legal/content-policy.html b/public/legal/content-policy.htmlnew file mode 100644index 000000000..e7f4a37a4--- /dev/null+++ b/public/legal/content-policy.html@@ -0,0 +1,105 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>Content Policy · three.ws</title>+ <link rel="icon" href="/favicon.ico" />+ <style>+ :root { color-scheme: dark; }+ * { box-sizing: border-box; }+ body {+ font: 16px/1.7 -apple-system, system-ui, 'Segoe UI', sans-serif;+ background: #000000;+ color: #ccc;+ margin: 0;+ padding: 48px 24px 80px;+ }+ .wrap { max-width: 720px; margin: 0 auto; }+ .brand { font-size: 12px; letter-spacing: .1em; text-transform: uppercase; color: #ffffff; margin: 0 0 32px; display: block; text-decoration: none; }+ .header-logo { width: 14px; height: 14px; vertical-align: -2px; margin-right: 6px; }+ h1 { font-size: 32px; color: #eee; margin: 0 0 6px; letter-spacing: -.02em; }+ .meta { color: #555; font-size: 14px; margin: 0 0 40px; }+ h2 { font-size: 18px; color: #eee; margin: 40px 0 10px; }+ p, li { color: #aaa; font-size: 15px; }+ ul { padding-left: 20px; }+ li { margin-bottom: 6px; }+ a { color: #cccccc; }+ hr { border: none; border-top: 1px solid #1e1e1e; margin: 48px 0; }+ .foot { color: #555; font-size: 13px; }+ </style>++ <meta name="description" content="Content policy for three.ws — what you may publish, mint, and monetise on the platform.">+ <link rel="canonical" href="https://three.ws/legal/content-policy">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="Content Policy · three.ws">+ <meta property="og:description" content="Content policy for three.ws — what you may publish, mint, and monetise on the platform.">+ <meta property="og:url" content="https://three.ws/legal/content-policy">+ <meta property="og:image" content="https://three.ws/api/page-og?s=legal&t=Content+Policy&d=What+you+may+publish+on+three.ws.&p=%2Flegal%2Fcontent-policy">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="Content Policy · three.ws">+ <meta name="twitter:description" content="What you may publish, mint, and monetise on three.ws.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=legal&t=Content+Policy&d=What+you+may+publish+on+three.ws.&p=%2Flegal%2Fcontent-policy">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Content Policy","description":"Content policy for three.ws.","url":"https://three.ws/legal/content-policy","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <meta property="og:image:alt" content="Content Policy — three.ws">+ <meta name="twitter:site" content="@trythreews">+</head>+<body>+<div class="wrap">+ <a class="brand" href="/"><img src="/three.svg" alt="" class="header-logo" aria-hidden="true" />three.ws</a>+ <h1>Content Policy</h1>+ <p class="meta">Effective: June 21, 2026 · <a href="/legal/tos.html">Terms of Service</a> · <a href="/legal/privacy.html">Privacy Policy</a></p>++ <p>three.ws lets anyone create, embed, and monetise 3D AI agents, avatars, and the assets that surround them. This Content Policy explains what you may and may not publish, mint, or sell through the Service. It supplements, and is incorporated into, our <a href="/legal/tos.html">Terms of Service</a>. By uploading, generating, listing, or transacting any content you agree to these rules.</p>++ <h2>1. Scope</h2>+ <p>"Content" means anything you submit to or generate on three.ws: avatars, meshes, textures, animations, agent personas and prompts, chat messages, marketplace listings, profile copy, embedded widgets, and any token, skill, or service you launch or sell through the platform.</p>++ <h2>2. You own and warrant your content</h2>+ <p>You retain ownership of content you create. By publishing it you confirm that you hold all rights necessary to do so and that the content does not infringe anyone else's intellectual-property, privacy, or publicity rights. Do not upload selfies, likenesses, brands, or 3D scans of people without their consent or of trademarks you do not own.</p>++ <h2>3. Prohibited content</h2>+ <p>You may not create, upload, mint, list, or distribute content that:</p>+ <ul>+ <li>Is illegal, or facilitates illegal activity, under applicable law.</li>+ <li>Sexualises minors, or depicts non-consensual, exploitative, or violent sexual content.</li>+ <li>Promotes terrorism, violent extremism, human trafficking, or credible threats of violence.</li>+ <li>Harasses, defames, or doxxes a person, or impersonates a real individual or organisation to deceive.</li>+ <li>Infringes copyright, trademark, or other IP — including unlicensed brand assets, characters, or game rips.</li>+ <li>Contains malware, deceptive scripts, or code that compromises a user, wallet, or embedding site.</li>+ <li>Is designed to defraud — fake giveaways, phishing, impersonated payment requests, or rug-pull mechanics.</li>+ </ul>++ <h2>4. Agents, personas, and AI output</h2>+ <p>Agents you publish must not be configured to produce the prohibited content above, to impersonate a real person without disclosure, or to give advice (financial, legal, medical) presented as professional guidance. You are responsible for your agent's behaviour and for the prompts and knowledge you give it. We may suspend agents that generate harmful output at scale.</p>++ <h2>5. Tokens, payments, and financial content</h2>+ <p>three.ws includes on-chain tooling (x402 payments, token launches, wallets). You are solely responsible for compliance with the securities, money-transmission, and tax laws of your jurisdiction. Do not use the platform to launder funds, evade sanctions, or market a token with false or misleading claims. Nothing on three.ws is financial advice, and any token you launch is your own undertaking, not an endorsement by us.</p>++ <h2>6. Marketplace and monetisation</h2>+ <p>Items you list for sale must be accurately described, must be content you are entitled to sell, and must deliver what the listing promises. Reviews must reflect genuine experience. We may delist items, reverse payouts for fraud, and withhold revenue tied to policy violations.</p>++ <h2>7. Embedded agents</h2>+ <p>When you embed an agent on a third-party site you remain responsible for its content there. Do not embed agents on pages that violate this policy, and do not use the embed to track or collect data from end users beyond what your own privacy policy discloses.</p>++ <h2>8. Reporting and enforcement</h2>+ <p>If you believe content on three.ws violates this policy or your rights, email <a href="mailto:[email protected]">[email protected]</a> with the URL and a description. We review reports and may remove content, suspend accounts or agents, reverse transactions, or report to authorities. Enforcement is at our discretion and does not waive any other remedy.</p>++ <h2>9. Changes</h2>+ <p>We may update this Content Policy as the platform and the law evolve. Material changes will be posted here with a new effective date; continued use after that date constitutes acceptance.</p>++ <h2>10. Contact</h2>+ <p>Questions about this policy? Email <a href="mailto:[email protected]">[email protected]</a>. To report abuse, use <a href="mailto:[email protected]">[email protected]</a>.</p>++ <hr>+ <p class="foot">three.ws · <a href="/legal/tos.html">Terms of Service</a> · <a href="/legal/privacy.html">Privacy Policy</a> · <a href="/">Home</a></p>+</div>+ <script src="/brand.js" defer></script>+</body>+</html>diff --git a/public/llms-full.txt b/public/llms-full.txtindex 964453aff..82d84f23a 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -716,6 +716,12 @@ Inspect on-chain reputation scores and attestations for any agent.Sign-in, dashboard, billing.+### Credits++URL: https://three.ws/credits++Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.+### Sign inURL: https://three.ws/logindiff --git a/public/llms.txt b/public/llms.txtindex cd9a9e0b6..fd88c2ccd 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -146,6 +146,7 @@ Manage, talk to, and deploy individual agents.Sign-in, dashboard, billing.+- [Credits](https://three.ws/credits): Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.- [Sign in](https://three.ws/login): Sign in with email, GitHub, or a connected wallet.- [Create account](https://three.ws/register): Create a new three.ws account.- [Forgot password](https://three.ws/forgot-password): Request a password-reset email.diff --git a/public/nav-data.js b/public/nav-data.jsindex b504306e8..227b3028a 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -233,6 +233,7 @@ export const NAV_GROUPS = [{ title: 'Tutorials', href: '/tutorials', desc: 'Step-by-step guides' },{ title: 'Chat', href: '/chat', desc: 'Talk to your agent' },{ title: 'Pay', href: '/pay', desc: 'Agent payments — x402 + USDC' },+ { title: 'Credits', href: '/credits', desc: 'Top up & spend — SOL or $THREE' },{title: 'Avatar SDK',href: '/avatar-sdk',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 9abf0375c..ec268cf8a 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 293 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 294 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 293 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 294 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -932,10 +932,17 @@<section class="sm-section" id="account"><header>- <h2>Account<span class="sm-count" data-count>8</span></h2>+ <h2>Account<span class="sm-count" data-count>9</span></h2><p class="sm-section-desc">Sign-in, dashboard, billing.</p></header><ul class="sm-list">+ <li>+ <a href="/credits">+ <span class="sm-title">Credits</span>+ <span class="sm-path">/credits</span>+ <span class="sm-desc">Top up with SOL or $THREE and spend credits on 3D generation, agents, and compute. Hold $THREE for up to 30% off every spend.</span>+ </a>+ </li><li><a href="/login"><span class="sm-title">Sign in</span>diff --git a/public/tutorials-manifest.js b/public/tutorials-manifest.jsindex d145fa895..d445e7f6f 100644--- a/public/tutorials-manifest.js+++ b/public/tutorials-manifest.js@@ -100,6 +100,46 @@previewModel: '/animations/robotexpressive.glb',ctaPrimary: { label: 'Open My Agents', href: '/my-agents' },},+ {+ slug: 'selfie-to-avatar',+ tier: 'easy',+ title: 'Turn a selfie into a 3D avatar',+ blurb: 'Snap or upload a photo and get a rigged 3D avatar that can walk, wave, and talk — then put it on an agent.',+ builds: 'A rigged 3D avatar of a real face, ready to animate',+ time: '8 min',+ previewModel: '/avatars/cz.glb',+ ctaPrimary: { label: 'Open the Scanner', href: '/scan' },+ },+ {+ slug: 'view-in-ar',+ tier: 'easy',+ title: 'View your 3D model in AR',+ blurb: 'See any three.ws model in augmented reality and walk around it in your kitchen — straight from the browser, no app to install. iOS Quick Look and Android WebXR.',+ builds: 'A 3D model you can place and view in your real room',+ time: '8 min',+ previewModel: '/animations/robotexpressive.glb',+ ctaPrimary: { label: 'Open the Forge', href: '/forge' },+ },+ {+ slug: 'import-avatar-url',+ tier: 'easy',+ title: 'Import an avatar by URL',+ blurb: 'Bring a Ready Player Me or any hosted glTF/GLB avatar into three.ws by link — auto-validated, auto-rigged, ready for an agent.',+ builds: 'An imported avatar live on your account from a single URL',+ time: '6 min',+ previewModel: '/avatars/cz.glb',+ ctaPrimary: { label: 'Import an avatar', href: '/import/rpm' },+ },+ {+ slug: 'walk-companion',+ tier: 'easy',+ title: 'Add the Walk Companion to your site',+ blurb: 'Drop a 3D avatar that strolls across any web page — corner mascot or full-page playground — with one script tag, the npm SDK, or a postMessage bridge.',+ builds: 'A walking 3D avatar living on your own website',+ time: '15 min',+ previewModel: '/animations/soldier.glb',+ ctaPrimary: { label: 'Open Walk', href: '/walk' },+ },/* ────────────────────────── MIDDLE ────────────────────────── */{@@ -212,6 +252,56 @@previewModel: '/avatars/cz.glb',ctaPrimary: { label: 'Open Library', href: '/library' },},+ {+ slug: 'animate-your-avatar',+ tier: 'middle',+ title: 'Animate your avatar',+ blurb: 'Apply the pre-baked clip library to any humanoid rig in the Animation Studio — browse, preview, retarget idle/walk/emotes onto your model, and export an animated GLB.',+ builds: 'Your avatar playing the full motion library, exported as an animated GLB',+ time: '20 min',+ previewModel: '/animations/robotexpressive.glb',+ ctaPrimary: { label: 'Open Animation Studio', href: '/pose' },+ },+ {+ slug: 'build-a-scene',+ tier: 'middle',+ title: 'Build a 3D scene in Scene Studio',+ blurb: 'Import GLBs, arrange objects, tune materials and lights, and export — a full three.js scene editor running in the browser.',+ builds: 'A composed 3D scene exported as a GLB',+ time: '30 min',+ previewModel: '/animations/soldier.glb',+ ctaPrimary: { label: 'Open Scene Studio', href: '/scene' },+ },+ {+ slug: 'place-agent-irl',+ tier: 'middle',+ title: 'Place your agent in the real world (IRL)',+ blurb: 'Use camera passthrough, a joystick, and tap-to-place to drop your 3D agent into your physical space — and understand how location privacy works.',+ builds: 'Your agent standing in your real room, pinned to a place',+ time: '15 min',+ previewModel: '/avatars/cz.glb',+ ctaPrimary: { label: 'Open IRL', href: '/irl' },+ },+ {+ slug: 'voice-and-lipsync',+ tier: 'middle',+ title: 'Give your agent a voice with lipsync',+ blurb: 'Add real-time text-to-speech with synchronized mouth movement — pick or clone a voice, drive visemes from audio, and wire it into a live agent.',+ builds: 'An agent that speaks out loud with its mouth in sync',+ time: '25 min',+ previewModel: '/animations/robotexpressive.glb',+ ctaPrimary: { label: 'Open Voice Lab', href: '/voice' },+ },+ {+ slug: 'pay-for-x402-service',+ tier: 'middle',+ title: 'Discover and pay for an x402 service',+ blurb: 'Browse the x402 Bazaar and call a paid API from your agent — the 402 challenge, the USDC payment, and the retry, end to end.',+ builds: 'Your agent paying USDC to call a real x402 endpoint',+ time: '30 min',+ previewModel: '/avatars/cz.glb',+ ctaPrimary: { label: 'Open the Bazaar', href: '/bazaar' },+ },/* ───────────────────────── ADVANCED ───────────────────────── */{@@ -304,6 +394,36 @@previewModel: '/animations/robotexpressive.glb',ctaPrimary: { label: 'Deployment docs', href: '/docs#deployment' },},+ {+ slug: 'claim-threews-name',+ tier: 'advanced',+ title: 'Claim a .threews.sol name & get paid by name',+ blurb: 'Mint a *.threews.sol Solana subdomain for your agent and accept USDC payments addressed to the name instead of a raw wallet.',+ builds: 'A human-readable .threews.sol name that resolves to your agent and receives payments',+ time: '40 min',+ previewModel: '/avatars/cz.glb',+ ctaPrimary: { label: 'Claim a name', href: '/threews/claim' },+ },+ {+ slug: 'agent-reputation',+ tier: 'advanced',+ title: "Read an agent's on-chain reputation (ERC-8004)",+ blurb: 'Explore and read ERC-8004 reputation — how feedback and attestations accrue, and how to query an agent\'s score from code, the API, or MCP.',+ builds: 'A reputation read on any registered agent, on-chain and via API',+ time: '35 min',+ previewModel: '/animations/robotexpressive.glb',+ ctaPrimary: { label: 'Open Reputation Explorer', href: '/reputation' },+ },+ {+ slug: 'mine-vanity-address',+ tier: 'advanced',+ title: 'Mine a Solana vanity address',+ blurb: 'Grind a custom-prefix Solana address in the browser, then prove how it was made with the proof-of-grind receipt, gallery, and bounty market.',+ builds: 'A vanity Solana address with a verifiable proof-of-grind receipt',+ time: '30 min',+ previewModel: '/animations/soldier.glb',+ ctaPrimary: { label: 'Open Vanity Wallet', href: '/vanity-wallet' },+ },];const TIER_META = {diff --git a/scripts/audit-links.mjs b/scripts/audit-links.mjsindex 08b7fb9cf..9a1efe8ac 100644--- a/scripts/audit-links.mjs+++ b/scripts/audit-links.mjs@@ -73,8 +73,10 @@ const vercel = JSON.parse(readFileSync(join(ROOT, 'vercel.json'), 'utf8'));const ASSET_CATCHALL = '/(.*\\.(?:svg|png|jpg|jpeg|gif|webp|avif|ico|woff2|woff|ttf|otf|glb|gltf|hdr|exr|ktx2|basis|bin))$';const isCatchAll = (src) => src === '/(.*)' || src === ASSET_CATCHALL;-// Specific routes that actually resolve a request to something (have a dest).-const destRoutes = (vercel.routes || []).filter((r) => r.dest && !isCatchAll(r.src));+const isRedirect = (r) => typeof r.status === 'number' && r.status >= 300 && r.status < 400;+// Specific routes that resolve a request to something: a rewrite (dest) OR a+// 3xx redirect to a real page. Both are valid link destinations.+const destRoutes = (vercel.routes || []).filter((r) => (r.dest || isRedirect(r)) && !isCatchAll(r.src));const compiledRoutes = destRoutes.map((r) => {let s = r.src;@@ -164,14 +166,23 @@ function resolveInternal(rawTarget, baseDir) {// ── Target extraction ────────────────────────────────────────────────────────const STUB_VALUES = new Set(['#', '', 'javascript:void(0)', 'javascript:void(0);', 'javascript:;', 'javascript:']);+// Self-origins: a link written as an absolute URL back to our own domain is really+// an internal route — resolve it locally instead of probing the live deploy (which+// lags source and yields false 404s). This also surfaces genuinely wrong self-links.+const SELF_ORIGINS = /^https?:\/\/(?:www\.)?(?:three\.ws|3d-agent\.vercel\.app)(\/[^\s]*)?$/i;+function classifyTarget(value) {const v = (value || '').trim();if (STUB_VALUES.has(v.toLowerCase())) return { type: 'stub', value: v };// javascript:void(0) is a stub; any other javascript: URL runs real code → scheme.if (/^(mailto:|tel:|sms:|data:|blob:|javascript:)/i.test(v)) return { type: 'scheme', value: v };+ // Dynamic FIRST — a template-literal/concatenated URL is not a concrete target,+ // even when it starts with https:// (e.g. `https://solscan.io/tx/${sig}`).+ if (v.includes('${') || /["'`]\s*\+/.test(v) || v.includes('+ ')) return { type: 'dynamic', value: v };+ const self = v.match(SELF_ORIGINS);+ if (self) return { type: 'internal', value: self[1] || '/' };if (/^https?:\/\//i.test(v)) return { type: 'external', value: v };if (/^\/\//.test(v)) return { type: 'external', value: 'https:' + v };- if (v.includes('${') || /["'`]\s*\+/.test(v) || v.includes('+ ')) return { type: 'dynamic', value: v };if (v.startsWith('#')) return { type: 'anchor', value: v };if (v.startsWith('/') || /^[\w.-]/.test(v)) return { type: 'internal', value: v };return { type: 'dynamic', value: v };@@ -220,7 +231,12 @@ function record(target, file, line) {// scheme / anchor → fine}+// Third-party/minified bundles whose internals aren't our navigable links.+const VENDOR_RE = /(?:\/draco\/|\/three\/|\bvendor\b|\.min\.js$|wasm_wrapper)/;+function scanFile(file) {+ const rel = file.replace(ROOT + '/', '');+ if (VENDOR_RE.test(rel)) return; // skip vendored libs — not our link surfaceconst content = readFileSync(file, 'utf8');const isJs = /\.m?js$/.test(file);findings.scanned++;@@ -247,6 +263,7 @@ function scanFile(file) {function danglingRoutes() {const out = [];for (const r of destRoutes) {+ if (!r.dest) continue; // redirect route — no file to dangleconst dest = r.dest.split('?')[0];if (!dest.endsWith('.html')) continue;if (dest.includes('$')) continue; // dest uses a capture group — resolved per-request@@ -276,7 +293,9 @@ async function probeExternal(urls) {}clearTimeout(t);status = res.status;- ok = res.status < 400;+ // 401/403/429/405 mean the host answered but bot-blocks automated probes —+ // the page exists. Only 404/410/5xx and DNS/timeout failures are truly dead.+ ok = res.status < 400 || [401, 403, 405, 429].includes(res.status);} catch (e) {status = e.name === 'AbortError' ? 'timeout' : 'error';}diff --git a/src/credits.js b/src/credits.jsnew file mode 100644index 000000000..23811623c--- /dev/null+++ b/src/credits.js@@ -0,0 +1,351 @@+// /credits — prepaid balance, deposit (SOL or $THREE → credits), and ledger.+//+// Deposit flow reuses the platform Solana adapter (src/onchain/adapters): connect+// + inline SIWS link (so the signing wallet is linked, which the deposit verifier+// requires), then we build the transfer with web3.js / spl-token, hand the+// unsigned tx to the adapter (it signs, submits via /api/solana-rpc, and waits for+// confirmation), and POST the signature to /api/credits/deposit for server-side+// verification + crediting. @solana/web3.js + spl-token are loaded on demand so the+// page paints instantly for the read-only balance view.++import { getAdapter } from './onchain/adapters/index.js';++const SOL_MINT = 'So11111111111111111111111111111111111111112';++const $ = (id) => document.getElementById(id);+const fmtUsd = (n) => `$${(Number(n) || 0).toFixed(2)}`;+const origin = window.location.origin;++let state = { asset: 'SOL', deposit: null, prices: {} };++function fmtAmount(n, max = 6) {+ const v = Number(n) || 0;+ return v.toLocaleString(undefined, { maximumFractionDigits: max });+}++function fmtWhen(iso) {+ try {+ const d = new Date(iso);+ const diff = (Date.now() - d.getTime()) / 1000;+ if (diff < 60) return 'just now';+ if (diff < 3600) return `${Math.floor(diff / 60)}m ago`;+ if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`;+ return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });+ } catch {+ return '';+ }+}++const LEDGER_LABEL = {+ deposit: 'Deposit',+ spend: 'Spend',+ refund: 'Refund',+ grant: 'Credit grant',+ adjust: 'Adjustment',+};++function ledgerActivity(row) {+ if (row.kind === 'deposit') return `Deposit · ${row.asset || ''}`.trim();+ if (row.kind === 'spend') return row.action ? `Spend · ${row.action}` : 'Spend';+ if (row.kind === 'refund') return row.action ? `Refund · ${row.action}` : 'Refund';+ return LEDGER_LABEL[row.kind] || row.kind;+}++function setStatus(msg, kind = 'work') {+ const el = $('status');+ el.textContent = msg || '';+ el.className = `status ${kind}`;+}++function renderTier(discountBps) {+ const pill = $('tier-pill');+ if (discountBps > 0) {+ pill.hidden = false;+ pill.textContent = `Holder discount active · ${(discountBps / 100).toFixed(0)}% off every spend`;+ } else {+ pill.hidden = true;+ }+}++function renderBuys(buys) {+ const host = $('buys');+ host.innerHTML = '';+ if (!buys?.length) {+ host.innerHTML = '<div class="muted" style="font-size:0.85rem">Pricing loads shortly.</div>';+ return;+ }+ for (const b of buys.slice(0, 8)) {+ const row = document.createElement('div');+ row.className = 'buy-row';+ row.innerHTML = `<span class="label"></span><span class="price"></span>`;+ row.querySelector('.label').textContent = b.label;+ row.querySelector('.price').textContent = fmtUsd(b.usd);+ host.appendChild(row);+ }+}++function renderLedger(items) {+ const table = $('ledger');+ const empty = $('ledger-empty');+ const body = $('ledger-body');+ body.innerHTML = '';+ if (!items?.length) {+ table.hidden = true;+ empty.hidden = false;+ return;+ }+ empty.hidden = true;+ table.hidden = false;+ for (const r of items) {+ const tr = document.createElement('tr');+ const credit = r.amount_usd >= 0;+ const sig = r.tx_signature+ ? `<a href="https://solscan.io/tx/${r.tx_signature}" target="_blank" rel="noopener">view</a>`+ : '';+ tr.innerHTML = `+ <td class="muted">${fmtWhen(r.created_at)}</td>+ <td>${escapeHtml(ledgerActivity(r))} ${sig}</td>+ <td class="amt ${credit ? 'pos' : 'neg'}">${credit ? '+' : '−'}${fmtUsd(Math.abs(r.amount_usd))}</td>+ <td class="amt">${fmtUsd(r.balance_after)}</td>`;+ body.appendChild(tr);+ }+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+}++function renderAll(data) {+ $('balance').textContent = fmtUsd(data.balance_usd);+ $('lifetime-dep').textContent = fmtUsd(data.lifetime_deposited_usd);+ $('lifetime-spent').textContent = fmtUsd(data.lifetime_spent_usd);+ $('deposit-addr').textContent = data.deposit?.wallet || 'Not configured';+ renderBuys(data.buys);+ renderLedger(data.ledger);+}++async function loadPrices() {+ // Best-effort live estimate; degrades silently to no number if blocked.+ try {+ const mint = state.asset === 'SOL' ? SOL_MINT : state.deposit?.three_mint;+ if (!mint || state.prices[mint] != null) return updateEstimate();+ const r = await fetch(`https://lite-api.jup.ag/price/v3?ids=${mint}`);+ if (r.ok) {+ const d = await r.json();+ const p = Number(d?.[mint]?.usdPrice ?? d?.[mint]?.price);+ if (p > 0) state.prices[mint] = p;+ }+ } catch {+ /* estimate is a nicety */+ }+ updateEstimate();+}++function updateEstimate() {+ const amt = Number($('amount').value);+ const mint = state.asset === 'SOL' ? SOL_MINT : state.deposit?.three_mint;+ const price = state.prices[mint];+ const el = $('estimate');+ if (!(amt > 0)) {+ el.innerHTML = price+ ? `1 ${state.asset === 'SOL' ? 'SOL' : '$THREE'} ≈ ${fmtUsd(price)}`+ : 'Credited at the live USD value when your deposit confirms.';+ return;+ }+ if (price > 0) {+ el.innerHTML = `≈ <b>${fmtUsd(amt * price)}</b> in credits`;+ } else {+ el.innerHTML = 'Credited at the live USD value when your deposit confirms.';+ }+}++function setAsset(asset) {+ state.asset = asset;+ for (const btn of document.querySelectorAll('.seg button')) {+ btn.setAttribute('aria-pressed', String(btn.dataset.asset === asset));+ }+ $('amount-label').textContent = `Amount (${asset === 'SOL' ? 'SOL' : '$THREE'})`;+ $('amount-unit').textContent = asset === 'SOL' ? 'SOL' : '$THREE';+ $('amount').step = asset === 'SOL' ? '0.001' : '1';+ const quick = $('quick');+ quick.innerHTML = '';+ const presets = asset === 'SOL' ? [0.05, 0.1, 0.25, 0.5, 1] : [10000, 50000, 100000, 500000];+ for (const p of presets) {+ const b = document.createElement('button');+ b.type = 'button';+ b.textContent = asset === 'SOL' ? `${p} SOL` : `${fmtAmount(p, 0)}`;+ b.addEventListener('click', () => {+ $('amount').value = String(p);+ updateEstimate();+ });+ quick.appendChild(b);+ }+ loadPrices();+}++async function refresh() {+ const r = await fetch('/api/credits', { credentials: 'include' });+ if (r.status === 401) {+ $('loading-state').hidden = true;+ $('app-state').hidden = true;+ $('signin-state').hidden = false;+ return null;+ }+ if (!r.ok) throw new Error('Could not load your credits.');+ const data = await r.json();+ state.deposit = data.deposit;+ $('loading-state').hidden = true;+ $('signin-state').hidden = true;+ $('app-state').hidden = false;+ renderAll(data);+ return data;+}++async function buildSolTransfer({ web3, conn, from, to, amountSol }) {+ const lamports = BigInt(Math.round(amountSol * web3.LAMPORTS_PER_SOL));+ if (lamports <= 0n) throw new Error('Enter an amount greater than zero.');+ const tx = new web3.Transaction().add(+ web3.SystemProgram.transfer({+ fromPubkey: new web3.PublicKey(from),+ toPubkey: new web3.PublicKey(to),+ lamports,+ }),+ );+ return tx;+}++async function buildThreeTransfer({ web3, spl, conn, from, to, amount, mintStr, decimals }) {+ const atomics = BigInt(Math.round(amount * 10 ** decimals));+ if (atomics <= 0n) throw new Error('Enter an amount greater than zero.');+ const owner = new web3.PublicKey(from);+ const dest = new web3.PublicKey(to);+ const mint = new web3.PublicKey(mintStr);+ const srcAta = await spl.getAssociatedTokenAddress(mint, owner);+ const dstAta = await spl.getAssociatedTokenAddress(mint, dest);+ const tx = new web3.Transaction();+ const dstInfo = await conn.getAccountInfo(dstAta);+ if (!dstInfo) {+ tx.add(spl.createAssociatedTokenAccountInstruction(owner, dstAta, dest, mint));+ }+ tx.add(spl.createTransferCheckedInstruction(srcAta, mint, dstAta, owner, atomics, decimals));+ return tx;+}++async function doDeposit() {+ const btn = $('deposit-btn');+ const amount = Number($('amount').value);+ if (!(amount > 0)) return setStatus('Enter an amount greater than zero.', 'err');+ if (!state.deposit?.wallet) return setStatus('Deposits are not configured right now.', 'err');++ btn.disabled = true;+ try {+ setStatus('Connecting wallet…');+ const adapter = getAdapter('solana');+ if (!adapter.isAvailable()) {+ setStatus('No Solana wallet detected. Install Phantom to deposit.', 'err');+ window.open(adapter.installUrl(), '_blank', 'noopener');+ return;+ }+ const { address, ref } = await adapter.connect({ ensureLinked: true, cluster: 'mainnet' });++ setStatus('Building transaction…');+ const web3 = await import('@solana/web3.js');+ const conn = new web3.Connection(`${origin}/api/solana-rpc`, 'confirmed');+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');++ let tx;+ if (state.asset === 'SOL') {+ tx = await buildSolTransfer({ web3, conn, from: address, to: state.deposit.wallet, amountSol: amount });+ } else {+ const spl = await import('@solana/spl-token');+ tx = await buildThreeTransfer({+ web3,+ spl,+ conn,+ from: address,+ to: state.deposit.wallet,+ amount,+ mintStr: state.deposit.three_mint,+ decimals: state.deposit.three_decimals || 6,+ });+ }+ tx.feePayer = new web3.PublicKey(address);+ tx.recentBlockhash = blockhash;+ tx.lastValidBlockHeight = lastValidBlockHeight;++ const txBase64 = btoa(String.fromCharCode(...tx.serialize({ requireAllSignatures: false, verifySignatures: false })));++ setStatus('Confirm the transfer in your wallet…');+ const { txHash } = await adapter.signAndSend({ txBase64 }, ref);++ setStatus('Verifying deposit on-chain…');+ await verifyAndApply(txHash, state.asset);+ } catch (err) {+ setStatus(err?.message || 'Deposit failed. Please try again.', 'err');+ } finally {+ btn.disabled = false;+ }+}++async function verifyAndApply(txSignature, asset) {+ const r = await fetch('/api/credits/deposit', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ asset, tx_signature: txSignature, network: 'mainnet' }),+ });+ const data = await r.json().catch(() => ({}));+ if (!r.ok) {+ throw Object.assign(new Error(data.error_description || 'Deposit could not be verified.'), { data });+ }+ if (data.replay) {+ setStatus(`Already credited — balance ${fmtUsd(data.balance_usd)}.`, 'ok');+ } else {+ setStatus(`Added ${fmtUsd(data.credited_usd)} (${fmtAmount(data.amount)} ${asset}). New balance ${fmtUsd(data.balance_usd)}.`, 'ok');+ }+ $('amount').value = '';+ $('manual-sig').value = '';+ updateEstimate();+ await refresh().catch(() => {});+}++async function doManualVerify() {+ const sig = $('manual-sig').value.trim();+ if (!sig) return setStatus('Paste a transaction signature to verify.', 'err');+ const btn = $('verify-btn');+ btn.disabled = true;+ try {+ setStatus('Verifying deposit on-chain…');+ await verifyAndApply(sig, state.asset);+ } catch (err) {+ setStatus(err?.message || 'Could not verify that signature.', 'err');+ } finally {+ btn.disabled = false;+ }+}++function wire() {+ for (const btn of document.querySelectorAll('.seg button')) {+ btn.addEventListener('click', () => setAsset(btn.dataset.asset));+ }+ $('amount').addEventListener('input', updateEstimate);+ $('deposit-btn').addEventListener('click', doDeposit);+ $('verify-btn').addEventListener('click', doManualVerify);+}++async function main() {+ wire();+ setAsset('SOL');+ try {+ await refresh();+ } catch (err) {+ $('loading-state').hidden = true;+ setStatus(err?.message || 'Something went wrong loading your credits.', 'err');+ }+}++if (document.readyState === 'loading') {+ document.addEventListener('DOMContentLoaded', main);+} else {+ main();+}diff --git a/tests/README.md b/tests/README.mdindex 6e3983671..bedb44e33 100644--- a/tests/README.md+++ b/tests/README.md@@ -1,7 +1,70 @@# Tests-This directory contains the tests for the 3D-Agent application.+How the three.ws test suite is organized, how to run each part, and which parts+need credentials. Real money rides on this code — green has to mean green.-## Running Tests+## TL;DR-`npm test`+```bash+npm run test:core # full vitest suite, single worker — the reliable local run+npm run test:gate # 7 critical money/auth files — fast, offline, mock-backed+npm run lint # eslint . (0 errors is the bar; warnings are a backlog)+npm run typecheck # tsc -p jsconfig.json — must stay clean (hard CI gate)+```++## Suites++| Command | Runner | What it covers | Needs creds? |+| --- | --- | --- | --- |+| `npm test` | vitest + playwright | Unit suite then the browser e2e specs | Some unit specs are creds-gated (skip cleanly); e2e needs Chromium |+| `npm run test:core` | vitest `--maxWorkers=1` | Same unit suite, serialized | No (creds-gated specs skip) |+| `npm run test:gate` | node `scripts/test-gate.mjs` | 7 highest-consequence files: money-path confirm, HTTP cache boundary, custody/spend guards, vanity flow, x402 verify, holder snapshot, healthz | No — offline + mock-backed |+| `npm run test:e2e` | playwright | `tests/**/*.spec.js` — boots `npm run dev` as its web server | Chromium (`npx playwright install chromium`) |+| `npm run test:pages` | node `scripts/test-pages.mjs` | Chromium health pass over every public route (thrown errors, console errors, dead requests, broken hero images) | Chromium; spawns its own vite |+| `npm run test:all` | — | `test` then `test:pages` | as above |+| `npm run test:mcp` | node `scripts/test-mcp-all.mjs` | MCP transport surface | varies |+| `npm run smoke:onchain` | node | Live Solana/RPC parity checks | RPC access |+| `npm run smoke:agent-wallet` | node | Agent wallet path | wallet/CDP creds |+| `npm run smoke:mcp` | node | Remote MCP endpoints | live endpoints |++`vitest` discovers `tests/**/*.test.{js,mjs}`, `src/**/*.test.js`,+`api/_lib/coin/**/*.test.js`, and `tour-sdk/test/**/*.test.mjs`+(see `vitest.config.js`).++## Credentials++Credential-gated specs **skip cleanly** when their env var is absent — they do not+fail. They run wherever the secret is present (CI secrets, a local `.env`). The+common ones, by frequency in the suite:++`NVIDIA_API_KEY`, `HF_TOKEN`, `JWT_SECRET`, `REPLICATE_API_TOKEN`,+`UPSTASH_REDIS_REST_URL` / `UPSTASH_REDIS_REST_TOKEN`, `OPENAI_API_KEY`,+`GROQ_API_KEY`, `CDP_API_KEY_ID` / `CDP_API_KEY_SECRET`, `OPENROUTER_API_KEY`,+`DATABASE_URL`, `BIRDEYE_API_KEY`.++A local run with none of these set is expected to show skips, not failures. If you+see a creds-gap spec *fail* rather than skip, that's a bug in the gate — fix the+guard, don't delete the test.++## Concurrency / flakes++Heavy cold ESM imports (Solana toolchain, `@coinbase/x402`, jsdom, neon) make+worker startup memory-hungry. `vitest.config.js` already caps forks+(`MAX_FORKS`) and sets a 120s test/hook timeout for this reason.++On a loaded box (e.g. a Codespace shared by several agents) the default+fork count can still starve and surface as `Timeout waiting for worker to+respond` — that's the host, not the test. When in doubt, run **`npm run+test:core`** (single worker): it's slower but does not flake on CPU contention.+Treat any failure that only appears under heavy load and disappears at+`--maxWorkers=1` as an environment artifact, not a regression.++## CI++`.github/workflows/ci.yml` runs **lint**, **typecheck**, **unit tests**+(`vitest run`), **source guards** (`check-api-not-bundled`, `check:images`,+`build:pages`), **page health** (`test:pages`), and **e2e** (`playwright test`)+on every push to `main` and every PR, and blocks merge on failure. Typecheck is+a hard gate (the JSDoc backlog is cleared). Lint blocks on errors only; the+~5.5k pre-existing warnings are a tracked backlog — tighten to+`--max-warnings 0` once burned down.diff --git a/tests/credits.test.js b/tests/credits.test.jsnew file mode 100644index 000000000..30796aed4--- /dev/null+++ b/tests/credits.test.js@@ -0,0 +1,177 @@+// Unit tests for the prepaid credit ledger (api/_lib/credits.js).+//+// The DB is mocked: a controllable result queue stands in for Neon so we can+// exercise the money logic (atomic credit/debit return shapes, insufficient-funds+// 402, idempotent replays, and holder-discount pricing) without a live database.+// The $THREE tier module is mocked so the holder discount is a test input. The+// real pricing catalog is used (it's pure) so the discount math is exercised end+// to end.++import { describe, it, expect, beforeEach, vi } from 'vitest';++const db = vi.hoisted(() => ({ queue: [] }));+const tier = vi.hoisted(() => ({ bps: 0 }));++vi.mock('../api/_lib/db.js', () => ({+ // Every sql`...` call shifts the next programmed result off the queue. An+ // Error result rejects (used to simulate a UNIQUE-constraint violation).+ sql: () => {+ const next = db.queue.length ? db.queue.shift() : [];+ return next instanceof Error ? Promise.reject(next) : Promise.resolve(next);+ },+}));++vi.mock('../api/_lib/three-tier.js', () => ({+ holderDiscountBps: async () => tier.bps,+}));++const {+ getCreditAccount,+ creditAccount,+ debitCredits,+ chargeCreditsForAction,+ refundCredits,+} = await import('../api/_lib/credits.js');++function uniqueViolation() {+ return Object.assign(new Error('duplicate key value violates unique constraint'), { code: '23505' });+}++beforeEach(() => {+ db.queue.length = 0;+ tier.bps = 0;+});++describe('getCreditAccount', () => {+ it('rejects without a userId', async () => {+ await expect(getCreditAccount(null)).rejects.toMatchObject({ code: 'bad_request' });+ });++ it('parses balance + lifetime totals into numbers, zeros when no row', async () => {+ db.queue.push([]); // no account row yet+ expect(await getCreditAccount('u1')).toMatchObject({+ balanceUsd: 0,+ lifetimeDepositedUsd: 0,+ lifetimeSpentUsd: 0,+ });++ db.queue.push([{ balance_usd: '12.500000', lifetime_deposited_usd: '20', lifetime_spent_usd: '7.5' }]);+ expect(await getCreditAccount('u1')).toMatchObject({+ balanceUsd: 12.5,+ lifetimeDepositedUsd: 20,+ lifetimeSpentUsd: 7.5,+ });+ });+});++describe('creditAccount', () => {+ it('rejects a non-positive amount', async () => {+ await expect(creditAccount({ userId: 'u1', amountUsd: 0, idempotencyKey: 'k' })).rejects.toMatchObject({+ code: 'bad_request',+ });+ });++ it('rejects an unknown kind', async () => {+ await expect(+ creditAccount({ userId: 'u1', amountUsd: 1, kind: 'spend', idempotencyKey: 'k' }),+ ).rejects.toMatchObject({ code: 'bad_request' });+ });++ it('credits and returns the new balance + ledger id', async () => {+ db.queue.push([{ id: 'led-1', balance_after: '15.000000' }]);+ const res = await creditAccount({+ userId: 'u1',+ amountUsd: 5,+ kind: 'deposit',+ idempotencyKey: 'deposit:sig1',+ });+ expect(res).toEqual({ balanceUsd: 15, ledgerId: 'led-1', replay: false });+ });++ it('resolves a replayed deposit to the prior row (no double credit)', async () => {+ db.queue.push(uniqueViolation()); // CTE insert hits UNIQUE(idempotency_key)+ db.queue.push([{ id: 'led-1', balance_after: '15.000000' }]); // priorLedger lookup+ const res = await creditAccount({+ userId: 'u1',+ amountUsd: 5,+ kind: 'deposit',+ idempotencyKey: 'deposit:sig1',+ });+ expect(res).toEqual({ balanceUsd: 15, ledgerId: 'led-1', replay: true });+ });+});++describe('debitCredits', () => {+ it('rejects a non-positive amount', async () => {+ await expect(debitCredits({ userId: 'u1', amountUsd: 0, idempotencyKey: 'k' })).rejects.toMatchObject({+ code: 'bad_request',+ });+ });++ it('debits and returns the charged amount + new balance', async () => {+ db.queue.push([{ id: 'led-9', balance_after: '4.600000' }]);+ const res = await debitCredits({ userId: 'u1', amountUsd: 0.4, idempotencyKey: 'spend:1' });+ expect(res).toEqual({ balanceUsd: 4.6, ledgerId: 'led-9', replay: false, chargedUsd: 0.4 });+ });++ it('throws a 402 insufficient_credits when the balance is short', async () => {+ db.queue.push([]); // conditional UPDATE matched no row → not enough balance+ db.queue.push([{ balance_usd: '0.100000', lifetime_deposited_usd: '1', lifetime_spent_usd: '0.9' }]);+ await expect(+ debitCredits({ userId: 'u1', amountUsd: 0.5, idempotencyKey: 'spend:2' }),+ ).rejects.toMatchObject({ status: 402, code: 'insufficient_credits', available_usd: 0.1, required_usd: 0.5 });+ });++ it('resolves a replayed charge to the prior row (no double debit)', async () => {+ db.queue.push(uniqueViolation());+ db.queue.push([{ id: 'led-9', balance_after: '4.600000' }]);+ const res = await debitCredits({ userId: 'u1', amountUsd: 0.4, idempotencyKey: 'spend:1' });+ expect(res).toEqual({ balanceUsd: 4.6, ledgerId: 'led-9', replay: true, chargedUsd: 0 });+ });+});++describe('chargeCreditsForAction', () => {+ it('charges the catalog price for an action at full price for a non-holder', async () => {+ tier.bps = 0;+ db.queue.push([{ id: 'led-h', balance_after: '9.500000' }]);+ const res = await chargeCreditsForAction({+ user: { id: 'u1' },+ action: 'forge.high',+ idempotencyKey: 'forge:credits:ref1',+ });+ expect(res.pricedUsd).toBe(0.5); // forge.high = $0.50+ expect(res.discountBps).toBe(0);+ expect(res.chargedUsd).toBe(0.5);+ });++ it('applies the $THREE holder discount to the charge', async () => {+ tier.bps = 2000; // Gold — 20% off+ db.queue.push([{ id: 'led-h', balance_after: '9.600000' }]);+ const res = await chargeCreditsForAction({+ user: { id: 'u1' },+ action: 'forge.high',+ idempotencyKey: 'forge:credits:ref2',+ });+ expect(res.pricedUsd).toBe(0.4); // 0.50 * (1 - 0.20)+ expect(res.discountBps).toBe(2000);+ expect(res.chargedUsd).toBe(0.4);+ });++ it('requires a signed-in user', async () => {+ await expect(+ chargeCreditsForAction({ user: null, action: 'forge.high', idempotencyKey: 'k' }),+ ).rejects.toMatchObject({ code: 'unauthorized' });+ });+});++describe('refundCredits', () => {+ it('returns credits as a refund-kind ledger entry', async () => {+ db.queue.push([{ id: 'led-r', balance_after: '10.000000' }]);+ const res = await refundCredits({+ userId: 'u1',+ amountUsd: 0.5,+ idempotencyKey: 'forge:credits:refund:led-h',+ });+ expect(res).toEqual({ balanceUsd: 10, ledgerId: 'led-r', replay: false });+ });+});diff --git a/vercel.json b/vercel.jsonindex 4688c2419..d238a196b 100644--- a/vercel.json+++ b/vercel.json@@ -1099,6 +1099,10 @@"src": "/pricing/?","dest": "/pricing.html"},+ {+ "src": "/credits/?",+ "dest": "/credits.html"+ },{"src": "/x-pricing/?","dest": "/x-pricing.html"@@ -3300,15 +3304,24 @@},{"src": "/blog",- "dest": "/blog/index.html"+ "status": 301,+ "headers": {+ "Location": "/changelog"+ }},{"src": "/blog/",- "dest": "/blog/index.html"+ "status": 301,+ "headers": {+ "Location": "/changelog"+ }},{"src": "/blog/([a-z0-9-]+)/?",- "dest": "/blog/$1.html"+ "status": 301,+ "headers": {+ "Location": "/changelog"+ }},{"src": "/llms.txt",@@ -3371,11 +3384,17 @@},{"src": "/chat",- "dest": "/chat/index.html"+ "status": 301,+ "headers": {+ "Location": "/app"+ }},{"src": "/chat/",- "dest": "/chat/index.html"+ "status": 301,+ "headers": {+ "Location": "/app"+ }},{"src": "/chat/(.*)",@@ -3485,6 +3504,14 @@"src": "/legal/tos/?","dest": "/legal/tos.html"},+ {+ "src": "/legal/content-policy/?",+ "dest": "/legal/content-policy.html"+ },+ {+ "src": "/content-policy/?",+ "dest": "/legal/content-policy.html"+ },{"src": "/extension/auth-callback/?","dest": "/extension-auth-callback.html"diff --git a/vite.config.js b/vite.config.jsindex c5afe8c38..d9db477b3 100644--- a/vite.config.js+++ b/vite.config.js@@ -390,6 +390,7 @@ const appConfig = {'ar-page': resolve(__dirname, 'pages/ar.html'),creating: resolve(__dirname, 'pages/creating.html'),pricing: resolve(__dirname, 'pages/pricing.html'),+ credits: resolve(__dirname, 'pages/credits.html'),'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),'avatar-studio-demo': resolve(__dirname, 'pages/avatar-studio-demo.html'),'gallery-picker': resolve(__dirname, 'pages/gallery-picker.html'),