Skip to content

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

feat: Add tasks for funding on-ramp, dynamic OG images, referral program, programmatic SEO, creator dashboard, skill reviews, checkout completion, resilience for external calls, and designed states

miniaturizationfa861ca1c7db
diff --git a/api/_lib/credit-deposit.js b/api/_lib/credit-deposit.js
index 86b893e80..034b262cf 100644
--- a/api/_lib/credit-deposit.js
+++ b/api/_lib/credit-deposit.js
@@ -87,7 +87,8 @@ function tokenCreditedTo(tx, { mint, owner }) {
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');
+ delta +=
+ BigInt(p.uiTokenAmount?.amount ?? '0') - BigInt(before?.uiTokenAmount?.amount ?? '0');
}
return delta;
}
@@ -110,10 +111,12 @@ function lamportsCreditedTo(tx, owner) {
*/
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');
+ 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 (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');
}
@@ -126,9 +129,18 @@ export async function verifyAndCreditDeposit({ user, asset, txSignature, network
commitment: 'confirmed',
});
} catch {
- throw depositError('transaction not found — it may need more confirmations', 422, 'tx_not_found');
+ 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)
+ 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
@@ -150,17 +162,30 @@ export async function verifyAndCreditDeposit({ user, asset, txSignature, network
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');
+ 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');
+ 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');
+ throw depositError(
+ 'no $THREE was received at the deposit wallet in this transaction',
+ 422,
+ 'no_funds_received',
+ );
}
const p = await getTokenPriceUsd();
priceUsd = p.priceUsd;
@@ -170,7 +195,12 @@ export async function verifyAndCreditDeposit({ user, asset, txSignature, network
}
usd = Math.round(usd * 1e6) / 1e6;
- if (!(usd > 0)) throw depositError('deposit amount rounds to zero at the current price', 422, 'amount_too_small');
+ 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,
diff --git a/api/_lib/credits.js b/api/_lib/credits.js
index 7de201825..00a5bd44e 100644
--- a/api/_lib/credits.js
+++ b/api/_lib/credits.js
@@ -115,7 +115,11 @@ export async function creditAccount({
} catch (err) {
if (isUniqueViolation(err)) {
const prior = await priorLedger(idempotencyKey);
- return { balanceUsd: Number(prior?.balance_after ?? 0), ledgerId: prior?.id ?? null, replay: true };
+ return {
+ balanceUsd: Number(prior?.balance_after ?? 0),
+ ledgerId: prior?.id ?? null,
+ replay: true,
+ };
}
throw err;
}
@@ -186,7 +190,12 @@ export async function debitCredits({
required_usd: amt,
});
}
- return { balanceUsd: Number(rows[0].balance_after), ledgerId: rows[0].id, replay: false, chargedUsd: amt };
+ return {
+ balanceUsd: Number(rows[0].balance_after),
+ ledgerId: rows[0].id,
+ replay: false,
+ chargedUsd: amt,
+ };
}
/**
@@ -216,7 +225,8 @@ export async function chargeCreditsForAction({
idempotencyKey,
meta = {},
}) {
- if (!user?.id) throw badRequest('a signed-in user is required to spend credits', 'unauthorized');
+ 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({
diff --git a/api/credits/deposit.js b/api/credits/deposit.js
index f1f652796..8ea5d93e5 100644
--- a/api/credits/deposit.js
+++ b/api/credits/deposit.js
@@ -9,7 +9,16 @@
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 {
+ 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';
@@ -42,7 +51,8 @@ export default wrap(async (req, res) => {
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');
+ 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 });
diff --git a/pages/credits.html b/pages/credits.html
index 7a4f711e8..67d24ee62 100644
--- a/pages/credits.html
+++ b/pages/credits.html
@@ -1,7 +1,22 @@
<!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>
+ <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>
@@ -59,7 +74,9 @@
align-items: start;
}
@media (max-width: 820px) {
- .credits-grid { grid-template-columns: 1fr; }
+ .credits-grid {
+ grid-template-columns: 1fr;
+ }
}
.card {
background: var(--surface-1, #14161c);
@@ -88,9 +105,22 @@
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; }
+ .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;
@@ -121,15 +151,28 @@
padding: 0.45rem 1rem;
border-radius: 8px;
cursor: pointer;
- transition: background 0.15s, color 0.15s;
+ 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; }
+ .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);
@@ -142,64 +185,227 @@
font-variant-numeric: tabular-nums;
}
.amt-row .unit {
- display: flex; align-items: center; padding: 0 0.9rem;
+ 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;
+ border-radius: 10px;
+ font-weight: 700;
+ }
+ .quick {
+ display: flex;
+ gap: 0.4rem;
+ margin-top: 0.55rem;
+ flex-wrap: wrap;
}
- .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;
+ 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;
}
- .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); }
+ 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;
+ 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; }
+ 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>
@@ -212,8 +418,8 @@
<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.
+ 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>
@@ -232,11 +438,17 @@
<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>
+ <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 class="row-2" style="margin-top: 1.2rem">
<div>
<h2>What credits buy</h2>
<div class="buys" id="buys"></div>
@@ -249,41 +461,72 @@
<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>
+ <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" />
+ <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 &amp; deposit</button>
+ <button class="btn" id="deposit-btn" type="button">
+ Connect wallet &amp; 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>
+ <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>
+ <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">
+ <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>
+ <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 class="empty" id="ledger-empty" hidden>
+ No activity yet. Add credits to get started.
+ </div>
</div>
</section>
</div>
@@ -291,8 +534,8 @@
<!-- 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 class="card"><div class="skel" style="height: 120px"></div></div>
+ <div class="card"><div class="skel" style="height: 220px"></div></div>
</div>
</div>
</main>
diff --git a/prompts/production-1b/E01-structured-logging-and-tracing.md b/prompts/production-1b/E01-structured-logging-and-tracing.md
new file mode 100644
index 000000000..0ad0abfe8
--- /dev/null
+++ b/prompts/production-1b/E01-structured-logging-and-tracing.md
@@ -0,0 +1,33 @@
+# E01 — Structured logging + request correlation + tracing
+
+> Phase E · Depends on: none · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+At $1B scale you cannot debug what you cannot see. Today logs are unstructured `console.*`
+strings with no request correlation, and metrics cover only payments. Add structured,
+correlated logging and lightweight tracing so any incident is diagnosable in minutes.
+
+## Where this lives (real files)
+- `api/_lib/http.js` — `wrap()` request envelope (inject correlation here), `serverError()`.
+- `api/_lib/sentry.js` — error envelope; `api/_lib/axiom.js` — business metrics ingest (payments only today).
+- 160+ scattered `console.*` call sites across `api/_lib/`.
+
+## Build this
+1. **Correlation IDs:** generate a request ID in `wrap()`, propagate it through async work (AsyncLocalStorage), and include it in every log line + error + the client-facing error ref.
+2. **Structured logger:** a `api/_lib/structured-log.js` emitting JSON `{ ts, level, request_id, user_id, route, msg, ...fields }`; replace hot-path `console.*` with it (keep it cheap/fire-and-forget). Ship to Axiom.
+3. **Span timing:** instrument the expensive operations (DB query, Solana RPC, LLM call, external API) with start/stop spans tagged by request ID, so a slow request shows where time went.
+4. **Cost fields:** attach per-request cost signals where known (RPC units, LLM tokens, x402 spend) for later budgeting (G06/E07).
+5. **No secret leakage:** reuse the existing `redactUrl()`/redaction so logs never carry keys, seeds, or coordinates.
+
+## Out of scope
+- The error dashboard + alerting (**E02**) — this produces the data it visualizes.
+
+## Definition of done
+- [ ] Every request carries a correlation ID through logs + errors + client ref.
+- [ ] Structured JSON logs ship to Axiom; hot paths use the new logger; no secrets in logs.
+- [ ] Key operations are span-timed; a slow request is attributable to a stage.
+- [ ] `npx vitest run` green; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Make a request; find its single correlation ID across the request log, a span, and (force one) an error.
diff --git a/prompts/production-1b/E02-error-telemetry-and-alerting.md b/prompts/production-1b/E02-error-telemetry-and-alerting.md
new file mode 100644
index 000000000..c873a2497
--- /dev/null
+++ b/prompts/production-1b/E02-error-telemetry-and-alerting.md
@@ -0,0 +1,35 @@
+# E02 — Error telemetry dashboard + tiered alerting & escalation
+
+> Phase E · Depends on: E01 · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+Errors are captured to Sentry and alerts go to Telegram, but there's no aggregation, no
+severity, and no escalation — so a money-path failure looks the same as a cosmetic one and
+can go unnoticed. Build the visibility and alerting that lets the team catch and triage
+incidents before users do.
+
+## Where this lives (real files)
+- `api/_lib/sentry.js` — fire-and-forget error envelope.
+- `api/_lib/alerts.js` — Telegram ops alerts (dedup by signature, recovery announce).
+- `api/_lib/axiom.js` — metrics ingest.
+- `api/cron/` — health crons (forge-smoke, uptime-check, world-health, quota-check).
+
+## Build this
+1. **Error aggregation:** emit structured error events (code, route, domain: payment|render|infra|auth) to Axiom alongside Sentry, so you can query "429s yesterday by route" and "payment errors this hour."
+2. **Severity tiers:** classify alerts (critical = money/auth/RPC down; warning = degraded; info). Critical alerts page louder (and are ready to wire to PagerDuty/Slack via an env-configurable sink, not Telegram-only).
+3. **Spike detection:** alert when a route's error rate exceeds a baseline (e.g. >Nσ or > threshold), not just on single failures; dedup + auto-recover messages (reuse `alerts.js`).
+4. **Dashboards:** define the Axiom queries/dashboards for error rate by route, p95 latency, RPC provider health, payment success rate, Redis quota burn.
+5. **SLO doc:** write the target SLOs (error rate <0.5%, p95 <2s, payment success >99.5%) in `docs/` and tie alerts to them.
+
+## Out of scope
+- Producing the structured logs (**E01**) — this consumes them.
+
+## Definition of done
+- [ ] Structured error events queryable by route + domain; severity tiers implemented with an env-configurable critical sink.
+- [ ] Spike-based alerts fire (not just single errors), with dedup + recovery.
+- [ ] Dashboards + SLO doc exist; a forced money-path error triggers a critical alert.
+- [ ] `npx vitest run` green; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Force a burst of errors on one route → spike alert (critical) fires once + recovers; confirm the Axiom query shows them.
diff --git a/prompts/production-1b/E03-health-and-status-page.md b/prompts/production-1b/E03-health-and-status-page.md
new file mode 100644
index 000000000..46ef89acb
--- /dev/null
+++ b/prompts/production-1b/E03-health-and-status-page.md
@@ -0,0 +1,33 @@
+# E03 — Health/readiness endpoint + dependency checks + public status page
+
+> Phase E · Depends on: E01 · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+There's no single endpoint that says "is the platform healthy?" and no public status page.
+A health endpoint enables fast detection + uptime monitoring; a public status page builds
+the trust a financial platform needs. Build both.
+
+## Where this lives (real files)
+- `api/_lib/forge-health.js` — aggregates generation/limiter/LLM/Redis/world signals.
+- `api/cron/uptime-check.js`, `api/cron/world-health.js` — existing checks.
+- `api/_lib/db.js`, `api/_lib/redis.js`, `api/_lib/solana/connection.js` — dependencies to probe.
+
+## Build this
+1. **Liveness:** `GET /api/health` returns 200 fast with a basic "process up" + cheap DB/cache ping.
+2. **Readiness:** `GET /api/health?deep=1` (auth/limited) checks real dependencies — DB, Redis (+ quota headroom), Solana RPC (failover state), LLM providers, x402 facilitators, generation workers — and returns per-dependency status + the overall verdict.
+3. **Degraded signal:** surface a `degraded_features` list (e.g. "buyback paused", "Redis fail-open") that the client (`/api/config`) can read to soften the UI instead of erroring.
+4. **Public status page:** a polished page rendering current + recent uptime per major subsystem (generation, payments, RPC, worlds), backed by the readiness data and uptime crons. Designed states; mobile.
+5. **Uptime hooks:** make the health endpoint consumable by an external uptime monitor.
+
+## Out of scope
+- Alerting (**E02**) — link health into it.
+
+## Definition of done
+- [ ] `/api/health` (liveness) + deep readiness with per-dependency status exist and are accurate.
+- [ ] `degraded_features` surfaced and consumed by the client to degrade gracefully.
+- [ ] Public status page live, reachable from the footer, with real subsystem status + history.
+- [ ] `npx vitest run` green; `npm run build:pages` passes; changelog entry; committed + pushed to both remotes.
+
+## Verify
+- Take a dependency down locally (e.g. bad Redis URL) → readiness flags it + `degraded_features` populates + status page reflects it.
diff --git a/prompts/production-1b/E04-circuit-breakers-and-retry.md b/prompts/production-1b/E04-circuit-breakers-and-retry.md
new file mode 100644
index 000000000..4c74c9866
--- /dev/null
+++ b/prompts/production-1b/E04-circuit-breakers-and-retry.md
@@ -0,0 +1,36 @@
+# E04 — Circuit breakers + adaptive retry for all external dependencies
+
+> Phase E · Depends on: none (the memory note: a `cockatiel` resilience helper may already exist) · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+The platform depends on many external services (Solana RPC, Helius DAS, market-data APIs,
+LLM providers, x402 facilitators). Failover exists for RPC and LLMs, but retries are fixed,
+there's no circuit breaker, and a thundering herd on recovery can re-knock-over a dependency.
+Standardize resilient calls so one flaky provider can't cascade.
+
+## Where this lives (real files)
+- `api/_lib/solana/rpc-fallback.js` — RPC failover (good model to generalize).
+- `api/_lib/chat-models.js` + `api/_lib/provider-health.js` — LLM provider chain + cooldowns.
+- `api/_lib/aggregator.js`, `api/_lib/balances.js`, `api/_lib/market/token-market.js` — market data fallback.
+- `api/_lib/db-retry.js` — fixed [150,400]ms backoff.
+- Check for an existing vetted resilience helper (e.g. `cockatiel`) before hand-rolling — prefer adopting it.
+
+## Build this
+1. **Shared resilience helper:** a single wrapper offering timeout + exponential backoff with jitter + circuit breaker (closed/open/half-open). Prefer wrapping a vetted library over hand-rolling. Additive — don't refactor working failover; apply to new/unprotected call sites first.
+2. **Apply to high-value calls:** Helius DAS (high-credit, currently unprotected), market-data sources, x402 facilitator verify/settle, and any external fetch lacking a breaker.
+3. **Adaptive retry:** replace fixed db-retry backoff with exponential + jitter; bound total retry budget per call so retries can't blow the function timeout.
+4. **Breaker observability:** when a breaker opens, log it (E01) + reflect it in `degraded_features` (E03) and metrics (E02).
+5. **No thundering herd:** half-open probes one request before fully closing; jitter spreads recovery.
+
+## Out of scope
+- Existing RPC/LLM failover internals — generalize the pattern around them, don't rewrite.
+
+## Definition of done
+- [ ] A shared, tested resilience wrapper (preferably library-backed) is applied to the previously-unprotected external calls (Helius DAS, market data, facilitators).
+- [ ] db-retry uses exponential backoff + jitter with a bounded budget.
+- [ ] Open breakers are logged + surfaced in degraded_features + metrics.
+- [ ] `npx vitest run` green; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Point a wrapped dependency at a failing URL → breaker opens, requests fail fast + degrade, then half-open recovers when it's back.
diff --git a/prompts/production-1b/E05-redis-quota-and-degradation.md b/prompts/production-1b/E05-redis-quota-and-degradation.md
new file mode 100644
index 000000000..9fbd16276
--- /dev/null
+++ b/prompts/production-1b/E05-redis-quota-and-degradation.md
@@ -0,0 +1,35 @@
+# E05 — Redis quota: proactive monitoring + degraded-feature signaling
+
+> Phase E · Depends on: E02, E03 · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+Rate limiting, idempotency, caching, and locks all lean on Upstash Redis, which has a hard
+daily command ceiling. A June 2026 incident showed quota exhaustion can degrade critical
+limiters platform-wide. Make quota burn proactively visible and make degradation graceful
+and intentional rather than a surprise.
+
+## Where this lives (real files)
+- `api/_lib/redis.js` — singleton client; `api/_lib/redis-usage.js` — quota burn tracking (reactive).
+- `api/_lib/rate-limit.js` — 360+ limiters (fail-closed for money/auth, fail-open for reads), `local: true` for high-frequency reads.
+- `api/cron/quota-check.js` — quota monitoring cron.
+- `api/_lib/cache.js` — cache + in-flight coalescing + Redis fallback.
+
+## Build this
+1. **Proactive thresholds:** alert at 50/70/85% of the daily ceiling (not just at exhaustion), via E02's tiered alerting; project burn rate to estimate time-to-exhaustion.
+2. **Command-cost reduction:** audit the hottest limiters/caches; expand `local: true` for non-critical high-frequency reads; coalesce/raise TTLs where safe; batch where possible — drive structural burn down.
+3. **Graceful degradation:** when approaching the ceiling, automatically shed non-critical Redis usage (serve more from in-memory, relax non-critical limiters) while keeping money/auth limiters fail-closed; reflect this in `degraded_features` (E03).
+4. **Client hint:** surface quota pressure on `/api/config` so the UI can soften polling/retries during a crunch.
+5. **Runbook:** document what to do at each threshold and how raising the ceiling vs shedding load trades off.
+
+## Out of scope
+- Replacing Redis or the limiter design — optimize + protect what's there.
+
+## Definition of done
+- [ ] Proactive alerts at graduated thresholds with a time-to-exhaustion estimate.
+- [ ] Measured reduction in command burn on the hottest paths (document before/after).
+- [ ] Automatic, intentional degradation keeps money/auth safe; reflected in degraded_features + client hint.
+- [ ] Runbook written; `npx vitest run` green; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Simulate high burn (lower the threshold locally) → graduated alerts + degradation engage; money/auth limiters stay fail-closed.
diff --git a/prompts/production-1b/E06-migrations-and-schema.md b/prompts/production-1b/E06-migrations-and-schema.md
new file mode 100644
index 000000000..a41d316fd
--- /dev/null
+++ b/prompts/production-1b/E06-migrations-and-schema.md
@@ -0,0 +1,34 @@
+# E06 — Migrations: remove CREATE TABLE from handlers, add versioning & rollback
+
+> Phase E · Depends on: none · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+Several handlers create their tables lazily (`CREATE TABLE IF NOT EXISTS` at request time) —
+a race condition, a hidden schema dependency, and a DDL-on-the-hot-path anti-pattern. And
+there's no record of which migrations have run. Make schema management explicit, versioned,
+and safe.
+
+## Where this lives (real files)
+- Lazy `CREATE TABLE` in handlers/libs: `api/_lib/agent-embeddings.js`, `api/_lib/diorama-store.js`, `api/_lib/onchain-deploy.js`, `api/_lib/coin/three-holders.js` (and audit for more).
+- `api/_lib/migrations/` — SQL migration files (timestamped).
+- `scripts/run-migrations.js` / `apply-migrations.mjs` — runner.
+
+## Build this
+1. **Migration versioning:** add a `schema_migrations` table that records applied migrations; make the runner idempotent (skip already-applied) and ordered.
+2. **Move DDL into migrations:** convert every in-handler `CREATE TABLE/INDEX IF NOT EXISTS` into a real migration; the handler assumes the table exists. Keep behavior identical.
+3. **Readiness check:** a startup/readiness assertion (ties to E03) that required tables exist; fail loud if a migration is pending in production.
+4. **Rollback strategy:** for each migration, document or provide a down/rollback path (or an explicit "forward-only, here's the compensating migration" note).
+5. **Pre-deploy gate:** wire migration application into the deploy/CI flow (E10) so schema is applied before traffic.
+
+## Out of scope
+- Read replicas + partitioning (**E09**).
+
+## Definition of done
+- [ ] No handler runs DDL at request time; all such tables have real migrations.
+- [ ] `schema_migrations` tracks applied migrations; runner is idempotent + ordered.
+- [ ] Readiness check fails on pending migrations; rollback/compensation documented.
+- [ ] `npx vitest run` green; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Drop a dev table, run the runner twice → created once, second run is a no-op; confirm no handler recreates tables.
diff --git a/prompts/production-1b/E07-cron-and-worker-health.md b/prompts/production-1b/E07-cron-and-worker-health.md
new file mode 100644
index 000000000..e1abae9d3
--- /dev/null
+++ b/prompts/production-1b/E07-cron-and-worker-health.md
@@ -0,0 +1,34 @@
+# E07 — Cron + worker health: execution history, SLA, dashboard
+
+> Phase E · Depends on: E02 · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+~20 crons and ~18 worker pipelines run the platform's background work — buybacks,
+reflections, holder snapshots, oracle scoring, smart-money rollups, auto-rig sweeps. If one
+silently stops, the failure is invisible until a user notices. Make every scheduled job
+observable, with history and "didn't run" detection.
+
+## Where this lives (real files)
+- `api/cron/` — `[name].js` dispatcher + ~20 jobs (forge-smoke, three-holders-snapshot, rewards-distribute, oracle-*, smart-money-*, auto-rig-sweep, quota-check, relayer-balance-check, etc.).
+- `workers/` — oracle, agent-sniper, model-*, avatar-reconstruction, unirig, etc.
+- `vercel.json` — cron schedules.
+
+## Build this
+1. **Execution ledger:** a `cron_executions` table recording each run (job, started/finished, status, summary, error). Wrap the cron dispatcher so every job auto-records — no per-cron boilerplate.
+2. **Missed-run detection:** know each job's expected cadence; alert (E02) if a job hasn't run within ~1.5× its interval ("buyback cron hasn't run in 18h").
+3. **Worker health:** workers report heartbeat/health + errors to a shared place (DB or metrics) so a dead worker is visible; failures propagate to ops, not just local logs.
+4. **Dashboard:** an admin view (or extend the status page E03) showing each job's last run, status, and 7-day history.
+5. **Money-job priority:** buyback/reflection/holder-snapshot/relayer-balance crons are treated as critical (loud alerts on failure or miss).
+
+## Out of scope
+- The job logic itself (covered in A01/A02/A04/D01).
+
+## Definition of done
+- [ ] Every cron auto-records to `cron_executions`; missed-run detection alerts on critical jobs.
+- [ ] Workers report health; a dead worker is detectable + alerts.
+- [ ] Dashboard shows last run + 7-day history per job; `npx vitest run` green.
+- [ ] Changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Disable a critical cron's schedule → missed-run alert fires after the window; kill a worker → health flags it.
diff --git a/prompts/production-1b/E08-ssrf-and-input-hardening.md b/prompts/production-1b/E08-ssrf-and-input-hardening.md
new file mode 100644
index 000000000..195887553
--- /dev/null
+++ b/prompts/production-1b/E08-ssrf-and-input-hardening.md
@@ -0,0 +1,34 @@
+# E08 — SSRF + input sanitization + secret-scanning hardening
+
+> Phase E · Depends on: none · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+User-supplied URLs are fetched server-side without validation (an SSRF vector that can probe
+cloud metadata / internal services), user content isn't centrally sanitized, and there's no
+CI guard against committed secrets. Close these before they become an incident.
+
+## Where this lives (real files)
+- `api/_lib/auto-rig.js` (`fetchGlbBuffer(url)` — fetches a user URL with no host validation), and similar fetch-user-URL sites (`bake`, avatar import, etc.).
+- `api/_lib/validate.js` — Zod schemas (extend with URL guards).
+- `api/_lib/http.js` — `redactUrl()` (good; extend coverage).
+- User-content surfaces: agent names/descriptions, avatar metadata.
+
+## Build this
+1. **SSRF guard:** a shared `assertSafeFetchUrl(url)` (https only; reject localhost, `169.254.*`, `10.*`, `172.16–31.*`, `192.168.*`, `.internal`, link-local, and non-public hosts; optional per-feature allowlist). Apply to every server-side fetch of a user-supplied URL, starting with `auto-rig.js`. Add tests with malicious inputs.
+2. **Content sanitization:** centralize sanitization of user-generated text (names, descriptions) used in HTML/OG/embeds to prevent injection; ensure escaping at every render boundary.
+3. **Upload validation:** enforce content-type + size + (where feasible) structural validation on uploaded GLBs/images, rejecting malformed files early.
+4. **Secret scanning in CI:** add a CI step (e.g. gitleaks/trufflehog) that fails on committed secrets; document remediation. Pairs with **E10**.
+5. **Secrets hygiene:** confirm no secret is logged (reuse redaction) and that the watch traps in CLAUDE.md (esbuild bundle overwrite, foreign-history pulls) are not reintroducing secrets.
+
+## Out of scope
+- Custody/key handling (**A06**) and auth/session hardening (**B06/G05**).
+
+## Definition of done
+- [ ] All server-side fetches of user URLs go through the SSRF guard; malicious inputs are rejected (tested).
+- [ ] User text is sanitized/escaped at every HTML/OG/embed boundary; uploads validated.
+- [ ] CI fails on committed secrets; no secret appears in logs.
+- [ ] `npx vitest run` green; changelog entry (security); committed + pushed to both remotes.
+
+## Verify
+- Call the rig/import path with `http://169.254.169.254/...` → rejected; run the secret scanner on the repo → clean; inject `<script>` into an agent name → escaped everywhere it renders.
diff --git a/prompts/production-1b/E09-data-layer-scaling.md b/prompts/production-1b/E09-data-layer-scaling.md
new file mode 100644
index 000000000..8997a1d8d
--- /dev/null
+++ b/prompts/production-1b/E09-data-layer-scaling.md
@@ -0,0 +1,33 @@
+# E09 — Data layer: read-replica routing, partitioning, backup/restore drills
+
+> Phase E · Depends on: E06 · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+Postgres (Neon) is a single point of failure: all reads hit the primary, high-growth tables
+grow unbounded, leaderboards recompute on every request, and there's no proven restore path.
+Make the data layer ready to scale and recoverable.
+
+## Where this lives (real files)
+- `api/_lib/db.js` — single Neon `DATABASE_URL`, HTTP driver; `api/_lib/db-retry.js`.
+- High-write tables: `agent_actions`, `agent_revenue_events`, world events, x402 settlements.
+- Hot read aggregations: leaderboards, holder stats, analytics.
+
+## Build this
+1. **Read-replica routing:** route heavy, non-critical reads (leaderboards, profiles, analytics) to a Neon read replica when configured, with fall-back to primary if the replica lags > threshold. Keep money/consistency-critical reads on primary.
+2. **Materialize hot aggregates:** precompute leaderboard/stat aggregates (materialized views or a rollup table refreshed by cron) so hot reads don't recompute over the whole table each request.
+3. **Partition/retention:** for unbounded tables, add time-partitioning or a retention/archival policy so they don't degrade over time; index review on the hottest queries.
+4. **Backup/restore drill:** document RTO/RPO; add a periodic job (or runbook) that restores a backup to a scratch DB and runs smoke checks; alert if the last backup is stale.
+5. **Connection discipline:** confirm the singleton HTTP driver usage avoids connection blowups under serverless fan-out.
+
+## Out of scope
+- Migration mechanics (**E06**) — build on it.
+
+## Definition of done
+- [ ] Heavy reads route to a replica (when configured) with lag-aware fallback; money reads stay on primary.
+- [ ] Hot aggregates are materialized/rolled up; hottest queries indexed.
+- [ ] Unbounded tables have partitioning/retention; backup/restore drill documented + a stale-backup alert exists.
+- [ ] `npx vitest run` green; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- With a replica configured, confirm leaderboard reads hit it and fall back when lagged; run the restore drill to a scratch DB.
diff --git a/prompts/production-1b/E10-ci-cd-and-test-gate.md b/prompts/production-1b/E10-ci-cd-and-test-gate.md
new file mode 100644
index 000000000..d5b34bc11
--- /dev/null
+++ b/prompts/production-1b/E10-ci-cd-and-test-gate.md
@@ -0,0 +1,34 @@
+# E10 — CI/CD: test gate, e2e on money paths, publish automation
+
+> Phase E · Depends on: E06 (migrations in deploy), E08 (secret scan) · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+A platform that ships continuously needs a gate that makes "main is always deployable" true.
+Today tests exist (463) but the gate, e2e coverage of money paths, preview verification, and
+package publish automation need to be locked in so quality scales with velocity.
+
+## Where this lives (real files)
+- `package.json` scripts: `test` (vitest + playwright), `test:core`, `test:gate`, `test:e2e`, `verify`, `build`, `build:vercel`.
+- `tests/` (vitest) + Playwright e2e; `scripts/test-gate.mjs`, `scripts/audit-*.mjs`.
+- Workspaces in `package.json` (SDKs/MCP packages to publish).
+
+## Build this
+1. **PR gate:** a CI workflow that runs `vitest run`, the relevant Playwright e2e, `prettier --check`, page-index/empty-handler audits, and a build — failing the PR on any break. Make it fast (shard/parallelize) so it doesn't slow the team.
+2. **Money-path e2e:** Playwright flows for the critical journeys — buy $THREE (swap), pay for a skill (402 modal), forge → result, sign-in, deploy an agent. These must pass on every PR (mock external chains where needed, but exercise the real UI wiring).
+3. **Secret scan + dep audit:** wire E08's secret scanner and an `npm audit`/dependency check into CI.
+4. **Preview verification:** on each PR, deploy a Vercel preview and smoke-test key endpoints (health, token stats, a paid 402 challenge) against it.
+5. **Publish automation:** a tag-triggered workflow that builds + tests + publishes the `@three-ws/*` packages (ties to F02), with provenance and changelogs.
+6. **Branch protection:** require the gate green before merge to `main`; keep pushes mirrored to both remotes per CLAUDE.md.
+
+## Out of scope
+- Writing the SDK tests themselves (**F02**) — this runs them.
+
+## Definition of done
+- [ ] PR gate runs tests + lint + audits + build and blocks on failure; it's fast enough to not bottleneck.
+- [ ] Money-path Playwright e2e run in CI and pass; preview smoke-tests run per PR.
+- [ ] Secret scan + dep audit in CI; tag-triggered publish workflow works for at least one package.
+- [ ] `npx vitest run` green locally; changelog entry (infra); committed + pushed to both remotes.
+
+## Verify
+- Open a PR with a deliberately failing test → gate blocks; tag a package release → it publishes via CI.
diff --git a/prompts/production-1b/F01-developer-guide-and-examples.md b/prompts/production-1b/F01-developer-guide-and-examples.md
new file mode 100644
index 000000000..40d86d092
--- /dev/null
+++ b/prompts/production-1b/F01-developer-guide-and-examples.md
@@ -0,0 +1,39 @@
+# F01 — Unified developer guide + runnable examples + quickstarts
+
+> Phase F · Depends on: none · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+three.ws ships ~13 SDKs + ~7 MCP servers — a genuine developer platform — but a developer
+today must do "README archaeology" across 20 packages to ship anything. Network effects come
+from frictionless adoption. Build the single front door + runnable examples that turn a
+curious dev into an integrated one in 15 minutes.
+
+## Where this lives (real files)
+- SDKs: `sdk/` (`@three-ws/sdk`), `solana-agent-sdk/`, `agent-payments-sdk/`, `agent-protocol-sdk/`, `avatar-sdk/`, `walk-sdk/`, `page-agent-sdk/`, `tour-sdk/`.
+- MCP: `mcp-server/`, `packages/*-mcp/`.
+- `STRUCTURE.md` (surface map), `README.md`, `examples/`.
+
+## Build this
+1. **Developer guide:** `docs/DEVELOPER_GUIDE.md` — an overview of every SDK/MCP + when to use which, a quick-start matrix (EVM vs Solana vs MCP vs avatar embed), architecture + flow diagrams ("agent pays with $THREE", "image → rigged avatar", "embed a 3D agent"), and links into each package.
+2. **Runnable examples:** under `examples/`, create self-contained projects that run with `npm install && npm run dev`:
+ - `agent-basic` — init + mount an agent panel
+ - `agent-avatar` — embed `<agent-3d>`, play an animation
+ - `agent-payments` — invoke a paid skill via x402
+ - `agent-solana-identity` — SIWS + on-chain agent registration
+ - `mcp-client` — call three.ws MCP tools programmatically
+3. **Quickstarts in READMEs:** each SDK README opens with a copy-paste 30-second quickstart that actually works.
+4. **CONTRIBUTING + onboarding:** `CONTRIBUTING.md` (fork/branch/commit/test/release flow) and a "build order" note so a fresh clone builds first try.
+5. **Discoverable:** link the guide + examples from `README.md`, the site's developer/docs page, and `llms.txt`.
+
+## Out of scope
+- SDK test coverage + release automation (**F02**) and MCP reconciliation (**F03**).
+
+## Definition of done
+- [ ] `docs/DEVELOPER_GUIDE.md` covers every SDK/MCP with a quick-start matrix + diagrams.
+- [ ] All 5 examples run clean with `npm install && npm run dev` against real services (free lanes where possible).
+- [ ] Every SDK README has a working 30-second quickstart; CONTRIBUTING + build order documented + linked.
+- [ ] `npx vitest run` green; changelog entry (docs/sdk); committed + pushed to both remotes.
+
+## Verify
+- From a clean checkout, follow the guide to run each example to a working result.
diff --git a/prompts/production-1b/F02-sdk-tests-versioning-release.md b/prompts/production-1b/F02-sdk-tests-versioning-release.md
new file mode 100644
index 000000000..00711dfff
--- /dev/null
+++ b/prompts/production-1b/F02-sdk-tests-versioning-release.md
@@ -0,0 +1,32 @@
+# F02 — SDK tests + versioning + release automation + changelogs
+
+> Phase F · Depends on: E10 (CI) · Parallel-safe: yes
+> Run in a fresh chat in `/workspaces/three.ws`. Read [CLAUDE.md](../../CLAUDE.md) first.
+
+## Mission
+Published SDKs are a promise to other developers. Today test coverage is uneven, there's no
+semver policy, no release automation, and no per-package changelog — so consumers can't trust
+upgrades. Make the `@three-ws/*` packages dependable to build on.
+
+## Where this lives (real files)
+- `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/` (fork, v3.x, has `FORK_NOTES.md`), `agent-protocol-sdk/`, `avatar-sdk/`, `walk-sdk/`, `page-agent-sdk/`, `tour-sdk/`, `mcp-server/`, `packages/*`.
+- Root `package.json` workspaces; `scripts/` build helpers.
+
+## Build this
+1. **Test every SDK:** each package gets meaningful unit tests (mock RPC/EVM at the boundary) + at least one integration test; add a `test:all` script that runs every workspace's tests. Prioritize the money + identity SDKs (`agent-payments-sdk`, `solana-agent-sdk`, `sdk`, `mcp-server`).
+2. **Semver policy:** `VERSIONING.md` at root defining semver rules + a Node `engines` field per package; a `MIGRATION.md` template for major bumps. Document the `agent-payments-sdk` fork's relationship to upstream + how to rebase.
+3. **Changelogs:** a `CHANGELOG.md` per published package (Conventional Commits / changesets if feasible), so every version explains what changed.
+4. **Release automation:** tag-triggered build+test+publish (wire into E10), with npm provenance; a `release` helper script; verify each package's `package.json` (name, version, files, exports, types) is publish-correct.
+5. **pump-fun migration guide:** `docs/MIGRATION_FROM_PUMPFUN.md` for users moving off `@pump-fun/agent-payments-sdk`.
+
+## Out of scope
+- Writing the developer guide/examples (**F01**) and MCP reconciliation (**F03**).
+
+## Definition of done
+- [ ] Every published SDK has unit + ≥1 integration test; `test:all` runs them green.
+- [ ] `VERSIONING.md` + per-package `engines`; per-package `CHANGELOG.md`; pump-fun migration guide written.
+- [ ] Tag-triggered publish works (provenance) for the priority packages; package.json metadata verified.
+- [ ] `npx vitest run` green; changelog entry (sdk); committed + pushed to both remotes.
+
+## Verify
+- `npm run test:all` green; cut a patch release of one SDK via tag → it publishes with a changelog.
diff --git a/prompts/production-hardening/23-responsive-audit.md b/prompts/production-hardening/23-responsive-audit.md
new file mode 100644
index 000000000..bb874a741
--- /dev/null
+++ b/prompts/production-hardening/23-responsive-audit.md
@@ -0,0 +1,35 @@
+# 23 · Responsive at 320 / 768 / 1440 across all surfaces
+
+> **Phase 4 — Frontend excellence** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M
+
+## Mission
+CLAUDE.md requires every surface to work at 320 / 768 / 1440. The audit found responsive coverage is
+inconsistent — largely a single `768px` breakpoint, fixed-width spots, and untested edges (320px
+overflow, 1440px sprawl). Make every primary surface genuinely responsive and add a check so it stays
+that way.
+
+## Context (read first)
+- `CLAUDE.md` ("Responsive by default": relative units, flex/grid over fixed widths).
+- Existing media queries cluster at `max-width: 768px`; some dashboard/marketplace components have fixed max-widths.
+- Recent mobile work landed in the changelog (tour, walk companion) — match that quality bar.
+
+## Build this
+1. **Breakpoint tokens** — establish a small, documented set of breakpoints (e.g. 480 / 768 / 1024 / 1440) as CSS variables/utility classes; use them consistently instead of one-off `768px`.
+2. **Fix 320px** — no horizontal scroll, no clipped controls, tap targets ≥44px, readable type, composers/modals usable. Sweep the primary surfaces: forge, marketplace, gallery, dashboard, agent detail, launches, wallet/checkout.
+3. **Fix 1440px+** — content doesn't sprawl into unreadable line lengths or leave awkward voids; use max-widths + centered gutters where appropriate (mirror the recent forge full-width work).
+4. **Touch vs hover** — hover-only affordances have a touch equivalent; no functionality hidden behind `:hover` on touch devices.
+5. **Automated check** — a Playwright responsive spec that loads the top surfaces at 320/768/1440 and asserts no horizontal overflow + key elements visible; wire to CI. (Pairs with visual regression, prompt 05.)
+
+## Files likely in play
+Global CSS tokens + layout CSS across `pages/*` and `src/*`, the primary surface stylesheets, a Playwright responsive spec, `.github/workflows`.
+
+## Definition of done
+- [ ] Documented breakpoint tokens used consistently.
+- [ ] Every primary surface verified at 320/768/1440 — no overflow, no clipping, usable controls.
+- [ ] Touch equivalents for all hover affordances.
+- [ ] Responsive Playwright spec green in CI.
+- [ ] Verified in a real browser at all three widths.
+- [ ] Changelog: **improvement** entry ("responsive polish across phones, tablets, and wide screens").
+
+## Guardrails
+Follow CLAUDE.md. Test the 3D viewers and modals at 320px specifically — they break first. Push both remotes.
diff --git a/prompts/production-hardening/24-dead-path-link-gate.md b/prompts/production-hardening/24-dead-path-link-gate.md
new file mode 100644
index 000000000..02249ae01
--- /dev/null
+++ b/prompts/production-hardening/24-dead-path-link-gate.md
@@ -0,0 +1,34 @@
+# 24 · Dead-path & broken-link CI gate
+
+> **Phase 4 — Frontend excellence** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M
+
+## Mission
+CLAUDE.md: "If a button exists, it must work. If a link exists, it must go somewhere." Audit tooling
+exists (`page-audit.mjs`, a link auditor, `audit-empty-handlers.mjs`) but isn't gating CI. Find and
+fix every dead link, no-op button, and unreachable state across 125 pages, then lock it with a CI gate
+so dead paths can't ship again.
+
+## Context (read first)
+- `CLAUDE.md` ("Eliminate dead paths").
+- `npm run audit:web` (`scripts/page-audit.mjs`), the link auditor (`scripts/audit-links.mjs` if present), `npm run audit:handlers` (`scripts/audit-empty-handlers.mjs`), `npm run audit:pages` (`scripts/audit-page-index.mjs`).
+- 125 pages in `pages/`, nav config, and `data/pages.json`.
+
+## Build this
+1. **Run the auditors** and produce a consolidated report of: 404-ing internal links, external links that are dead, buttons/`data-action`s with no handler, modals that can't close, routes referenced but missing, nav entries pointing nowhere.
+2. **Fix every finding** — wire the handler, fix the href, add the missing page, or remove the dead affordance. No "exists but does nothing" survives.
+3. **Handler-binding check** — extend `audit-empty-handlers.mjs` (or add a check) so every `data-action="X"` has a bound listener and every declared route resolves.
+4. **CI gate** — add `audit:web` + link audit + handler audit to CI (strict), so a new dead path fails the build. Archive the report as a CI artifact.
+5. **Verify** — spot-check the highest-traffic pages in a real browser; click everything.
+
+## Files likely in play
+`scripts/page-audit.mjs`, `scripts/audit-links.mjs`, `scripts/audit-empty-handlers.mjs` (extend), nav/route config, the offending `pages/*` + `src/*`, `.github/workflows`.
+
+## Definition of done
+- [ ] Zero dead internal links, dead external links, or no-op buttons across the site.
+- [ ] Every `data-action` has a handler; every referenced route resolves.
+- [ ] `audit:web` + link + handler audits gate CI (strict); report archived.
+- [ ] Top pages clicked-through in a browser — everything works.
+- [ ] Changelog: **fix** entry if user-visible broken links were repaired.
+
+## Guardrails
+Follow CLAUDE.md. Removing an affordance is a last resort — prefer wiring it to where it should go. Push both remotes.
diff --git a/prompts/production-hardening/25-forge-server-thumbnails.md b/prompts/production-hardening/25-forge-server-thumbnails.md
new file mode 100644
index 000000000..9e7852945
--- /dev/null
+++ b/prompts/production-hardening/25-forge-server-thumbnails.md
@@ -0,0 +1,37 @@
+# 25 · Server-side Forge thumbnails
+
+> **Phase 4 — Frontend excellence** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M
+
+## Mission
+Geometry-first Forge lanes (nvidia/trellis/replicate) produce a GLB but **no `preview_image_url`**,
+so the "Fresh from the Forge" gallery falls back to client-side GLB frame capture — fragile, slow
+(megabytes per card), and a frequent source of blank/odd thumbnails. Generate a real thumbnail
+**server-side** at creation time so every creation has a stored preview, and the client never has to
+render a GLB just to show a card.
+
+## Context (read first)
+- `CLAUDE.md`.
+- `api/_lib/forge-store.js` (`setPreview`, `preview_image_url`, `listShowcase` orders preview-first).
+- `src/forge-showcase.js` (the Plan A→D client fallback chain — keep as a *last* resort, not the norm).
+- Worker fleet that already does GLB/render work: `workers/` (e.g. `stylize`, `texture`, `remesh`, `model-*`). `sharp` and `@gltf-transform/*` are dependencies. There's an auto-rig sweep cron precedent (recent commit) for backfilling.
+
+## Build this
+1. **Render-on-create** — when a generation finishes and has a GLB but no preview, render a thumbnail server-side (headless GLB→image: a worker using a GL/offscreen renderer, or the existing render worker if one fits) and store it to R2/S3, then `setPreview`.
+2. **Backfill sweep** — a cron/worker (mirror the auto-rig sweep) that finds `done` creations with `glb_url` and null `preview_image_url` and backfills thumbnails, oldest-visible-first.
+3. **Consistent framing** — neutral lighting, auto-framed camera, square output, reasonable resolution (e.g. 512²), webp. Deterministic enough that thumbnails look uniform across the gallery.
+4. **Client simplification** — with previews now populated, `src/forge-showcase.js` should hit Plan A (stored image) for the vast majority; keep the GLB-capture/gradient fallback only for the rare missing case.
+5. **Tests** — store path sets preview correctly; backfill selects the right rows; gallery now serves previews; client fallback still works when a preview is genuinely absent.
+
+## Files likely in play
+A thumbnail render worker (`workers/forge-thumbnail/` or reuse an existing render worker), `api/_lib/forge-store.js`, the forge-completion path, a backfill cron, `src/forge-showcase.js` (simplify), tests.
+
+## Definition of done
+- [ ] New finished creations get a stored server-side `preview_image_url`.
+- [ ] Backfill sweep populates previews for existing preview-less creations.
+- [ ] Gallery cards render from stored previews (no GLB download needed for thumbnails).
+- [ ] Client GLB-capture path remains only as a genuine last resort.
+- [ ] Tests cover create-render, backfill, and gallery serving.
+- [ ] Changelog: **improvement** entry ("Forge gallery thumbnails are crisp and instant").
+
+## Guardrails
+Follow CLAUDE.md. No fake/placeholder thumbnails — render the real model. Mind worker cost/scale (coordinate with prompts 30/31). Push both remotes.
diff --git a/prompts/production-hardening/26-logging-tracing.md b/prompts/production-hardening/26-logging-tracing.md
new file mode 100644
index 000000000..f18ea6c07
--- /dev/null
+++ b/prompts/production-hardening/26-logging-tracing.md
@@ -0,0 +1,36 @@
+# 26 · Structured logging + request correlation/tracing
+
+> **Phase 5 — Observability & ops** · **Depends on:** none (enables 27) · **Parallel-safe:** yes · **Effort:** L
+
+## Mission
+The platform is **minimally observable**: Sentry is wired exception-only (a custom HTTP envelope to
+avoid the heavy OTel SDK that nearly broke the Vercel build), logging is scattered `console.log`, and
+there are **no correlation IDs or tracing**. The team can't answer "did forge success rate drop?" or
+trace a failing payment across services. Add structured, correlated logging end-to-end — lightweight
+enough to keep the deploy fast.
+
+## Context (read first)
+- `CLAUDE.md`.
+- `api/_lib/sentry.js` (custom envelope — keep lightweight; do NOT pull the full `@sentry/node` OTel tree that broke the build), `api/_lib/axiom.js` (payments metrics sink), `api/_lib/http.js` (`wrap()` boundary — the natural place to inject).
+- Workers in `workers/` need the same correlation propagated.
+
+## Build this
+1. **Correlation IDs** — generate/propagate a request ID at the `wrap()` boundary (accept inbound `x-request-id`, generate if absent, echo in the response header). Thread it through to downstream fetches (forward the header) and into worker invocations.
+2. **Structured logger** — a tiny `api/_lib/log.js` emitting JSON lines (`{ ts, level, op, requestId, agentId?, durationMs?, ...ctx }`). Replace ad-hoc `console.log` in hot/important paths. No PII or secrets in logs.
+3. **Request summary log** — one structured line per request at the boundary (method, route, status, duration, requestId) so latency/error rates are derivable from logs.
+4. **Trace key flows** — emit span-like start/end events (with the correlation ID) for the multi-step flows: forge generation, x402 pay→settle→deliver, avatar create→rig. Stay lightweight (no full OTel SDK) — Axiom/structured-logs are the backend.
+5. **Sentry context** — attach requestId + op + (non-PII) context to exceptions so an error links back to its request and trace.
+
+## Files likely in play
+`api/_lib/log.js` (new), `api/_lib/http.js` (`wrap()` injection), `api/_lib/sentry.js` (context), `api/_lib/axiom.js` (correlation), downstream fetch helper (`fetch-json.js` from prompt 07), workers, the key-flow files.
+
+## Definition of done
+- [ ] Every request has a correlation ID, echoed in headers and propagated downstream + to workers.
+- [ ] Structured JSON logs replace ad-hoc console logging in important paths; no secrets/PII.
+- [ ] One request-summary line per request (status + duration) → enables metrics (prompt 27).
+- [ ] Key flows emit correlated span events; exceptions carry request context.
+- [ ] No meaningful build-time/deploy-size regression (don't pull the heavy OTel SDK).
+- [ ] Changelog: internal/ops → **no** entry.
+
+## Guardrails
+Follow CLAUDE.md. Keep it lightweight — the previous heavy-SDK approach nearly broke deploys. Never log secrets, keys, or full payment payloads. Push both remotes.
diff --git a/prompts/production-hardening/27-metrics-dashboards-slos.md b/prompts/production-hardening/27-metrics-dashboards-slos.md
new file mode 100644
index 000000000..50e1ac63c
--- /dev/null
+++ b/prompts/production-hardening/27-metrics-dashboards-slos.md
@@ -0,0 +1,35 @@
+# 27 · Metrics, dashboards & SLOs
+
+> **Phase 5 — Observability & ops** · **Depends on:** 26 · **Parallel-safe:** yes · **Effort:** L
+
+## Mission
+Today Axiom records only payment metrics, optionally. There's no per-endpoint latency, no error
+budgets, no SLA tracking — so a degradation is invisible until users complain. Build the metrics,
+dashboards, SLOs, and alerts that let the team see platform health at a glance and get paged before
+customers notice.
+
+## Context (read first)
+- `CLAUDE.md`.
+- `api/_lib/axiom.js` (existing sink), the structured request-summary logs from prompt 26, `api/status.js`/`healthz.js`.
+- Critical user-facing metrics: forge generation success rate + latency by engine, x402 settlement success rate + latency by rail, avatar create/rig success, RPC latency by provider, error rate by endpoint.
+
+## Build this
+1. **Emit metrics** — from the request-summary + key-flow events (prompt 26), record: request count, latency percentiles (p50/p95/p99), error rate per endpoint; plus domain metrics (forge success% by engine, payment settle% by rail, refund rate, breaker state from prompt 08).
+2. **Dashboards** — build Axiom (or chosen backend) dashboards: platform overview, forge health, payments health, RPC/dependency health. Commit the dashboard definitions/queries to the repo (`infra/dashboards/`) so they're versioned.
+3. **SLOs + error budgets** — define SLOs (e.g. forge success ≥99%, payment settle ≥99.9%, API p95 < Xms, availability target) and track burn rate.
+4. **Alerts** — page/notify on SLO breach, error-rate spikes, forge/payment success drops, breaker-open storms, reconciliation backlog (prompt 14). Route to the team channel; document thresholds.
+5. **Synthetic checks** — a periodic synthetic that exercises forge (free lane) + a read path and alerts if the user-visible flow breaks, independent of internal metrics.
+
+## Files likely in play
+`api/_lib/metrics.js` (new, on top of axiom + logs), `infra/dashboards/*` (new, versioned defs), alert config, a synthetic-check worker/cron, `docs/ops/slos.md`.
+
+## Definition of done
+- [ ] Per-endpoint latency + error-rate metrics flowing; domain metrics (forge/payments/RPC) live.
+- [ ] Versioned dashboards in-repo; rendering real data.
+- [ ] SLOs + error budgets defined and tracked.
+- [ ] Alerts fire on breach/spike/success-drop, routed to the team.
+- [ ] Synthetic user-flow check running + alerting.
+- [ ] Changelog: internal/ops → **no** entry.
+
+## Guardrails
+Follow CLAUDE.md. Keep metric emission async/fire-and-log (use the prompt-06 helper) so telemetry never slows or breaks a request. Push both remotes.
diff --git a/prompts/production-hardening/28-deploy-safety-rollback.md b/prompts/production-hardening/28-deploy-safety-rollback.md
new file mode 100644
index 000000000..7f2b0c3b0
--- /dev/null
+++ b/prompts/production-hardening/28-deploy-safety-rollback.md
@@ -0,0 +1,34 @@
+# 28 · Deploy safety: auto-rollback + isolated staging
+
+> **Phase 5 — Observability & ops** · **Depends on:** 26/27 (health signal) · **Parallel-safe:** yes · **Effort:** L
+
+## Mission
+Deploys are fragile: no automatic rollback on a bad ship, and **preview branches share the SAME
+Postgres/Redis/x402 accounts as prod** — a feature branch can corrupt production data. Add an
+isolated staging environment and a post-deploy health gate that auto-rolls-back a bad release.
+
+## Context (read first)
+- `CLAUDE.md` + the **`npx vercel build` overwrites `api/*.js`** trap (and `scripts/audit-deploy-artifacts.mjs`, `check-dist.mjs`, `build-vercel.mjs`).
+- `vercel.json`, deploy scripts, `api/healthz.js`/`status.js`.
+- Workers deploy is scattered (`gcloud builds submit` per service — see `workers/README.md`); coordinate with prompt 31.
+
+## Build this
+1. **Isolated preview/staging** — give non-prod deploys their own Postgres (separate DB/branch — Neon branching), Redis namespace, and x402 test config, so no preview can read/write prod data or move real funds. Wire env separation in `vercel.json`/project settings; document it.
+2. **Post-deploy health gate** — after a prod deploy, poll `/api/healthz` (+ key synthetic from prompt 27) for ~5 min; if it doesn't reach healthy, **automatically `vercel rollback`** and alert. Script it (`scripts/post-deploy-verify.mjs`) and run it in the deploy pipeline.
+3. **Artifact safety in CI** — enforce `audit:deploy` + a check that committed `api/*.js` are source (no `__defProp`/`createRequire` bundles) on every PR, so the bundling trap can never reach main.
+4. **Rollback runbook** — document the exact manual rollback steps as a fallback, with who/when.
+5. **Release notes hook** — on successful prod deploy, run `changelog:push` (already exists) so holders get updates automatically.
+
+## Files likely in play
+`vercel.json`, `scripts/post-deploy-verify.mjs` (new), `scripts/audit-deploy-artifacts.mjs` (CI wiring), deploy workflow, `docs/ops/deploy-runbook.md`, env/project config docs.
+
+## Definition of done
+- [ ] Preview/staging fully isolated from prod data + funds; verified.
+- [ ] Post-deploy health gate auto-rolls-back on failure; tested with a deliberately-bad canary.
+- [ ] CI blocks bundled `api/*.js` and runs `audit:deploy`.
+- [ ] Rollback runbook committed.
+- [ ] Successful deploy triggers changelog push.
+- [ ] Changelog: internal/ops → **no** entry.
+
+## Guardrails
+Follow CLAUDE.md. Test rollback before relying on it. Never point a preview deploy at prod credentials. Push both remotes.
diff --git a/prompts/production-hardening/29-backup-dr-migrations.md b/prompts/production-hardening/29-backup-dr-migrations.md
new file mode 100644
index 000000000..888aada1a
--- /dev/null
+++ b/prompts/production-hardening/29-backup-dr-migrations.md
@@ -0,0 +1,35 @@
+# 29 · Data backup/DR runbook + migration gating
+
+> **Phase 5 — Observability & ops** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M
+
+## Mission
+The DB (Neon/postgres) has 180+ migrations but **no documented, tested backup/restore** and
+migrations are applied manually with no pre-deploy gate. A $1B platform must be able to recover from
+data loss on demand and never deploy code ahead of its schema. Establish DR and migration discipline.
+
+## Context (read first)
+- `CLAUDE.md`.
+- `scripts/apply-migrations.mjs` (`db:migrate`, `db:status`; dry-run default, hash-tracked in `schema_migrations`), `api/_lib/migrations/*`.
+- `@neondatabase/serverless`; Neon supports branching + point-in-time recovery.
+- Asset storage: R2/S3 (`apply:r2-cors`); Redis (Upstash) is cache/idempotency (define what's recoverable vs ephemeral).
+
+## Build this
+1. **Backup strategy** — document and (where scriptable) automate: Neon PITR/snapshot cadence, R2/S3 versioning for generated assets, and what Redis state is reconstructable vs must-not-lose (idempotency/ledger live in Postgres, not Redis).
+2. **Tested restore runbook** — `docs/ops/dr-runbook.md`: step-by-step restore to a temp Neon branch, validate schema + row counts + a smoke query, and a target RTO/RPO. **Actually perform the restore once** and record the result.
+3. **Migration gating** — add `db:status` to CI: fail the deploy if there are pending migrations not applied to the target environment (no code-ahead-of-schema). Document the apply order relative to deploy.
+4. **Migration safety** — guidelines + a check for backward-compatible (expand/contract) migrations so a rollback (prompt 28) doesn't hit a schema it can't read. Flag destructive migrations for explicit review.
+5. **Restore drill cadence** — schedule a periodic DR drill (`/schedule` or a cron) so the runbook stays real.
+
+## Files likely in play
+`docs/ops/dr-runbook.md` (new), `scripts/apply-migrations.mjs` (CI status gate + safety checks), backup automation script, `.github/workflows`, migration-authoring guidelines doc.
+
+## Definition of done
+- [ ] Backup strategy documented + automated where possible (DB, assets).
+- [ ] DR runbook written **and a restore actually performed + recorded**; RTO/RPO stated.
+- [ ] CI fails on pending/unapplied migrations for the target env.
+- [ ] Expand/contract migration guidelines + destructive-migration flagging in place.
+- [ ] DR drill scheduled.
+- [ ] Changelog: internal/ops → **no** entry.
+
+## Guardrails
+Follow CLAUDE.md. Never run a destructive migration without a verified fresh backup. Don't restore over prod during a drill — use a temp branch. Push both remotes.
diff --git a/prompts/production-hardening/30-async-job-queue.md b/prompts/production-hardening/30-async-job-queue.md
new file mode 100644
index 000000000..2cb0ad3bb
--- /dev/null
+++ b/prompts/production-hardening/30-async-job-queue.md
@@ -0,0 +1,37 @@
+# 30 · Async job queue for heavy generation
+
+> **Phase 5 — Observability & ops** · **Depends on:** 26 (correlation) · **Parallel-safe:** yes · **Effort:** L
+
+## Mission
+Forge generation runs **synchronously** in the request path with a 300s `maxDuration`. A traffic spike
+monopolizes 300-second serverless slots, burns cost, and risks timeouts — it won't scale to platform
+volume. Move heavy generation to an async job queue: enqueue and return immediately, process on
+workers, deliver via polling/stream. Make generation elastic and observable.
+
+## Context (read first)
+- `CLAUDE.md`.
+- `vercel.json` forge `maxDuration` (~300s), `api/forge*.js`, the `workers/` model fleet (trellis/hunyuan3d/triposg/etc.).
+- Queue infra already in deps: `@upstash/qstash` (and Redis). Prefer it over adding a new broker.
+- Forge store (`api/_lib/forge-store.js`) already tracks creation status (`done`, `glb_url`) — extend with queued/processing/failed.
+
+## Build this
+1. **Enqueue endpoint** — `POST /api/forge` (or a new `/api/forge/jobs`) validates + bills/authorizes, creates a creation row in `queued`, enqueues a QStash job, and returns **202** with `{ job_id }` immediately. No synchronous GLB work in the request.
+2. **Worker processing** — a worker consumes the queue, runs the engine chain (with the resilience policies from prompt 08), updates status (`processing`→`done`/`failed`), stores the GLB + server-side thumbnail (prompt 25), and records metrics.
+3. **Status + delivery** — `GET /api/forge/jobs/:id` returns status/progress and the result when ready; optionally an SSE/stream for live progress. Update the client to enqueue → poll/stream → render (real progress, **not** a fake progress bar — CLAUDE.md forbids that).
+4. **Failure + refund** — a failed job surfaces a real error and, if it was paid, triggers the refund path (prompt 10). Retries are bounded and idempotent.
+5. **Backpressure** — queue depth metric + alert (prompt 27); a sane max in-flight per user/agent so one actor can't starve the queue.
+
+## Files likely in play
+`api/forge.js` → enqueue, `api/forge/jobs/[id].js` (new), a forge worker consumer, `api/_lib/forge-store.js` (status states), the forge client module, metrics + alerts, tests.
+
+## Definition of done
+- [ ] Forge requests enqueue + return 202 instantly; no synchronous 300s generation in the request path.
+- [ ] Worker processes jobs, updates status, stores GLB + thumbnail, records metrics.
+- [ ] Client shows **real** progress (poll/stream), then the result; failures show real errors.
+- [ ] Paid job failure → refund (prompt 10); retries bounded + idempotent.
+- [ ] Queue-depth metric + backpressure cap + alert.
+- [ ] Tests cover enqueue, process, deliver, fail+refund.
+- [ ] Changelog: **improvement** entry ("Forge generation is now queued — faster, more reliable under load").
+
+## Guardrails
+Follow CLAUDE.md. No fake progress/`setTimeout` loaders — real job status only. Keep the free-lane UX snappy. Push both remotes.
diff --git a/prompts/production-hardening/31-worker-autoscaling.md b/prompts/production-hardening/31-worker-autoscaling.md
new file mode 100644
index 000000000..ea19bcfb2
--- /dev/null
+++ b/prompts/production-hardening/31-worker-autoscaling.md
@@ -0,0 +1,36 @@
+# 31 · Worker autoscaling & one-command deploy
+
+> **Phase 5 — Observability & ops** · **Depends on:** 30 (queue) · **Parallel-safe:** yes · **Effort:** L
+
+## Mission
+~20 workers (model inference, texture, remesh, rembg, segment, stylize, avatar-pipeline-controller,
+oracle, sniper, etc.) are each provisioned individually and deployed by hand (`gcloud builds submit`
+per service). Single-instance services bottleneck under load, and the scattered deploy is error-prone.
+Make the worker fleet autoscaling, observable, and deployable with one command.
+
+## Context (read first)
+- `CLAUDE.md`.
+- `workers/` (each subdir is a service), `workers/README.md` (current scattered deploy), `scripts/deploy-sniper.mjs` (a one-service precedent).
+- The job queue from prompt 30 (workers should scale on queue depth).
+- Correlation/metrics from prompts 26/27 (workers must emit both).
+
+## Build this
+1. **Autoscaling** — configure each compute-heavy service (Cloud Run or equivalent) with min/max instances + concurrency tuned to its workload; scale on queue depth/CPU. Eliminate single-instance bottlenecks (avatar-pipeline-controller, texture, remesh, model-*).
+2. **One-command deploy** — a `scripts/deploy-workers.mjs` (mirroring `deploy-sniper.mjs`) that builds + deploys all (or a named subset of) workers with consistent config, health checks, and version stamping. Document in `workers/README.md`.
+3. **Worker health + observability** — every worker exposes a health endpoint and emits the structured logs + metrics (prompts 26/27): processed count, failures, latency, queue lag. Dead/stuck workers alert.
+4. **Resource limits + cost guardrails** — per-service CPU/mem limits and max-instances caps so a runaway can't blow the budget; document expected cost envelope.
+5. **Graceful failure** — a worker crash/restart must not lose in-flight jobs (queue redelivery from prompt 30); document the at-least-once semantics + idempotency expectation.
+
+## Files likely in play
+Per-service deploy config (Cloud Run YAML/Dockerfiles in `workers/*`), `scripts/deploy-workers.mjs` (new), `workers/README.md`, health/metrics wiring per worker, alert config.
+
+## Definition of done
+- [ ] Heavy workers autoscale on load; no single-instance bottlenecks remain.
+- [ ] `scripts/deploy-workers.mjs` deploys all/subset with one command + health checks.
+- [ ] Every worker emits health, logs, and metrics; stuck/dead workers alert.
+- [ ] Resource caps + cost envelope documented.
+- [ ] In-flight jobs survive worker restarts (idempotent redelivery).
+- [ ] Changelog: internal/ops → **no** entry.
+
+## Guardrails
+Follow CLAUDE.md. Don't set max-instances so high it risks runaway cost — cap it. Verify autoscaling with the load suite (prompt 05). Push both remotes.
diff --git a/prompts/production-hardening/32-sdk-changelogs-tests.md b/prompts/production-hardening/32-sdk-changelogs-tests.md
new file mode 100644
index 000000000..9ef0d8e99
--- /dev/null
+++ b/prompts/production-hardening/32-sdk-changelogs-tests.md
@@ -0,0 +1,35 @@
+# 32 · Per-package CHANGELOGs + SDK unit tests
+
+> **Phase 6 — Developer ecosystem** · **Depends on:** none · **Parallel-safe:** yes · **Effort:** M
+
+## Mission
+External devs are how a platform compounds to $1B, but the published SDKs are inconsistent: only ~2 of
+13 packages have a CHANGELOG, and several (`avatar-sdk`, `walk-sdk`, `mcp-server`) have **no unit
+tests**. Treat the SDKs as a product family: every published package gets release history and a test
+suite so external developers can trust and verify it.
+
+## Context (read first)
+- `CLAUDE.md`; `STRUCTURE.md` (surface→package map).
+- Published packages: `@three-ws/{avatar,walk,page-agent,sdk,solana-agent,agent-payments,agent-protocol-sdk,mcp-server,mcp-bridge,agent-ui,x402-modal-sdk}` + `packages/*` + `tour-sdk`.
+- Test-script precedents: `page-agent-sdk` (`npm test`), `solana-agent-sdk` (jest), `agent-protocol-sdk` (`node --test`). Missing: `avatar-sdk`, `walk-sdk`, `mcp-server`.
+- Monorepo `CHANGELOG.md` is rich, but per-package history is absent.
+
+## Build this
+1. **Per-package CHANGELOG** — add `CHANGELOG.md` to every published package (Keep a Changelog format), seeded with current version + recent notable changes. Add a `prepublishOnly`/release step that requires the CHANGELOG be updated for a version bump.
+2. **SDK unit tests** — add a real `test` script + meaningful tests to the packages that lack them (start with `avatar-sdk`, `walk-sdk`, `mcp-server`): public API surface, error paths, type-level smoke (import + invoke). No trivial assert-true tests.
+3. **Consistent package metadata** — verify each `package.json`: `types`, `exports`/subpaths, `files` allowlist, `repository`, `license`, `engines`, and `sideEffects` where relevant. Fix divergence.
+4. **Test the published shape** — a check that imports each package via its public entry (as an external consumer would) and exercises a basic call, catching broken `exports` maps.
+5. **CI** — run all SDK test suites in CI; block publish if a package's tests fail or its CHANGELOG wasn't updated for a version change.
+
+## Files likely in play
+`CHANGELOG.md` in each published package, `package.json` (`test`, metadata) per package, new test files in `avatar-sdk`/`walk-sdk`/`mcp-server` (and any other gap), `.github/workflows`, the publish scripts.
+
+## Definition of done
+- [ ] Every published package has a CHANGELOG + a passing test suite.
+- [ ] Package metadata consistent + correct (types/exports/files/repository/license).
+- [ ] Published-shape import test passes for each package.
+- [ ] CI runs SDK tests + enforces CHANGELOG-on-bump.
+- [ ] Changelog (platform): **sdk** entry ("SDKs now ship tests + per-package release notes").
+
+## Guardrails
+Follow CLAUDE.md. $THREE only in any SDK example/fixture. Don't publish from this prompt — just make them publish-ready (publishing is prompt 33). Push both remotes.
diff --git a/prompts/production-readiness/10-observability-and-alerting.md b/prompts/production-readiness/10-observability-and-alerting.md
new file mode 100644
index 000000000..403f30027
--- /dev/null
+++ b/prompts/production-readiness/10-observability-and-alerting.md
@@ -0,0 +1,41 @@
+# 10 — Observability & alerting
+
+> **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/sentry.js`, server + client error capture, structured logging, ops alerts, `api/healthz.js`.
+**Depends on:** `06`. **Pairs with:** `09`, `47` (status page).
+
+## Why this matters for $1B
+You can't operate at scale blind. When money moves and avatars render for thousands of
+users, you need to know within seconds that something broke, where, and how badly. Good
+observability turns 3am outages into 3-minute fixes — and gives investors confidence the
+team can run the thing.
+
+## Map — real anchors
+- `api/_lib/sentry.js` — custom HTTP envelope (no `@sentry/node`, to avoid NFT bloat); `SENTRY_DSN` configures; fired by `serverError()` in `api/_lib/http.js`; 2.5s timeout.
+- `api/_lib/http.js` — redacts lat/lng/token before logs/Sentry.
+- `public/error-reporter.js` → `POST /api/client-errors` — batched client capture.
+- `api/healthz.js` → `GET /api/healthz` — uptime + sub-probe status (resend/x402/monitor/watches).
+
+## Do this
+1. **Structured server logs:** standardize log lines into a structured shape (level, route, request id, user/agent id where safe, latency, outcome) via a small helper in `api/_lib/`. Keep the existing redaction. Replace ad-hoc `console.log` on hot paths with it.
+2. **Error capture coverage:** confirm **every** `serverError()` path reports to Sentry and every unhandled client error reaches `/api/client-errors`. Add a request id that ties a client error to its server trace.
+3. **Money + auth events:** emit a durable audit log (DB-backed where it exists) for every payment, withdrawal, mint, gating decision, and authz denial — queryable after the fact (coordinate with x402 audit-log in `api/_lib/x402/`).
+4. **Alerting:** wire ops alerts (the existing alert path in `http.js`) for: payment failures, auth-denial spikes, upstream-failover events, rate-limit-breaker trips, healthz sub-probe failures. Route to a real channel (Telegram/Slack/email) using existing creds.
+5. **Health/metrics:** extend `api/healthz.js` to cover the dependencies that matter (DB, Redis, RPC, model providers) with cached sub-probes. Expose key counters (paid calls/hr, forge jobs, errors/min) for the status page (`47`).
+6. **Dashboards:** document where to watch (Vercel Observability + Sentry) in `docs/internal/runbook.md`; add a minimal runbook for the top 5 alerts.
+
+## Must-not
+- Do not log secrets, full wallet keys, or precise user location — keep the redaction.
+- Do not add a heavy SDK that bloats the serverless bundle — match the lightweight `sentry.js` approach.
+
+## Definition of done
+- [ ] Structured logging helper in use on hot/money/auth paths, with redaction intact.
+- [ ] Every server + client error is captured and correlatable via request id.
+- [ ] Durable audit log for payments/withdrawals/mints/gating/authz-denials.
+- [ ] Real alerts wired for the critical event classes, with a runbook.
+- [ ] `healthz` covers DB/Redis/RPC/model providers; `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/11-backend-caching-and-cdn.md b/prompts/production-readiness/11-backend-caching-and-cdn.md
new file mode 100644
index 000000000..f31c5282d
--- /dev/null
+++ b/prompts/production-readiness/11-backend-caching-and-cdn.md
@@ -0,0 +1,41 @@
+# 11 — Backend caching & CDN
+
+> **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:** `Cache-Control` on API responses, `vercel.json` route caching, R2/Edge-config asset serving, read-path memoization.
+**Depends on:** `09`. **Pairs with:** `17` (web vitals), `51` (SEO).
+
+## Why this matters for $1B
+Caching is the cheapest performance and cost win available. Read-heavy public surfaces
+(gallery, launches, agent profiles, changelog) should be served from the edge, not
+recomputed per request. Right caching cuts RPC/DB bills, slashes latency, and lets the
+platform absorb a traffic spike instead of melting.
+
+## Map — real anchors
+- `api/_lib/http.js` — defaults to `no-store` unless a handler sets `Cache-Control`. Public reads should opt into `public, s-maxage=…`.
+- `vercel.json` — per-route cache headers already exist (e.g. `/embed/v1.js` 300s+CDN, `/changelog.json` 600s, `/widget-client.js` immutable) and R2 serving via `/api/cdn-object`.
+- Neon Postgres (`api/_lib/db.js`), Upstash Redis (`api/_lib/rate-limit.js` — reusable for caching).
+
+## Do this
+1. **Classify every GET endpoint:** public-cacheable (gallery, launches, agent profiles, leaderboards, prices, features), private (user dashboard), or never-cache (auth, payment state). Public reads should set `Cache-Control: public, s-maxage=… , stale-while-revalidate=…`; private reads `private`; money/auth `no-store`.
+2. **Edge-cache hot public reads** with `s-maxage` tuned to data freshness + `stale-while-revalidate` so the edge serves instantly while revalidating. Use SWR generously on slow-changing data.
+3. **Server-side memoization** for expensive repeated computations (e.g. $THREE balance — already 30s cached; pump quotes; on-chain reads) using Upstash with sensible TTLs and explicit invalidation on writes.
+4. **Static assets:** GLBs, textures, fonts, images served with long-lived immutable cache + content hashing; confirm R2/CDN path (`/api/cdn-object`) sets correct headers and compression.
+5. **Cache invalidation:** on every write that changes a cached read (new launch, profile edit, new avatar), invalidate or version the cache key — no stale-forever bugs.
+6. **Verify hit rates:** check response headers (`x-vercel-cache`, age) in the browser for the hot public routes; confirm HIT after warmup.
+
+## Must-not
+- Never cache authenticated or money/payment-state responses publicly.
+- Do not set immutable cache on content that changes without a hashed URL.
+- Do not cache an error response as if it were success.
+
+## Definition of done
+- [ ] Every GET endpoint classified and carries correct `Cache-Control` (public/private/no-store).
+- [ ] Hot public reads edge-cached with `s-maxage` + SWR; verified HIT in headers.
+- [ ] Expensive on-chain/DB reads memoized with TTL + write-invalidation.
+- [ ] Static 3D/image/font assets immutable + content-hashed via CDN.
+- [ ] No auth/money response cached publicly; `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/12-test-coverage-unit.md b/prompts/production-readiness/12-test-coverage-unit.md
new file mode 100644
index 000000000..515435381
--- /dev/null
+++ b/prompts/production-readiness/12-test-coverage-unit.md
@@ -0,0 +1,40 @@
+# 12 — Unit & integration test coverage
+
+> **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:** Vitest suites under `tests/` + colocated `*.test.js`; `vitest.config.js`.
+**Depends on:** `01`. **Pairs with:** `13` (e2e), `14` (CI), `44` (money safety).
+
+## Why this matters for $1B
+Tests are how a small team ships fast without breaking money. The repo already has ~466
+test files and a `test:gate` for critical money/auth paths — the goal now is closing
+coverage gaps on the logic that, if wrong, loses funds or corrupts data. Coverage is a
+diligence checkbox; correctness on money paths is survival.
+
+## Map — real anchors
+- `npm test` → `vitest run` + `playwright test`. `npm run test:core` → `vitest run --maxWorkers=1`. `npm run test:gate` → `scripts/test-gate.mjs` (critical money/auth subset).
+- `vitest.config.js` — 120s timeout, forks capped at min(4, cpus-1), `@grpc/*` deduped.
+- Tests in `tests/*.test.js` + colocated (e.g. `api/_lib/coin/*.test.js`).
+
+## Do this
+1. **Coverage report:** run `vitest run --coverage` (add the coverage dep/config if missing). Identify the lowest-covered high-risk modules: `api/_lib/x402/*`, `api/_lib/agent-wallet.js`, `api/_lib/pump*.js`, `api/_lib/three-gate.js`/`require-three.js`, `api/_lib/secret-box.js`, `api/_lib/db.js`, retarget/canonicalize (`src/glb-canonicalize.js`, `src/animation-retarget.js`).
+2. **Pure-logic first:** add deterministic unit tests for pricing math, amount/units conversions, idempotency-key derivation, gating tier thresholds, bonding-curve quotes, address validation, and bone-name canonicalization (the CLAUDE.md rule: every new skeleton mapping gets a `tests/glb-canonicalize.test.js` case).
+3. **Boundary + error cases:** for each money/auth module, test the failure paths — invalid input, replay, insufficient balance, RPC failure, unauthorized caller — not just the happy path.
+4. **Integration tests** for handler flows that can run without live third parties (use the existing test seams; do **not** introduce mocks of real APIs into production code — keep test doubles in test files only).
+5. **Make `test:gate` comprehensive:** ensure the critical-path gate covers every money/auth invariant so CI blocks regressions there.
+6. **Flaky-test sweep:** find and fix nondeterminism (time, ordering, network). No `.skip`/`xfail` left without a written reason + removal condition.
+
+## Must-not
+- Do not add mocks/fakes into shipped `src/`/`api/` code — test doubles live in test files only (CLAUDE.md forbids mocks in production code).
+- Do not chase a coverage % by testing trivial getters; prioritize money/auth/data-integrity logic.
+- Do not leave skipped tests without a documented reason.
+
+## Definition of done
+- [ ] Coverage measured; high-risk money/auth/data modules meaningfully covered incl. failure paths.
+- [ ] New deterministic unit tests for pricing, idempotency, gating, quotes, address validation, canonicalization.
+- [ ] `test:gate` covers all critical money/auth invariants.
+- [ ] No flaky/skipped tests without a written reason; `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/13-e2e-critical-flows.md b/prompts/production-readiness/13-e2e-critical-flows.md
new file mode 100644
index 000000000..aa5f0b328
--- /dev/null
+++ b/prompts/production-readiness/13-e2e-critical-flows.md
@@ -0,0 +1,45 @@
+# 13 — End-to-end tests for critical flows
+
+> **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:** Playwright suites under `tests/e2e/*.spec.js`; `playwright.config.js`.
+**Depends on:** `12`. **Pairs with:** `14` (CI), product-surface prompts `21`–`34`.
+
+## Why this matters for $1B
+Unit tests prove functions work; E2E proves the **product** works. The flows that make
+or break the company — create an avatar, launch a coin, pay via x402, embed a widget —
+must be guarded by browser tests that fail loudly when a refactor breaks the journey. This
+is how you ship daily without fear.
+
+## Map — real anchors
+- `npm run test:e2e` → `playwright test`. `playwright.config.js` — 120s timeout, 1 retry, dev server on port 3000, 180s cold-start budget.
+- Existing specs in `tests/e2e/` (e.g. `tests/e2e/avatar-edit.spec.js`).
+
+## Do this
+1. **Define the critical journeys** (the ones a $1B platform cannot ship broken):
+ - Forge: prompt → generate (free lane) → preview → save/download.
+ - Avatar: create/import → rig → customize → save → view in gallery.
+ - Onboarding: the create wizard end-to-end → deployed embed snippet.
+ - Marketplace: browse → open skill → purchase flow reaches checkout.
+ - x402: hit a paid endpoint → 402 → payment modal renders → settle path (use test/sandbox where real settlement isn't safe, but exercise the real UI flow).
+ - Embed/widget studio: configure → copy snippet → snippet renders an avatar on a test page.
+ - Walk companion: loads and animates on a page.
+2. **Author Playwright specs** for each, asserting real DOM/network outcomes (not screenshots-only). Cover the designed loading/empty/error states too.
+3. **Stabilize:** use role/text selectors, explicit waits on real conditions (no arbitrary sleeps), and the existing cold-start budget. Make them deterministic.
+4. **Money flows:** exercise the full UI up to the irreversible step; assert the confirmation/guard UI. Don't move real mainnet funds in CI.
+5. **Wire into CI** (coordinate with `14`) so these run on PRs and block merge on failure.
+
+## Must-not
+- No mainnet money movement in CI; stop at the confirmation boundary or use a sandbox.
+- No arbitrary `waitForTimeout` as the primary sync — wait on real conditions.
+- Do not assert on brittle pixel screenshots for logic; assert behavior.
+
+## Definition of done
+- [ ] Playwright specs cover forge, avatar create→rig→save, onboarding, marketplace purchase entry, x402 modal, embed/widget, walk companion.
+- [ ] Specs assert real behavior incl. loading/empty/error states; deterministic, no arbitrary sleeps.
+- [ ] Money flows tested up to the irreversible boundary only.
+- [ ] Specs run green locally and are wired into CI; `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/14-ci-cd-gates.md b/prompts/production-readiness/14-ci-cd-gates.md
new file mode 100644
index 000000000..e10c61237
--- /dev/null
+++ b/prompts/production-readiness/14-ci-cd-gates.md
@@ -0,0 +1,41 @@
+# 14 — CI/CD gates
+
+> **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:** `.github/workflows/*.yml`, build guards in `scripts/`, the Vercel build pipeline.
+**Depends on:** `12`, `13`. **Pairs with:** `04` (route audit), `45` (migrations).
+
+## Why this matters for $1B
+CI is the seatbelt that lets a team move fast. The deploy that triggered this whole effort
+failed because a strict route audit caught an undocumented page — that's the system
+working. The goal: make every class of regression (broken build, failing test, leaked
+bundle, undocumented route, accessibility break, money-path failure) impossible to merge.
+
+## Map — real anchors
+- `.github/workflows/ci.yml` — jobs: lint (eslint, new-errors-only), unit (vitest), source guards (`check-api-not-bundled.mjs`, `check:images`, `build:pages`), typecheck (advisory). Concurrency cancels in-flight runs per branch.
+- `scripts/build-vercel.mjs` — the multi-phase Vercel build; `scripts/audit-page-index.mjs --strict` gates it.
+- `scripts/check-api-not-bundled.mjs` — prevents esbuild bundles in `api/*.js`.
+
+## Do this
+1. **Make the gate complete.** Ensure CI blocks merge on: lint errors, unit test failures, `test:gate` (money/auth), the page-route audit (`audit:pages`), image-loading audit (`check:images`), handler audit (`audit:handlers`), and the api-not-bundled guard.
+2. **Add E2E to CI** (from `13`) on PRs — at least the smoke subset — with the dev-server + Playwright setup, retried once, and a sane timeout.
+3. **Typecheck:** decide whether to promote typecheck from advisory to blocking; if not yet clean, track the gap and gate net-new type errors only.
+4. **Build parity:** ensure CI runs the same `build:vercel` gates Vercel runs, so a green PR can't red the deploy. Catch the esbuild-bundle trap in CI (the guard exists — confirm it runs on the right paths).
+5. **Required checks + branch protection:** document which checks must pass; ensure the deploy only proceeds when CI is green.
+6. **Speed:** cache `node_modules`/build artifacts; keep PR feedback under ~10 min. Parallelize independent jobs.
+7. **Secret scanning in CI:** add a secret scan step (coordinate with `05`) so a leaked key fails the PR.
+
+## Must-not
+- Do not let a deploy proceed on a red gate to "unblock" a release — fix the cause.
+- Do not add flaky E2E that erodes trust in the gate; quarantine or fix flakes immediately.
+- Do not disable the api-not-bundled or route-audit guards.
+
+## Definition of done
+- [ ] CI blocks merge on lint, unit, test:gate, page/image/handler audits, api-not-bundled, secret scan.
+- [ ] E2E smoke runs on PRs and gates merge; CI build mirrors the Vercel gates.
+- [ ] Branch protection / required checks documented; deploy only on green.
+- [ ] PR feedback time is reasonable (caching + parallelism); `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/15-accessibility-wcag.md b/prompts/production-readiness/15-accessibility-wcag.md
new file mode 100644
index 000000000..204176517
--- /dev/null
+++ b/prompts/production-readiness/15-accessibility-wcag.md
@@ -0,0 +1,40 @@
+# 15 — Accessibility (WCAG 2.2 AA)
+
+> **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:** semantic HTML, ARIA, keyboard nav, focus management, contrast across `pages/` + `src/`.
+**Depends on:** `01`. **Pairs with:** `16` (responsive), `20` (design system).
+
+## Why this matters for $1B
+CLAUDE.md: "Accessibility is not optional." It's also enterprise procurement reality —
+AWS/IBM/Google-tier customers require it, and it's a legal exposure if absent. The repo
+already has ~2,500 ARIA usages; the goal is conformance, a CI gate, and a keyboard-only
+user who can do everything a mouse user can.
+
+## Map — real anchors
+- ~2,490 `aria-*`/`role=` usages across `pages/`. Design tokens (`public/tokens.css`, `:root` in `public/style.css`) carry contrast intent; theme via `public/theme-switcher.js` (dark default + light).
+- No a11y CI gate yet — add one.
+
+## Do this
+1. **Automated pass:** run `axe-core` (or `@axe-core/playwright`) across the top ~25 routes. Catalog violations by rule + severity.
+2. **Fix systematically:** semantic landmarks (`header`/`nav`/`main`/`footer`), heading order, labels on every form control, `alt` on meaningful images + `aria-hidden` on decorative, `aria-label`/`aria-labelledby` on icon buttons, `aria-live` on async status, correct roles on custom widgets.
+3. **Keyboard:** every interactive element reachable + operable by keyboard; visible focus ring everywhere (tokens already define `--focus-ring-*`); logical tab order; no keyboard traps; modals trap+restore focus; skip-to-content link.
+4. **Contrast:** verify text + UI contrast meets AA in **both** dark and light themes; fix token values that fail rather than one-off overrides.
+5. **Motion + 3D:** honor `prefers-reduced-motion` (pause/reduce avatar idle, transitions); provide text alternatives / controls for canvas-only 3D content where it conveys info.
+6. **CI gate:** add an automated a11y check (axe in Playwright) to the suite so regressions fail CI (coordinate with `14`).
+
+## Must-not
+- Do not add ARIA that lies about state, or ARIA where semantic HTML would do.
+- Do not fix contrast with per-element hacks — fix the design token.
+- Do not ship a focus style that's invisible on either theme.
+
+## Definition of done
+- [ ] axe across top ~25 routes: zero critical/serious violations.
+- [ ] Full keyboard operability + visible focus + skip link + modal focus management.
+- [ ] AA contrast in dark **and** light themes via tokens.
+- [ ] `prefers-reduced-motion` honored for 3D/animation.
+- [ ] a11y check wired into CI; `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/16-mobile-responsiveness.md b/prompts/production-readiness/16-mobile-responsiveness.md
new file mode 100644
index 000000000..f0e956771
--- /dev/null
+++ b/prompts/production-readiness/16-mobile-responsiveness.md
@@ -0,0 +1,40 @@
+# 16 — Mobile responsiveness
+
+> **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:** `public/mobile.css`, responsive layout across `pages/` + `src/`, touch interactions.
+**Depends on:** `01`. **Pairs with:** `15` (a11y), `20` (design system), `55` (PWA).
+
+## Why this matters for $1B
+A large share of crypto + consumer traffic is mobile. If forge, the gallery, the wallet
+flow, or a coin page is broken at 360px, half the audience bounces. CLAUDE.md: "Responsive
+by default. Test at 320px, 768px, and 1440px." Mobile parity is not a nice-to-have for a
+consumer platform aiming at $1B.
+
+## Map — real anchors
+- `public/mobile.css` (~442 lines) — breakpoints at 768/640/480/380/360px, `@media (hover:none) and (pointer:coarse)` touch rules, `@media (display-mode: standalone)` PWA tweaks.
+- `public/style.css` — fluid `clamp()` sizing + viewport units. `public/tokens.css` — spacing scale.
+
+## Do this
+1. **Audit every primary surface at 320 / 360 / 768 / 1024px** (and a real phone if possible): home, forge, gallery, marketplace, dashboard, create wizard, scene, club, city, walk, agent-studio, brain, coin/launch detail, wallet/funding, embed studio.
+2. **Fix layout breaks:** horizontal overflow, clipped content, overlapping elements, unreadable type, off-screen CTAs, fixed widths that don't fit. Prefer fluid units + the existing `clamp()` pattern; avoid new fixed pixel widths.
+3. **Touch targets:** ≥44px tap targets, adequate spacing, no hover-only affordances (provide tap equivalents). Honor the existing coarse-pointer media query.
+4. **3D on mobile:** canvas surfaces (forge preview, viewer, scene, walk, city) must be usable on touch — pinch/drag camera, sane default framing, lower asset/quality tier on low-power devices (coordinate with `19`). No locked-up scroll.
+5. **Forms + modals:** inputs don't get hidden by the soft keyboard; modals/sheets are full-height-friendly; payment + wallet flows work one-handed.
+6. **Safe areas + PWA:** respect `env(safe-area-inset-*)` on notched devices; verify the `standalone` display mode (coordinate with `55`).
+
+## Must-not
+- No horizontal scroll on any primary surface at 320px.
+- No hover-only interactions without a touch equivalent.
+- Do not ship a desktop-only 3D control scheme on touch surfaces.
+
+## Definition of done
+- [ ] Every primary surface clean at 320/360/768/1024px — no overflow, clipping, or off-screen CTAs.
+- [ ] Tap targets ≥44px; no hover-only affordances; coarse-pointer rules honored.
+- [ ] 3D/canvas surfaces usable + framed on touch, with a low-power quality tier.
+- [ ] Forms/modals/payment flows usable one-handed; safe-area insets respected.
+- [ ] `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/17-performance-core-web-vitals.md b/prompts/production-readiness/17-performance-core-web-vitals.md
new file mode 100644
index 000000000..2637e26c5
--- /dev/null
+++ b/prompts/production-readiness/17-performance-core-web-vitals.md
@@ -0,0 +1,39 @@
+# 17 — Performance & Core Web Vitals
+
+> **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:** LCP / INP / CLS across public surfaces; loading strategy; the `page-audit` tooling.
+**Depends on:** `11` (caching). **Pairs with:** `18` (bundle), `19` (3D), `51` (SEO).
+
+## Why this matters for $1B
+Web Vitals are a ranking signal **and** a conversion signal — every 100ms of latency costs
+sign-ups. A 3D-heavy platform fights gravity here, which makes disciplined performance a
+competitive moat: if three.ws loads fast with avatars rendering, it wins where rivals jank.
+
+## Map — real anchors
+- `npm run audit:web` → `scripts/page-audit.mjs` (Lighthouse-style audits). `npm run check:images` enforces lazy-load attrs on `<img>`.
+- Fonts in `public/fonts/`, `public/style.css` (large), `public/mobile.css`. Vite build for `src/`.
+
+## Do this
+1. **Measure first:** run Lighthouse / `audit:web` on the top ~15 public routes (mobile + desktop). Record LCP, INP, CLS, TBT, TTFB. Target: LCP < 2.5s, INP < 200ms, CLS < 0.1 on mid-tier mobile.
+2. **LCP:** identify each page's LCP element; preload it; serve hero images as responsive `srcset` + modern formats (AVIF/WebP); inline critical CSS; ensure fast TTFB via edge caching (`11`).
+3. **CLS:** reserve space for images/embeds/3D canvases (explicit dimensions / aspect-ratio); avoid layout shift from late fonts (`font-display: swap` + preload) and injected banners.
+4. **INP/TBT:** defer non-critical JS; break up long tasks; lazy-load heavy modules (Three.js scenes, studios) on interaction/viewport; debounce input handlers (CLAUDE.md). Hydrate/init only what's visible.
+5. **Images:** confirm `check:images` passes — every `<img>` lazy-loaded with dimensions; convert heavy PNGs; use a CDN/transform where available.
+6. **Fonts:** subset + preload the critical font; `font-display: swap`; cut unused weights.
+7. **Re-measure** and confirm the targets on the key routes; record before/after in `docs/internal/perf.md`.
+
+## Must-not
+- Do not regress 3D fidelity to win a number — tier it instead (`19`), don't gut it.
+- Do not block first paint on non-critical JS or analytics.
+- Do not ship layout-shifting late content above the fold.
+
+## Definition of done
+- [ ] Top ~15 routes meet LCP<2.5s / INP<200ms / CLS<0.1 on mid-tier mobile (before/after recorded).
+- [ ] LCP preloaded + responsive modern-format images; critical CSS inlined.
+- [ ] Heavy JS deferred/lazy-loaded; long tasks broken up; inputs debounced.
+- [ ] `check:images` + `audit:web` pass; `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/P13-csrf-protection.md b/prompts/production-readiness/P13-csrf-protection.md
new file mode 100644
index 000000000..bf18b18ba
--- /dev/null
+++ b/prompts/production-readiness/P13-csrf-protection.md
@@ -0,0 +1,59 @@
+# P13 · Enforce CSRF on all cookie-authenticated mutations
+
+> **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
+- CSRF infrastructure already exists and is **partially** adopted:
+ - `api/csrf-token.js` — `GET /api/csrf-token` issues a single-use token bound to the session/bearer user via `issueCsrf(userId)`.
+ - `api/_lib/csrf.js` — `issueCsrf(userId)` (inserts into `csrf_tokens`, 1h TTL) and `requireCsrf(req, res, userId)` middleware. `requireCsrf` returns `true`/sends 403 + returns `false`. It exempts `Bearer ` requests, honors a `CSRF_DISABLED=1` escape hatch **only outside production** (`IS_PROD` from `VERCEL_ENV`/`NODE_ENV`), reads the token from `x-csrf-token`/`X-CSRF-Token`/`req.body._csrf`, and validates atomically via `DELETE ... RETURNING` (one-time use, user-scoped).
+ - `api/_lib/auth.js` exposes `getSessionUser`, `authenticateBearer`/`extractBearer`, `isSameSiteOrigin`, plus `csrfTokenFor(req)` / `verifyCsrfToken(req, submitted)`. Cookies use the `__Host-` prefix (per `docs/security.md`).
+ - `api/_lib/http.js` provides `wrap(handler)`, `cors(req, res, {methods, credentials})`, `method(req, res, [...])`, `error(res, status, code, msg)`, and sets `SameSite` cookies + `X-Frame-Options: DENY` defaults.
+- `requireCsrf` is already imported in ~85 handlers (e.g. `api/agents.js`, `api/subscriptions/*`, `api/auth/[action].js`, `api/keys/*`, `api/admin/*`, `api/x/*`, `api/marketplace/*`). **But adoption is inconsistent**: many cookie-authenticated mutating handlers do not import or call it, and there is no single enforcement point — each handler must remember to call `requireCsrf` after resolving the user, which is exactly the kind of manual wiring that rots.
+
+## Problem / opportunity
+State-changing endpoints currently lean on SameSite cookies + CORS as the primary CSRF defense, with per-handler `requireCsrf` calls bolted on inconsistently. SameSite is a good layer but not sufficient alone (older browsers, `Lax` GET edge cases, subdomain quirks). The token machinery exists and works — the gap is **uniform enforcement**: a reusable wrapper so every cookie-auth POST/PUT/PATCH/DELETE verifies a CSRF token, with bearer/x402 machine calls correctly exempt, and an audit proving no mutating cookie-auth route is missed.
+
+## Mission
+Provide a reusable enforcement wrapper that verifies a CSRF token on every cookie-authenticated state-changing request (POST/PUT/PATCH/DELETE), exempts bearer-token and x402 machine-to-machine calls, adopt it across all such handlers, and add a CI/test guard that fails if a new mutating cookie-auth handler ships without it.
+
+## Scope
+**In scope:** a reusable wrapper layered on the existing `requireCsrf`/`wrap`; consistent adoption across mutating handlers; client-side fetch helper that attaches `X-CSRF-Token`; a static guard test enumerating mutating handlers.
+**Out of scope:** rewriting `issueCsrf`/token storage (it works), changing cookie/session design, x402 payment-flow auth (bearer/payment-proof callers stay exempt by design).
+
+## Implementation guide
+1. **Reusable wrapper in `api/_lib/csrf.js`.** Add `withCsrf(handler)` (or extend `wrap`) that, for `POST`/`PUT`/`PATCH`/`DELETE`:
+ - Resolves the caller once: `const session = await getSessionUser(req, res)`, `const bearer = session ? null : await authenticateBearer(extractBearer(req))`.
+ - **Exempt** when the request is bearer/x402 machine auth: if `extractBearer(req)` returns a token (Authorization: Bearer) OR an x402 payment proof header is present (grep `x402`/`x-payment` handling in `api/x402-*.js` and `api/x/*` for the exact header names — match them), skip CSRF (the bearer token / payment proof is itself proof of intent and is not auto-attached by browsers). This preserves the existing `requireCsrf` Bearer exemption.
+ - **Enforce** when the caller is cookie-session-authenticated: call `requireCsrf(req, res, session.id)`; if it returns `false` the wrapper returns (403 already sent).
+ - Leaves `GET`/`HEAD`/`OPTIONS` untouched (CORS preflight + safe methods).
+ - Keep the `CSRF_DISABLED=1`-only-outside-prod semantics already in `requireCsrf` — do not duplicate or weaken it.
+ Compose cleanly with `wrap`: e.g. `export default wrap(withCsrf(async (req,res) => {...}))`, with `withCsrf` running after `cors()`/`method()` inside the handler, OR expose a `csrfGate(req,res)` helper handlers call right after they resolve the user. Pick the shape that requires the least churn given how the ~85 existing handlers already call `requireCsrf(req,res,userId)` post-auth, and keep that call signature working (don't break the 85 sites).
+2. **Adopt across mutating cookie-auth handlers.** Enumerate every `api/**/*.js` that (a) handles a mutating method and (b) authenticates via `getSessionUser` (cookie). Grep: `grep -rln "getSessionUser" api/ | xargs grep -l "POST\|PUT\|PATCH\|DELETE"`, then subtract the ones already calling `requireCsrf`. For each gap, add the gate. Read 2-3 already-correct handlers (`api/agents.js`, `api/subscriptions/index.js`, `api/keys/index.js`) and copy their exact pattern for consistency.
+3. **Client fetch helper.** Ensure the frontend attaches the token on mutations. Find the shared fetch wrapper (grep `public/` and `src/` for `csrf`, `X-CSRF-Token`, `/api/csrf-token`). If a helper exists, confirm it caches the token from `GET /api/csrf-token` and re-fetches on a 403 `csrf_invalid`/`csrf_missing` (single-use tokens expire on use — the client must refresh and retry once). If no such helper exists, add one and route mutating UI fetches through it. Design the retry so a user never sees a spurious CSRF failure on a valid action.
+4. **Static guard.** Add `tests/csrf-coverage.test.js`: statically scan `api/**/*.js`, build the set of handlers that (mutating method) ∧ (uses `getSessionUser`) ∧ (NOT bearer-only), and assert each calls the CSRF gate (`requireCsrf` or `withCsrf`/`csrfGate`). Allow a tiny documented allowlist (e.g. login/refresh endpoints that mint the first token, or webhook receivers verified by signature) with a `reason`. This is the gate that stops regressions.
+
+## Definition of done
+- [ ] `withCsrf`/`csrfGate` exists in `api/_lib/csrf.js`, exempts bearer + x402, enforces on cookie-auth mutations, preserves the prod-safe `CSRF_DISABLED` semantics.
+- [ ] Every mutating cookie-auth handler verifies CSRF; gaps closed; allowlist documented.
+- [ ] Client mutations send `X-CSRF-Token` and transparently refresh+retry once on a CSRF 403.
+- [ ] `tests/csrf-coverage.test.js` enumerates handlers and fails on an unguarded one.
+- [ ] Existing tests pass (`npm test`); the 85 existing `requireCsrf` call sites still work.
+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages` (security work counts — tag `security`).
+- [ ] `git diff` self-reviewed.
+
+## Verification
+- `npx vitest run tests/csrf-coverage.test.js` → green; temporarily strip a gate from one handler → test fails naming it.
+- Manual: `npm run dev`, sign in (cookie session), then `curl -X POST http://localhost:3000/api/<a-protected-route> --cookie "<session>"` WITHOUT `X-CSRF-Token` → 403 `csrf_missing`. With a token from `GET /api/csrf-token` → succeeds; replaying the same token → 403 `csrf_invalid` (single-use).
+- `curl -X POST ... -H "Authorization: Bearer <token>"` → NOT blocked by CSRF (bearer exemption intact).
+- Exercise a mutating UI action in the browser → Network tab shows `X-CSRF-Token` header, no console errors, and a transparent retry if a token expired.
+
+## 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/P14-csp-tightening-nonces.md b/prompts/production-readiness/P14-csp-tightening-nonces.md
new file mode 100644
index 000000000..8db8f8739
--- /dev/null
+++ b/prompts/production-readiness/P14-csp-tightening-nonces.md
@@ -0,0 +1,56 @@
+# P14 · Tighten CSP to nonce/hash-based, kill unsafe-inline/unsafe-eval
+
+> **Workstream:** Security & compliance · **Priority:** P1 · **Effort:** L · **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
+- CSP is set as response headers in `vercel.json` (the `headers` array). The main app policy (around line 207 and 221) is:
+ `script-src 'self' 'unsafe-inline' 'unsafe-eval' blob: https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://ajax.googleapis.com https://s3.tradingview.com https://platform.twitter.com https://3d-agent.vercel.app https://three.ws; worker-src 'self' blob:; ... ; report-uri /api/client-errors`. Both `'unsafe-inline'` and `'unsafe-eval'` are present.
+- There are inline `<script>` tags in pages — notably the theme-boot no-flash snippet injected by `scripts/inject-theme-boot.mjs` (marker string `three.ws theme boot`, injected into `pages/*.html` during `prebuild`/`seo:meta`). Inline scripts are why `'unsafe-inline'` is currently required.
+- CSP violation reports already flow to `report-uri /api/client-errors`. `api/client-errors.js` already accepts a `csp` event type (`EVENT_TYPES` includes `'csp'`), validates/truncates the attacker-controllable payload, logs a structured `[client-error]` line, and forwards to Sentry. So the reporting pipeline for a report-only rollout exists.
+- Some routes already ship a tighter policy with no `script-src` at all (embed/iframe routes around lines 844+ use `frame-ancestors *; base-uri 'self'; object-src 'none'; report-uri /api/client-errors`).
+- `npm run test:pages` (`scripts/test-pages.mjs`) drives Chromium over every public route and fails on real console errors — a too-tight CSP that blocks a legit script will surface here.
+
+## Problem / opportunity
+`'unsafe-inline'` and `'unsafe-eval'` neutralize most of CSP's XSS protection: any injected `<script>` or `eval`'d string runs. Moving to a nonce/hash-based policy restores the protection. The blocker is inline scripts (theme-boot) and any `eval`-dependent third-party libs. We roll out safely: enumerate inline scripts and eval usage, switch to nonces/hashes, ship Report-Only first using the existing `/api/client-errors` pipeline, then enforce.
+
+## Mission
+Eliminate `'unsafe-inline'` (and, where feasible, `'unsafe-eval'`) from the main `script-src` by converting inline scripts to nonce- or hash-based, rolling out Report-Only first via `report-to`/`report-uri /api/client-errors`, then flipping to enforcing CSP once reports are clean.
+
+## Scope
+**In scope:** auditing every inline `<script>` and `eval`/`new Function` usage in shipped HTML/JS; nonce-or-hash strategy for the theme-boot and any other first-party inline scripts; a `Content-Security-Policy-Report-Only` rollout; tightening `vercel.json` script-src; verifying `/api/client-errors` ingests CSP reports.
+**Out of scope:** the relaxed embed/iframe route policies (they already omit script-src), rewriting third-party CDN libs, removing `'unsafe-eval'` if a load-bearing dependency genuinely needs it (document it instead and keep `'unsafe-eval'` scoped only where required).
+
+## Implementation guide
+1. **Audit inline scripts + eval.** `grep -rn "<script>" pages/ public/ | grep -v "src="` to list every inline script (theme-boot is the known one). `grep -rn "eval(\|new Function(" public/ src/ pages/` and check CDN libs (tradingview/twitter widgets are common `eval` users) to see whether `'unsafe-eval'` can be dropped or must stay scoped. Write the inventory into the PR description.
+2. **Pick the directive strategy.** Vercel static headers are per-route strings and can't inject a per-request nonce, so prefer **hashes** for the small, stable set of first-party inline scripts (the theme-boot snippet is deterministic — `inject-theme-boot.mjs` writes a fixed marker + body, so its SHA-256 is computable and stable). For routes served by an `api/` function that emits HTML, a per-request **nonce** is viable — but the theme-boot path is static, so hash is the right tool. Add `'sha256-<base64>'` entries to `script-src`. Have `scripts/inject-theme-boot.mjs` (or a new `scripts/compute-csp-hashes.mjs` run in `prebuild`) compute the hash of the exact inline body it injects and emit it where the CSP is assembled, so the hash never drifts from the script. Do NOT hand-maintain a hash that can silently go stale.
+3. **CSP assembly without drift.** `vercel.json` CSP strings are duplicated across routes. Rather than hand-edit each, consider generating the relevant `vercel.json` header blocks (or a shared CSP constant injected at build) so the script-src is defined once. If a generator is too invasive, at minimum centralize the allowed-origins + hash list in one place and document it. Keep the existing trusted CDN origins; only remove `'unsafe-inline'` and (if proven unused) `'unsafe-eval'`.
+4. **Report-Only rollout first.** Ship `Content-Security-Policy-Report-Only` with the *new tight* policy alongside the existing enforcing (looser) `Content-Security-Policy`. Point reports at the existing pipeline: add `report-to csp-endpoint` + a `Report-To` (or `Reporting-Endpoints`) header to `/api/client-errors`, keeping the legacy `report-uri /api/client-errors` for older browsers. Confirm `api/client-errors.js` accepts the `application/csp-report` / `application/reports+json` content types its `csp` event type implies — if it only parses `application/json`, extend `readBody`/`readJson` handling so real browser CSP reports aren't dropped at the boundary.
+5. **Observe, then enforce.** After the Report-Only policy is live and `[client-error]` CSP logs are clean for the public routes (verify via `npm run test:pages` driving Chromium + a manual sweep of high-traffic pages), flip the tight policy to the enforcing `Content-Security-Policy` and remove the now-redundant Report-Only (or keep Report-Only for the next tightening step). Never enforce a policy that hasn't first run clean in Report-Only.
+6. **Frame/object hardening pass (cheap win).** While in `vercel.json`, confirm the main policy keeps `object-src 'none'`, `base-uri 'self'`, and a sensible `frame-ancestors` — don't loosen these.
+
+## Definition of done
+- [ ] Inventory of inline scripts + eval usage documented; theme-boot converted to a build-computed hash (or nonce) — no `'unsafe-inline'` in the main `script-src`.
+- [ ] `'unsafe-eval'` removed from the main policy, OR retained only on the specific route(s) a documented dependency requires.
+- [ ] Report-Only rollout shipped first; CSP reports reach `/api/client-errors`; reports clean before enforcement flips.
+- [ ] Hash is generated from the actual injected script body (cannot drift); CSP defined in one place where practical.
+- [ ] Existing tests pass (`npm test`); `npm run test:pages` is green with the new policy (no blocked legit scripts).
+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages` (security work counts — tag `security`).
+- [ ] `git diff` self-reviewed.
+
+## Verification
+- `npm run dev`, open the app, DevTools console shows **no** CSP violation errors on home/dashboard/pricing/legal routes.
+- Inject a test inline `<script>alert(1)</script>` into a page locally → blocked by enforced CSP (proves `'unsafe-inline'` is gone); remove it.
+- Trigger a real CSP violation (e.g. add a disallowed `<img src=evil>` script) and confirm a `csp` event lands as a `[client-error]` line via `/api/client-errors`.
+- `npm run test:pages` passes (Chromium over every public route, no new console errors).
+- `npm run build` / `prebuild` runs the theme-boot hash computation and the emitted hash matches the injected snippet (re-run twice → identical hash).
+
+## 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/P20-enforce-tier-perks.md b/prompts/production-readiness/P20-enforce-tier-perks.md
new file mode 100644
index 000000000..35efe7ba2
--- /dev/null
+++ b/prompts/production-readiness/P20-enforce-tier-perks.md
@@ -0,0 +1,54 @@
+# P20 · Enforce $THREE Tier Perks at the Request Boundary
+
+> **Workstream:** Monetization (revenue engine) · **Priority:** P1 · **Effort:** M · **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 hold-to-access lever is fully specified and partly enforced:
+
+- `api/_lib/three-tier.js` — `TIERS` ladder (Member/Bronze/Silver/Gold/Genesis) by USD value of $THREE held. Each tier carries `discountBps` (fee discount, already consumed by `priceForAction`) AND `rateMultiplier` (1/2/3/5/10 — scales free quotas). `signTierPass`/`verifyTierPass` mint a pure-HMAC tier pass (no RPC) so a game/MCP server can gate without a price feed. `resolveUserTier(user)` reads on-chain holdings.
+- `api/_lib/three-access.js` — `GATED_FEATURES` registry. Today `enforced:true` only on `forge.high` (gated in `api/forge.js`) and `forge.gameready` (gated in `api/forge-gameready.js`). **`enforced:false` on:** `worlds.private` (minLevel 2), `worlds.branded` (minLevel 3), `mcp.priority` (minLevel 2), `drops.early` (minLevel 3), `names.first_dibs` (minLevel 4). The registry's `enforced` flag is what `/three` uses to label a perk "Live" vs "Planned" — flipping it to `true` is a PROMISE the gate is actually wired.
+- `api/_lib/require-three.js` — `requireFeatureAccess(req, res, featureId, { allowPayPerUse, body })` is the keystone gate: pass-first (HMAC), then session on-chain tier, then anonymous Member. On block it writes a structured `402 three_hold_required` with `held`/`required`/`usd_to_go`/`acquire`/`pay_per_use`. Returns `{ ok, access, level, wallet }`. This is the ONLY helper to call at a gated boundary — `forge.high` already uses it.
+- `rateMultiplier` is currently read in exactly two places: `api/forge.js:100` (`tier?.rateMultiplier || 1` for the free-lane quota) and surfaced read-only in `api/three/[action].js:87`. **MCP/forge queueing never consumes it.**
+- MCP lanes: `api/mcp-3d.js` (text→3D, image→3D, auto-rig, etc.), `api/mcp-agent.js`, `api/mcp-bazaar.js`, `api/mcp.js`. `mcp-3d.js` already does tier-aware pricing (`_mcp3d/pricing.js`) and per-IP/per-user rate limits (`limits.mcpIp`, `limits.mcpUser`). Worlds: the Colyseus multiplayer server verifies a tier pass (`verifyTierPass`) — see `three-tier.js` "signed tier pass" note.
+
+## Problem / opportunity
+Five declared perks are advertised on `/three` and in the tier ladder but `enforced:false` — a Silver holder is promised "Private worlds" and "Priority MCP routing" that no code checks. The `rateMultiplier`, the headline holder benefit ("2×/3×/5×/10× free quota"), is consumed for the free Forge lane only; MCP free quotas and any queue priority ignore it. The platform promises tier value it doesn't deliver — a credibility and revenue gap (holders have no reason to hold for unenforced perks).
+
+## Mission
+Wire each `enforced:false` perk to a real check at its request boundary using `requireFeatureAccess`, flip its `enforced` flag to `true` only once the gate ships (with a test), and make `rateMultiplier` actually scale MCP/forge free-tier quotas and queue priority.
+
+## Scope
+**In scope:** enforce `worlds.private`, `worlds.branded`, `mcp.priority`, `drops.early`, `names.first_dibs` at their boundaries; consume `rateMultiplier` in MCP + forge free-quota limiting and `mcp.priority` queue ordering; flip `enforced` flags + add per-perk tests.
+**Out of scope:** changing tier thresholds or `rateMultiplier` values, the discount path (already wired), inventing new perks.
+
+## Implementation guide
+1. **`worlds.private` / `worlds.branded`.** At world-create / world-join (the multiplayer/world endpoints that mint or admit to a private/branded room), call `requireFeatureAccess(req, res, 'worlds.private', { body })` (or `worlds.branded`) before provisioning. Since the Colyseus server already verifies a tier pass, the create path should issue a `signTierPass` the room server re-checks with `verifyTierPass` — gate on the pass level so the room never needs an RPC. `payPerUse: null` for these, so the 402 is hold-only (no pay-per-use leg).
+2. **`mcp.priority` + `rateMultiplier` in MCP (`api/mcp-3d.js`).** Resolve the caller's tier once per request (pass-first via header `x-three-tier-pass`, else session `resolveUserTier`). Scale the free/OAuth-funded quota by `rateMultiplier` (a Silver holder gets 3× the base `limits.mcpUser` budget). For `mcp.priority`, when the compute lane is queued, holders at minLevel 2+ jump the shared queue (priority dequeue) — wire it into the actual queue ordering, not a comment. Non-holders keep the base lane. Do not change x402 per-tool pricing (that's the pay path).
+3. **`rateMultiplier` parity in forge.** `api/forge.js:100` already applies it to the free lane; ensure the same multiplier is applied consistently anywhere a free-tier daily/window quota is enforced (audit `limits.*` call sites tied to generation). One helper — e.g. `quotaFor(baseLimit, tier)` in `three-tier.js` — so the multiplier math lives in one place.
+4. **`drops.early`.** At the drop/collectible mint endpoint, gate the early-access WINDOW: before the public open time, `requireFeatureAccess(req, res, 'drops.early')` must pass (minLevel 3); after public open, everyone in. The gate is time-conditional, not a hard block forever.
+5. **`names.first_dibs`.** At the rare-name claim/auction-bid endpoint (`api/threews/auction.js` / `api/x402/pay-by-name.js` area), during the first-dibs window require minLevel 4. This perk has `payPerUse: 'name.auction'`, so allow the pay path after the window per `allowPayPerUse`.
+6. **Flip `enforced` + tests.** For EACH perk, only after its gate is wired: set `enforced:true` in `GATED_FEATURES` and add a focused test (mirror `tests/api/forge-gameready.test.js` and `forge-high-gate.test.js`): a sub-tier caller gets `402 three_hold_required` with the right `required` tier; a holder (valid tier pass) passes. A perk whose gate isn't shipped stays `enforced:false` — never flip a flag without the boundary check.
+
+## Definition of done
+- [ ] Every flipped `enforced:true` perk has a live boundary check via `requireFeatureAccess` and a passing test for both block and allow.
+- [ ] `rateMultiplier` scales MCP + forge free quotas; `mcp.priority` reorders the queue for 2+ holders.
+- [ ] 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; `/three` "Live vs Planned" labels now match reality.
+
+## Verification
+- `vitest run` the new per-perk gate tests; assert 402 shape (`held`, `required`, `usd_to_go`, `acquire`) for a Member and pass for a holder pass.
+- `npm run dev`: as a non-holder, attempt to create a private world → 402; present a Silver tier pass header → success.
+- MCP: fire a batch as a holder vs non-holder and confirm the holder's effective free quota is `rateMultiplier`× and priority dequeue ordering holds under contention.
+- Load `/three`: every perk row labeled "Live" is genuinely enforced; none claims an unwired gate.
+
+## 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/P21-revenue-analytics-dashboards.md b/prompts/production-readiness/P21-revenue-analytics-dashboards.md
new file mode 100644
index 000000000..9a3b04d35
--- /dev/null
+++ b/prompts/production-readiness/P21-revenue-analytics-dashboards.md
@@ -0,0 +1,52 @@
+# P21 · Revenue Attribution & Creator/Agent Analytics
+
+> **Workstream:** Monetization (revenue engine) · **Priority:** P1 · **Effort:** M · **Depends on:** P19
+
+## 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
+Analytics today is admin totals over the x402 audit log — no creator/agent/endpoint attribution surfaced to the people who earn:
+
+- `api/x402/admin/analytics.js` — admin-only (`requireAdmin`), `?period=1d|7d|30d|90d|all`. Calls `getPaymentStats({ since })` from `api/_lib/x402/audit-log.js`, which aggregates `x402_audit_log` rows where `event_type='payment_settled'`: total payments, total volume (USDC atomics → 6dp), unique payers, `by_route`, `by_network`, `by_day`, plus SIWX grant/access and bypass-by-reason. This is platform-wide x402 traffic, not per-creator revenue, and it reads the audit log, not the settle ledger.
+- `api/_lib/token/payments.js` — the $THREE settle ledger. `token_payments` rows carry `purpose`, `splits` (jsonb legs), `ref_type`, `ref_id`, `user_id`, `payer_wallet`, `usd`, `price_usd`, `total_atomics`. `economyStats({ sinceDays })` already unrolls `splits` to `by_role` (treasury/rewards/seller) and `by_purpose`. `creatorEarnings({ sellerWallet })` sums the seller leg per wallet. `listPayments({ purpose, refType, refId, userId })` is keyset-paginated and filters by `ref_type`/`ref_id` — the attribution hooks already exist on the row.
+- P19 adds per-agent attribution (`agent_id` on settle metadata + `agentEarnings`). This task builds the dashboards on top.
+- `src/dashboard-next/pages/` — `analytics.js` (fetches `/api/billing/revenue`, `/api/widgets`, `/api/billing/summary`, `/api/monetization/revenue?period=`), `monetize.js`, `transactions.js`, `holders.js`, `three-token.js`. Existing revenue endpoints: `api/billing/revenue.js`, `api/billing/summary.js`, `api/monetization/revenue.js`, `api/admin/revenue.js`.
+
+## Problem / opportunity
+A creator can't answer "which of my endpoints/skills/agents made the most $THREE this week, and from whom?" Admin sees grand totals; creators see a flat earnings number (P19) with no breakdown by ref_type, endpoint, or counterpart. The attribution columns (`ref_type`, `ref_id`, `purpose`, per-leg `splits`) are written but never sliced into a creator-facing report. Evidence: `getPaymentStats` groups only by route/network/day for an admin; `economyStats` groups by role/purpose platform-wide; neither filters to a creator's own sales nor breaks revenue down by endpoint × counterpart. Without attribution, creators can't optimize what they sell.
+
+## Mission
+Build attribution queries over the existing `token_payments` settle ledger (and reconcile the x402 audit log for endpoint hit/conversion stats), and ship creator + agent revenue dashboards that break revenue down by endpoint/skill, by agent, by day, and by paying counterpart — scoped to the requesting creator, not admin-only.
+
+## Scope
+**In scope:** creator-scoped attribution reads (`api/_lib/token/payments.js`), a creator analytics endpoint, an agent revenue breakdown, dashboard panels in `analytics.js`/`monetize.js`. Reuse `economyStats`/`creatorEarnings`/`agentEarnings` shapes.
+**Out of scope:** changing the admin analytics endpoint's contract (extend, don't break), new charting libs (use the existing dashboard render helpers), the buyback/distribute reporting.
+
+## Implementation guide
+1. **Attribution reads (`api/_lib/token/payments.js`).** Add `creatorRevenueBreakdown({ sellerWallet, agentIds, sinceDays, groupBy })` where `groupBy ∈ {ref_type, ref_id, purpose, day, payer_wallet}`. Filter rows to the creator's sales: `splits @> [{role:'seller',address:sellerWallet}]` (jsonb-containment, index-friendly — same pattern `creatorEarnings` uses) OR the P19 `agent_id IN (...)`. Sum the seller-leg atomics per group. Return `{ since, total_atomics, by_endpoint[], by_agent[], by_day[], top_payers[] }`. Keep it pure SQL aggregation — never load all rows into JS to group.
+2. **Endpoint hit + conversion (reconcile audit log).** For paid endpoints, join the settle ledger (revenue) with `getPaymentStats`-style `x402_audit_log` counts (`payment_settled` vs `payment_failed` per `route`) so a creator sees attempts, failures, and conversion per endpoint — revenue alone hides churned buyers. Add a `byRouteWithRevenue` read that pairs route hit-count with settled volume; restrict to the creator's owned routes/agents.
+3. **Creator analytics endpoint (`api/three/[action].js` add `revenue-breakdown`, or `api/billing/revenue.js` extend).** Auth = session/bearer (mirror `api/three/[action].js` `handleEarnings` at line 288 and `skill-prices.js` ownership checks). Resolve the caller's seller wallet(s) + owned agent ids, call `creatorRevenueBreakdown`, return the breakdown. Window via `?sinceDays`. Never return another creator's rows.
+4. **Agent revenue endpoint.** Per-agent slice for the agent owner: revenue by skill/endpoint for one agent over a window, built on P19's `agentEarnings` + the new breakdown. Powers the agent profile's earnings tab.
+5. **Dashboards.** In `src/dashboard-next/pages/analytics.js`, add a "Revenue by endpoint / by agent / over time" section fed by the new endpoint — bar list per endpoint (volume + conversion), a sparkline per day, a top-payers list. In `monetize.js`, add the per-agent breakdown beside P19's earnings card. Design loading (skeleton rows), empty ("no sales yet — list a skill"), populated, and error (actionable retry) states. Numbers in $THREE with the USD equivalent from `price_usd` on the row — never a hardcoded price.
+6. **Admin parity (optional, additive).** Extend `getPaymentStats` with an optional `groupBy: 'ref_type'|'purpose'` so the admin endpoint can also show settle-ledger attribution, without breaking its current response shape.
+
+## Definition of done
+- [ ] Creator/agent breakdowns are scoped to the requester and sourced from `token_payments` (+ audit-log conversion), no new revenue table.
+- [ ] Endpoint view shows volume AND conversion (settled vs failed) per owned route.
+- [ ] Money paths covered by tests (verify, settle, split, idempotency); `npm test` passes — including that breakdown sums equal the flat `creatorEarnings` total.
+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages`.
+- [ ] `git diff` self-reviewed; revenue math validated (Σ by_endpoint == Σ by_agent == total).
+
+## Verification
+- `vitest run tests/revenue-breakdown.test.js`: seed `token_payments` with seller legs across two endpoints/agents/days, assert each `groupBy` partitions correctly and totals reconcile with `creatorEarnings`; assert a foreign seller's rows never leak.
+- `npm run dev`, `/dashboard/analytics` as a creator with sales: network tab shows the real breakdown endpoint; bars/sparkline render; switching `?sinceDays` re-queries.
+- Confirm a non-owner gets 403 (or empty) for another creator's agent revenue.
+
+## 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/P22-evm-x402-lane-scale.md b/prompts/production-readiness/P22-evm-x402-lane-scale.md
new file mode 100644
index 000000000..c426c26e3
--- /dev/null
+++ b/prompts/production-readiness/P22-evm-x402-lane-scale.md
@@ -0,0 +1,54 @@
+# P22 · Harden the EVM x402 Lanes for Scale
+
+> **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 EVM x402 rail spans three networks and three signature methods, but only the Base EIP-3009 path is exercised:
+
+- `api/_lib/x402-spec.js` — the verify/settle core. CAIP-2 networks: `NETWORK_BASE_MAINNET` (`eip155:8453`), `NETWORK_BASE_SEPOLIA` (`eip155:84532`), `NETWORK_ARBITRUM_MAINNET` (`eip155:42161`), gathered in `CDP_EVM_NETWORKS`. `paymentRequirements()` emits an EIP-3009 accept first, then `permit2VariantOf()` appends a Permit2 sibling — but ONLY when CDP creds are present (`env.CDP_API_KEY_ID`/`CDP_API_KEY_SECRET`); without them no Permit2 sibling is advertised (we can't settle it). `verifyPayment()` does defense-in-depth: decodes the signed amount (`decodeSignedAmount`) and recipient (`decodeSignedRecipient`) from both EIP-3009 (`authorization.value`/`.to`) and Permit2 (`permitted.amount`/witness) payloads, rejecting under-payment / wrong payTo BEFORE calling the facilitator, then cross-checks the facilitator's echoed `network`/`asset`. `settlePayment()` sends `/settle` with an `idempotencyKey` from `buildIdempotencyKey()` and cross-checks echoed `network`/`payer`. `facilitatorFor(network)` returns `{direct:true}` for BSC (`x402-bsc-direct.js`), `{url, cdp:true}` for CDP networks (requires creds), else throws.
+- `public/x402.js` + `public/x402-pay-core.js` — the drop-in buyer modal. `EVM_NETWORKS` lists Base, Base Sepolia, Arbitrum (42161), Optimism (10). The modal signs EIP-3009 `transferWithAuthorization` typed data locally (`buildEip3009TypedData`, `isEip3009Accept`) — it deliberately picks the EIP-3009 entry over the Permit2 sibling, since signing against Permit2 builds a payload the facilitator rejects. EIP-2612 sponsorship + Permit2 are SDK-client paths (the facilitator's `x402ExactPermit2Proxy` submits the approval atomically so the payer never broadcasts an approve tx).
+- `api/x402-checkout.js` — Solana-only tx builder (`prepare`/`encode`); EVM clients sign typed data locally and don't use it. `tests/x402-checkout-prepare.test.js` covers the Solana prepare path.
+- Existing tests: `tests/evm-payment-verify.test.js` (verify path), `x402-giving.test.js`, `x402-vanity-sealed-envelope.test.js`.
+
+## Problem / opportunity
+Base EIP-3009 is proven; the rest is wired but untested at scale: the Permit2/EIP-2612 sponsorship path only emits when CDP creds exist and has no test asserting a sponsored settlement; Arbitrum is in `CDP_EVM_NETWORKS` and the modal's `EVM_NETWORKS` but there's no Arbitrum verify/settle test or receipt check; under load there's no validation that idempotency holds across concurrent settles or that the facilitator echo cross-checks catch a wrong-network reply. A silent failure on these lanes means lost revenue or, worse, an under-paid settlement slipping through.
+
+## Mission
+Validate and harden every EVM lane end-to-end — EIP-3009 + Permit2/EIP-2612 sponsorship, on Base and Arbitrum — proving sponsorship works, gas is sponsor-paid, settlement is idempotent under concurrency, receipts encode correctly, and the supported-network matrix is documented and accurate.
+
+## Scope
+**In scope:** test + harden `verifyPayment`/`settlePayment` for EIP-3009 and Permit2/EIP-2612 across Base + Arbitrum; concurrency/idempotency tests; receipt-header encoding tests; a supported-networks doc; fixing any gap found (e.g. a network advertised in the modal but unsettleable).
+**Out of scope:** Solana lane changes, BSC direct scheme internals (already separate), adding brand-new chains beyond what `CDP_EVM_NETWORKS` already declares.
+
+## Implementation guide
+1. **Network matrix audit.** Cross-check `EVM_NETWORKS` in `public/x402.js`/`x402-pay-core.js` against `CDP_EVM_NETWORKS` + `facilitatorFor` in `api/_lib/x402-spec.js`. Optimism (`eip155:10`) is in the modal list but NOT in `CDP_EVM_NETWORKS` — confirm whether `facilitatorFor('eip155:10')` can settle; if it throws, either add it to the settle set or remove it from the modal so the UI never advertises an unsettleable lane (a dead path = a failed checkout). Resolve the mismatch, don't paper over it.
+2. **Permit2/EIP-2612 sponsorship test.** Add `tests/x402-permit2-sponsorship.test.js`: assert `paymentRequirements()` appends a `permit2VariantOf` sibling WHEN CDP creds are set and omits it when absent (the existing gate). For a Permit2 payload, assert `decodeSignedAmount`/`decodeSignedRecipient` read `permitted.amount` + witness recipient correctly and that under-payment / wrong-payTo are rejected pre-facilitator. Mock the facilitator HTTP boundary only (network I/O) — never mock the signature decode/verify logic.
+3. **Arbitrum end-to-end.** Add Arbitrum (`eip155:42161`) cases to `tests/evm-payment-verify.test.js`: a valid EIP-3009 authorization verifies; a wrong-`asset` or wrong-`network` facilitator echo trips `facilitator_bad_response` (502); a payment for chain A presented as chain B is rejected. Confirm the USDC EIP-3009 domain (`buildEip3009TypedData`) uses Arbitrum's correct contract/version.
+4. **Idempotency under concurrency.** Test that two concurrent `settlePayment` calls for the same `paymentPayload` produce the same `buildIdempotencyKey` and the facilitator is sent the idempotency header so a retry/double-submit settles once. On the app side, the settled payment must still land exactly once in `token_payments` (UNIQUE(nonce)/UNIQUE(tx_signature) per `api/_lib/token/payments.js`) — assert a replay resolves to `already_settled`, never a double-credit.
+5. **Receipt encoding.** Test `encodePaymentResponseHeader(settleResult, extensions)` produces a well-formed `X-PAYMENT-RESPONSE` with `transaction`/`network`/`payer` and the Offer-&-Receipt extension envelope when configured. Assert the explorer URL resolves per network (`explorerUrl` in `public/x402.js`: basescan / arbiscan).
+6. **Gas/sponsorship behavior.** Document and assert that on the Permit2/EIP-2612 path the facilitator (`x402ExactPermit2Proxy`) pays gas and the buyer never broadcasts an approve tx — surface a clear modal message for wallets lacking sponsorship support (the modal already falls back to EIP-3009). No fake gas estimates.
+7. **Docs.** Write/update a supported-networks section (e.g. `specs/` or `docs/`): the matrix of network × method × settle-path (EIP-3009 everywhere; Permit2/2612 sponsorship where CDP creds + proxy exist), required env (`CDP_API_KEY_ID`, `CDP_API_KEY_SECRET`, `X402_CDP_FACILITATOR_URL`), and the precise reason a sibling is or isn't advertised.
+
+## Definition of done
+- [ ] Network matrix is consistent across client + server; no lane advertised that can't settle.
+- [ ] Permit2/EIP-2612 sponsorship verified by test (emit gate, payload decode, under-pay/wrong-payTo rejection).
+- [ ] Arbitrum EIP-3009 verify/settle + facilitator echo cross-checks tested.
+- [ ] Money paths covered by tests (verify, settle, split, idempotency); `npm test` passes — including concurrent-settle idempotency and a `token_payments` replay resolving to `already_settled`.
+- [ ] User-visible change → entry in `data/changelog.json`, then `npm run build:pages`.
+- [ ] `git diff` self-reviewed; revenue math validated; supported-networks doc accurate.
+
+## Verification
+- `vitest run tests/evm-payment-verify.test.js tests/x402-permit2-sponsorship.test.js` — all green, including Arbitrum + Permit2 cases.
+- `npm run dev`, open the drop-in modal on a paid endpoint with MetaMask on Base and on Arbitrum: confirm the EIP-3009 sign flow, then the `X-PAYMENT` header builds and the resource unlocks; check network tab for a real `/verify`+`/settle` round-trip and an `X-PAYMENT-RESPONSE` with the right explorer link.
+- With CDP creds set, confirm the 402 challenge advertises a Permit2 sibling; with creds unset, confirm it does not.
+
+## Guardrails
+- No mocks/fake data. Real on-chain verification + settlement (mock only the facilitator HTTP boundary in unit tests, never the decode/verify logic). Idempotent (no double-charge / double-payout).
+- $THREE only in copy; never hardcode a non-$THREE mint. USDC is the payment-rail asset, not a coin to promote.
+- 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` (and never commit a bundled `api/x402-checkout.js` / `public/x402*.js`).
diff --git a/prompts/production-readiness/P47-developer-portal-docs-home.md b/prompts/production-readiness/P47-developer-portal-docs-home.md
new file mode 100644
index 000000000..80f4e9a30
--- /dev/null
+++ b/prompts/production-readiness/P47-developer-portal-docs-home.md
@@ -0,0 +1,57 @@
+# P47 · Developer portal / docs homepage
+
+> **Workstream:** SEO, content & developer experience · **Priority:** P1 · **Effort:** M · **Depends on:** none
+
+## Before you start
+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (surface map). The changelog system is described in CLAUDE.md.
+2. three.ws monorepo: vanilla JS + Vite. Docs in `docs/`, blog in `blog/`, SEO via `scripts/inject-seo-meta.mjs` + `api/sitemap.js` + `api/page-og`. Page catalog in `data/pages.json`. Dev: `npm run dev`. Tests: `npm test`.
+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.
+
+## Context
+The docs surface is real and large. `docs/` holds ~111k lines of markdown across 80+ files (`start-here.md`, `quick-start.md`, `introduction.md`, `api-reference.md`, `js-api.md`, `web-component.md`, `mcp.md`, `sdk.md`, `embedding.md`, `erc8004.md`, a `tutorials/` set, an `internal/` ops set, etc.). They are served as raw `.md` and rendered client-side by `docs/index.html` — a single-page docs app that:
+- ships a hardcoded `NAV` array (sections: SDK/API reference, Integrations, Tutorials, Reference, Operations…) at ~line 790,
+- hash-routes (`#start-here`), `fetch`es `/docs/<path>.md`, and renders with `[email protected]` + `highlight.js` from CDN,
+- defaults to `start-here` when no path is given, and has a sidebar filter input + "Copy page / Open in Claude" page tools.
+
+Routing: `vite.config.js` maps `/docs` and `/docs/` → `docs/index.html`; `copy-static-docs` copies `docs/` → `dist/docs`. `data/pages.json` lists `/docs` and ~16 individual doc routes (`/docs/start-here`, `/docs/quick-start`, `/docs/api-reference`, …) that feed the sitemap, `llms.txt`, and `scripts/inject-seo-meta.mjs`.
+
+## Problem / opportunity
+`/docs` opens straight into the `start-here` article body. There is **no portal landing**: no role-based "I'm a no-code creator" vs "I'm a developer" split, no surfaced "popular paths," no top-level search across all pages (the sidebar input only filters nav *labels*, not page content), and the NAV array drifts from `data/pages.json` (links are maintained in two places). A first-time developer lands on prose with no map of where to go. The pieces exist (renderer, nav, ~80 pages) — they need a real front door at the bar of Stripe/Vercel docs homes.
+
+## Mission
+Ship a real docs portal home at `/docs`: a role-based "start here" landing, a curated set of paths/cards into the existing markdown, and client-side full-text search across all doc pages — reusing the existing `docs/index.html` renderer and the vanilla/Vite stack (no framework, no build step beyond what exists).
+
+## Scope
+**In scope:** A landing view in `docs/index.html` shown for the bare `/docs` route; role/task cards linking to existing `.md` pages; a search box that queries page *content* (built index); reconciling the NAV with `data/pages.json`; all states (loading/empty/error) for search; a changelog entry.
+**Out of scope:** Rewriting article content; a server-side renderer; moving off `marked`; touching `blog/` (that's P49); the OpenAPI explorer (P48).
+
+## Implementation guide
+1. **Landing view, not an article.** In `docs/index.html`, when `currentPath()` resolves to the bare docs root (no hash, path === `/docs`), render a **portal home** instead of fetching `start-here.md`. Build it from real content:
+ - A hero with the product one-liner (reuse copy from `docs/start-here.md`).
+ - **Two role lanes** mirroring `start-here.md`'s "Two kinds of people": *Creators (no code)* → `make-your-agent`, `share-and-embed`, `do-i-need-crypto`; *Developers* → `quick-start`, `introduction`, `api-reference`, `web-component`, `mcp`, `sdk`. Each card: title, one-line description, arrow, hover/focus states.
+ - A "popular" / "by task" grid (Embed an agent → `embedding`; Generate 3D from a prompt → `tutorials/text-to-3d`; Register on-chain → `erc8004`; Pay-per-call → `x402`). Use only paths that exist in `docs/`.
+2. **Single source for the path list.** Pull the canonical doc routes from `data/pages.json` (the `/docs/*` section) so the portal cards and the sidebar can't drift from the catalog. Keep the human-friendly grouping in `NAV`, but assert at runtime (dev only) that every `NAV` `path` exists in `data/pages.json` and warn on a mismatch — eliminate the dual-maintenance trap.
+3. **Real content search.** Add a build step `scripts/build-docs-search-index.mjs` that reads every `docs/**/*.md` (skip `internal/` if it shouldn't be public-indexed — match what `data/pages.json` exposes), strips markdown, and writes `public/docs/search-index.json` (`[{path, title, headings[], excerpt, body}]`, body truncated to keep it lean). Wire it into the build (add an npm script, e.g. `build:docs-search`, and call it from `build:pages` or the existing docs copy step). In `docs/index.html`, lazy-`fetch` that index on first keystroke, score by title/heading/body match, and render a results dropdown (keyboard navigable, `Esc` to close, designed empty + error states). Add a `/` keyboard shortcut to focus search.
+4. **Wire it into nav.** Confirm `/docs` is reachable from the home doors (`pages/home.html` already links `/docs`) and the global nav (`public/nav.js`). The portal must link back out to `/blog`, `/` and the live API explorer once P48 lands (leave a clearly-labeled link only if the route exists).
+5. **SEO.** `/docs` already has a `data/pages.json` entry; ensure its `title`/`description` describe a portal, run `npm run seo:meta` so `inject-seo-meta.mjs` backfills canonical + JSON-LD, and confirm the new search-index file is excluded from the sitemap.
+
+## Definition of done
+- [ ] `/docs` renders a role-based portal landing (not an article); every card links to a doc page that exists.
+- [ ] Content search returns ranked results across all public docs, with loading/empty/error states and keyboard nav.
+- [ ] NAV and `data/pages.json` reconciled; dev-time mismatch warning in place; no dual-maintained link list ships broken.
+- [ ] `npm test` passes; build (`npm run build:pages` and/or `npm run build`) succeeds.
+- [ ] User-visible → `data/changelog.json` entry + `npm run build:pages`.
+- [ ] `git diff` self-reviewed.
+
+## Verification
+- `npm run dev`, open `http://localhost:3000/docs` → portal home, not an article. Tab through cards: hover/focus rings present.
+- Type a query (e.g. "embed", "web component", "x402") → ranked results; clicking one hash-routes to the article. Empty query state and a no-results state both look intentional.
+- Existing deep links still work: `http://localhost:3000/docs/quick-start`, `#api-reference`.
+- `npm run build` then check `dist/docs/search-index.json` exists and parses; `curl -s http://localhost:3000/sitemap.xml` does **not** list the search index.
+- `node -e "JSON.parse(require('fs').readFileSync('public/docs/search-index.json'))"` exits 0.
+- DevTools console: no errors/warnings from the portal code.
+
+## Guardrails
+- No mocks/fake data. Real content, real links (CLAUDE.md: changelog `link` must be a live page path).
+- $THREE only. Stage explicit paths; re-check `git status`. Push only when asked, to BOTH remotes.
+- Watch the `npx vercel build` trap: never commit bundled `api/*.js`.
diff --git a/prompts/production-readiness/P48-openapi-explorer.md b/prompts/production-readiness/P48-openapi-explorer.md
new file mode 100644
index 000000000..08b98d65c
--- /dev/null
+++ b/prompts/production-readiness/P48-openapi-explorer.md
@@ -0,0 +1,58 @@
+# P48 · Interactive OpenAPI explorer
+
+> **Workstream:** SEO, content & developer experience · **Priority:** P2 · **Effort:** M · **Depends on:** P47 (nice-to-have)
+
+## Before you start
+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md` (surface map). The changelog system is described in CLAUDE.md.
+2. three.ws monorepo: vanilla JS + Vite. Docs in `docs/`, blog in `blog/`, SEO via `scripts/inject-seo-meta.mjs` + `api/sitemap.js` + `api/page-og`. Page catalog in `data/pages.json`. Dev: `npm run dev`. Tests: `npm test`.
+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.
+
+## Context
+There is a real, hand-built OpenAPI document but no interactive UI for it.
+- `api/openapi-json.js` (`982` lines) serves a full OpenAPI **3.1.0** doc at `/openapi.json` (rewrite in `vercel.json`: `/openapi\.json` → `/api/openapi-json`). It documents `POST /api/mcp` (JSON-RPC MCP tool calls), the paid `/api/x402/*` and `/api/insights/*` routes (HTTP 402, USDC over x402, no API key), `securitySchemes` `bearerAuth` + `apiKeyAuth`, and carries `x-payment-info`/`x-guidance` extensions for agent discovery (AgentCash, x402scan).
+- A static mirror exists at `public/.well-known/openapi.yaml` (~72 KB). The JSON endpoint is the live source of truth.
+- `docs/api-reference.md` (~24 KB) is the prose REST reference, surfaced in the docs portal NAV as "REST API". `docs/api.html` also exists.
+
+## Problem / opportunity
+The OpenAPI doc is rich enough for a fully interactive explorer, but a developer today can only read static prose (`docs/api-reference.md`) or curl the raw JSON. There's no "try it" surface, no schema browser, no copyable request examples, and nothing that visually communicates the paid (x402) vs free vs bearer-auth split that makes this API distinctive. A self-serve, browsable API console is table stakes for developer adoption and gets the API indexed by tooling that scrapes rendered reference pages.
+
+## Mission
+Ship a public, interactive API explorer page wired to the **live** `/openapi.json`, served at a real route (e.g. `/docs/api` or `/api-explorer`), kept automatically in sync with the endpoint (no second copy of the spec), and styled to fit the docs/site dark theme. Make the x402-paid vs bearer-auth distinction legible.
+
+## Scope
+**In scope:** A vendored, self-hosted explorer UI (Scalar API Reference or Swagger UI) pointed at `/openapi.json`; a real route + `data/pages.json` entry + nav links; sync verification; SEO meta; all states (loading/error if the spec fails to fetch).
+**Out of scope:** Changing the API itself; auth/credential injection for live authenticated calls (read-only/try-public only — never embed real keys); rewriting `api-reference.md` (link to it, keep both).
+
+## Implementation guide
+1. **Pick the lightest fit.** Prefer **Scalar API Reference** (modern, dark-themeable, single script/standalone bundle, renders 3.1 well) or **Swagger UI** if you want the most familiar console. Whichever you choose: **vendor it self-hosted** — download the standalone bundle into `public/vendor/<tool>/` (do not load a third-party CDN at runtime; CLAUDE.md + the site's CSP posture favor self-hosted assets). Note the version and license in a short header/README beside the vendored files.
+2. **Create the page.** Add `public/api-explorer.html` (or `docs/api.html` if you prefer the docs namespace — but don't clobber the existing file; pick a clean route). It should:
+ - Configure the explorer to load the spec from `/openapi.json` at runtime (so it's always live — never paste the spec inline).
+ - Apply a dark theme matching `public/style.css` / the docs tokens (`docs/index.html` `--docs-accent: #8b5cf6`).
+ - Show a clear loading state and a designed error state if `/openapi.json` 404s or fails to parse (don't leave a blank frame).
+ - Include a short header banner explaining the auth model (free MCP `getting_started`, OAuth/API-key bearer, and x402-paid `/api/x402/*` settling in USDC) — text only, no secrets.
+3. **Route + catalog.** Add a route to `vite.config.js` (dev) and `vercel.json` (prod) for `/api-explorer` (or `/docs/api`) → the html file. Add a `data/pages.json` entry (title/description/section) so it joins the sitemap, `llms.txt`, and gets SEO meta. Link to it from `docs/index.html` NAV ("REST API" group, add "API explorer (interactive)") and from `docs/api-reference.md` (a banner link at the top: "Prefer to click around? Open the interactive explorer →").
+4. **Keep it in sync — prove it.** Because the page fetches `/openapi.json` live, sync is automatic at runtime. Add a guard so it stays valid: extend or add a verifier (reuse the pattern in `scripts/verify-x402-discovery.mjs`) — e.g. `scripts/verify-openapi.mjs` that fetches `/openapi.json` (default `https://three.ws`, `--base` override), validates it parses as OpenAPI 3.1, asserts the documented `paths` are non-empty and that the x402 paths carry `x-payment-info` with both `price` and `protocols` (the AgentCash requirement noted in `api/openapi-json.js`), and that the static `public/.well-known/openapi.yaml` mirror hasn't gone stale relative to the live doc (warn, don't fail the build, if it drifts). Wire an npm script `verify:openapi`.
+5. **SEO.** Run `npm run seo:meta` so canonical/OG/JSON-LD land on the new page from its `data/pages.json` copy.
+
+## Definition of done
+- [ ] Public explorer page renders all operations from the **live** `/openapi.json` (not an inlined copy), themed to the site, reachable from docs nav + `api-reference.md`.
+- [ ] Explorer UI is self-hosted under `public/vendor/` (no runtime third-party CDN); version + license recorded.
+- [ ] Loading + error states designed; spec fetch failure degrades gracefully.
+- [ ] `verify:openapi` script added and passing; x402 ops show `price` + `protocols`.
+- [ ] `npm test` passes; build (`npm run build:pages` and/or `npm run build`) succeeds.
+- [ ] User-visible → `data/changelog.json` entry + `npm run build:pages`.
+- [ ] `git diff` self-reviewed.
+
+## Verification
+- `npm run dev` → open the new route; every endpoint group from `/openapi.json` renders; expanding an operation shows params, schemas, and example request. Toggle a paid `/api/x402/*` op → its 402/x402 payment info is visible.
+- Kill the spec route mentally: load with `/openapi.json` returning an error (e.g. point at a bad base) → designed error state, not a blank screen.
+- `view-source:` the page → no inlined spec JSON, no third-party CDN `<script src>` for the explorer, no secrets.
+- `node scripts/verify-openapi.mjs --base=http://localhost:3000` exits 0.
+- `curl -s http://localhost:3000/sitemap.xml | grep -i explorer` (or your route) shows it indexed; `view-source` shows canonical + JSON-LD.
+- DevTools console: no errors/warnings.
+
+## Guardrails
+- No mocks/fake data. Real content, real links (CLAUDE.md: changelog `link` must be a live page path).
+- $THREE only. Stage explicit paths; re-check `git status`. Push only when asked, to BOTH remotes.
+- Watch the `npx vercel build` trap: never commit bundled `api/*.js`. Never edit `api/openapi-json.js` into a bundle.
+- Never embed a real API key, OAuth token, or wallet secret into the explorer config.
diff --git a/prompts/production-readiness/P53-api-test-coverage-expansion.md b/prompts/production-readiness/P53-api-test-coverage-expansion.md
new file mode 100644
index 000000000..4a708061e
--- /dev/null
+++ b/prompts/production-readiness/P53-api-test-coverage-expansion.md
@@ -0,0 +1,71 @@
+# P53 · API test coverage expansion (high-risk mutations)
+
+> **Workstream:** Testing, CI & quality · **Priority:** P1 · **Effort:** L · **Depends on:** P58 (coverage instrumentation) recommended, not required
+
+## Before you start
+1. Read `CLAUDE.md` (rules that override defaults) and `STRUCTURE.md`.
+2. three.ws monorepo: tests via `vitest` (`tests/**/*.test.js`) + Playwright (`tests/e2e/**/*.spec.js`); gate is `npm test`. CI in `.github/workflows/ci.yml`. Dev server `npm run dev` (port 3000).
+3. **$THREE is the only coin** — CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. In tests/fixtures use the $THREE CA or a clearly-synthetic placeholder — NEVER a real third-party mint.
+
+## Context
+The suite is large but lopsided. `find tests src -name '*.test.js' -o -name '*.test.mjs'` returns **~466 files**, and `tests/api/` alone holds ~200 of them. But `find api -name '*.js' -not -path '*/_*'` returns **~586 route handlers** (~966 including `api/_lib/**`). Whole families of money- and identity-moving routes have zero direct handler test:
+- **Payments / x402:** good coverage on the *prepare/verify* layer (`tests/api/x402-paid-endpoint-replay.test.js`, `x402-spec.test.js`, `tests/x402-checkout-prepare.test.js`), but the checkout *record/settle* and merchant routes (`api/x402-checkout-record.js`, `api/x402-merchant.js`, `api/x402-status.js`) are thin.
+- **pump dashboard mutations:** `api/pump/withdraw-prep.js`, `withdraw-confirm.js`, `accept-payment-prep.js`, `accept-payment-confirm.js`, `launch-prep.js` move value and are under-tested at the handler level.
+- **Avatars/agents CRUD:** `tests/api/agents.test.js` is the gold-standard pattern; many sibling mutation routes (`api/forge-upload.js`, `api/forge-creation.js`, avatar persist routes) lack equivalents.
+
+The established handler-test pattern is already excellent — follow it exactly:
+- `tests/api/agents.test.js`: `vi.mock` for `_lib/auth.js`, `_lib/csrf.js`, `_lib/db.js` (tagged-template `sql` stub with a result queue), `_lib/agent-wallet.js`; handler imported *after* mocks; `makeReq`/`makeRes` build a Node `Readable` request and a capturing response.
+- `tests/_helpers/monetization.js`: shared `createTestAgent`/`makeReq` — note the comment that `agent_id` must be a real UUID (`00000000-0000-4000-8000-…`) or `isUuid()` 404s before the logic runs.
+- All responses flow through `api/_lib/http.js` (`json`/`error`/`serverError`/`rateLimited`), so assertions target `res.statusCode` + parsed `res.body` and the security headers it always sets (`x-content-type-options`, `x-frame-options`).
+
+## Problem / opportunity
+350+ mutation routes can regress silently. A broken `withdraw-confirm`, a CSRF gate that stops firing, or a settlement double-credit would ship green. The fix is not "test everything" — it's a **risk-ranked push** that closes the gap on the routes where a regression costs money or leaks identity, plus a measurable `api/` coverage target so the gap can't quietly reopen.
+
+## Mission
+Add handler-level vitest specs for the highest-risk untested `api/` mutation routes, following the existing `tests/api/agents.test.js` pattern, and define + document a coverage target for `api/`.
+
+## Scope
+**In scope:** New `tests/api/*.test.js` for ranked routes across auth, x402 settlement/merchant, pump withdraw/accept-payment, agents/avatars/forge CRUD. A short ranking doc. A coverage target proposal for `api/` (coordinate with P58).
+**Out of scope:** Rewriting handlers (only fix a bug if a new test exposes one — note it). E2E (that's P54). Load (P55). Changing the global `npm test` gate semantics.
+
+## Implementation guide
+1. **Rank the gap (do this first, commit the ranking).**
+ - List untested handlers: `comm -23 <(find api -name '*.js' -not -path '*/_*' | sort) <(grep -rhoE "api/[a-zA-Z0-9/_-]+\.js" tests/api | sort -u)` — treat as a starting signal, then eyeball.
+ - Score each by **(writes value | moves money | touches auth/identity | CSRF-gated)**. Top of the list: `api/x402-checkout-record.js`, `api/x402-merchant.js`, `api/pump/withdraw-prep.js`, `api/pump/withdraw-confirm.js`, `api/pump/accept-payment-confirm.js`, `api/forge-upload.js`, avatar persist routes, any auth route lacking a test.
+2. **For each chosen route, write a spec mirroring `tests/api/agents.test.js`:**
+ - Declare `vi.mock('../../api/_lib/auth.js', …)`, `vi.mock('../../api/_lib/csrf.js', …)`, `vi.mock('../../api/_lib/db.js', …)` (sql result queue) BEFORE the dynamic `import('../../api/<route>.js')`.
+ - Mock external boundaries the route hits (`_lib/agent-wallet.js`, Solana RPC fetch, facilitator verify/settle as `x402-paid-endpoint-replay.test.js` does) — never reach a real chain or RPC.
+ - Reuse `makeReq`/`makeRes` (copy from `agents.test.js` or import from `tests/_helpers/monetization.js`).
+3. **Cover the contract, not just the happy path** — each spec asserts:
+ - **Method gate:** wrong method → 405 (handlers call `method(...)` from `http.js`).
+ - **Auth gate:** no session/bearer → 401.
+ - **CSRF gate:** cookie-session mutation without CSRF → 403 (see how `agents.test.js` mocks `requireCsrf`; the gate itself lives in `security-csrf-gates.test.js`).
+ - **Validation:** malformed body → 400 via `validationError`.
+ - **Happy path:** valid input → correct `sql` calls fired (assert against the captured `sqlState.calls`) + 200/201 shape.
+ - **Idempotency/replay where relevant:** a confirm route must not double-settle (model on `x402-paid-endpoint-replay.test.js`).
+4. **Coverage target.** With P58's v8 coverage enabled, add a per-directory threshold for `api/` (start at the measured baseline, e.g. lines ≥ current %, then ratchet). If P58 isn't landed yet, document the intended target in `tests/api/README.md`-style note and wire the threshold when P58 merges.
+5. **Determinism.** No real network, no timers without `vi.useFakeTimers`, no `process.env` writes that leak across files (restore in `afterAll`, like `tests/api/forge-cost-cap.test.js`). Use synthetic Solana addresses (`Keypair.generate().publicKey.toBase58()` or `3wsSynthetic…`), the $THREE CA, or USDC mint — never a third-party mint.
+
+## Definition of done
+- [ ] New checks pass locally and in CI; `npm test` green.
+- [ ] No flaky tests introduced; deterministic (no real network in unit tests).
+- [ ] `git diff` self-reviewed.
+- [ ] Ranking doc committed; ≥ the top-ranked untested money/auth routes now have specs covering method + auth + CSRF + validation + happy path.
+- [ ] An `api/` coverage target is defined (threshold wired if P58 landed, else documented).
+
+## Verification
+```bash
+# Run only the new/affected API specs fast:
+npx vitest run tests/api
+# Full gate:
+npm test
+# Prove a new test actually guards the route: temporarily break the route
+# (e.g. drop the CSRF check or flip a status code), re-run the spec, confirm RED,
+# then revert. Paste the before/after into your report.
+git stash # or git checkout -- the route, after the deliberate break
+```
+
+## Guardrails
+- No real third-party coin mints in fixtures. No mocks of the kind CLAUDE.md forbids in product code — but test doubles/stubs ARE appropriate inside tests.
+- Stage explicit paths; re-check `git status`. Push only when asked, to BOTH remotes.
+- Watch the `npx vercel build` trap: never commit bundled `api/*.js` (check `head -1` for `__defProp`/`createRequire`).
diff --git a/prompts/production-readiness/P61-upgrade-authority-multisig-migration.md b/prompts/production-readiness/P61-upgrade-authority-multisig-migration.md
new file mode 100644
index 000000000..6c68d2b2f
--- /dev/null
+++ b/prompts/production-readiness/P61-upgrade-authority-multisig-migration.md
@@ -0,0 +1,72 @@
+# P61 · Migrate upgrade authority to multisig & define key rotation
+
+> **Workstream:** On-chain & contracts · **Priority:** P1 · **Effort:** M · **Depends on:** none (do before/alongside P60)
+
+## 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
+Authority over the platform's upgradeable on-chain programs currently sits on **single deployer/hot keys** — a custody risk before scaling.
+
+**Solana programs (BPF, upgradeable — the upgrade authority can replace program bytecode):**
+- `skill_license` — program `EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8`. `contracts/skill-license/DEPLOYMENT.md` documents three keys: the **program keypair** (`SKILL_LICENSE_PROGRAM_KEYPAIR`), the **deploy/upgrade authority** (`~/.config/solana/skill-license-deployer.json` → `SKILL_LICENSE_DEPLOY_AUTHORITY`), and the **minter** (`SKILL_LICENSE_MINTER_KEY`, the backend wallet authorized for `mint_skill_license`/`revoke_skill_license`). The doc ends with a `solana program set-upgrade-authority` snippet (migration **pending**) and notes the minter is rotatable on-chain via `set_minter` (admin-only) and that production should init the marketplace with a **separate** admin authority so a cold key can rotate the minter.
+- `agent_invocation` — program `AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo` (`contracts/agent-invocation/Anchor.toml` cluster `devnet`, wallet `~/.config/solana/agent-invocation-deployer.json`). Non-trust-bearing (emits events only) but still upgradeable — same upgrade-authority risk.
+
+**EVM ownership (related, same theme):** `AgentPayments` owner (set via `AGENT_PAYMENTS_OWNER`) and the ERC-8004 registry owners are currently the deployer EOA. `specs/SECURITY.md` governance roadmap: "Migrate to a 3-of-5 Safe on Base before opening public registration."
+
+## Problem / opportunity
+A single hot key can upgrade `skill_license` bytecode or rotate the minter. Leak or loss = total compromise (or bricking) of the program. There is a documented `set-upgrade-authority` step but no executed migration and no written rotation runbook for the minter/admin/validator secrets. Moving upgrade authority to a multisig/cold key and writing a tested rotation procedure removes the single point of failure that any auditor or integrator will flag first.
+
+## Mission
+Migrate the upgrade authority of both Solana programs to a multisig (e.g. Squads) or cold key, document the exact procedure and the cosigner set, and define a concrete rotation runbook for every authority/minter secret (Solana minter via `set_minter`, EVM owner via `transferOwnership`, validator key). Mirror the EVM-side intent by capturing the registry/`AgentPayments` owner → Safe plan.
+
+## Scope
+**In scope:** Standing up (or wiring to) a Solana multisig (Squads recommended); transferring `skill_license` + `agent_invocation` upgrade authority to it on devnet first, then mainnet; a `contracts/UPGRADE_AUTHORITY.md` runbook (or additions to each program's `DEPLOYMENT.md`); a `KEY_ROTATION.md` covering minter (`set_minter`), EVM owner (`transferOwnership`), validator key (`scripts/erc8004/provision-validator-key.mjs`), and program upgrade authority; recording new authority addresses in the deploy docs.
+
+**Out of scope:** Changing program logic (no `lib.rs` edits — `skill_license` already exposes `set_minter`/admin-authority separation; use it). Executing the EVM 3-of-5 Safe migration (document the plan + commands; the Safe ceremony is its own task). Deploying new programs.
+
+## Implementation guide
+1. **Inventory current authorities (read-only first).**
+ ```bash
+ solana program show EdngSwxmDktyrr4phwGEZnCXEoQ27vgnBtowjhKa7Wr8 --url mainnet-beta
+ solana program show AgEntJDMi1A7UadCoYcx6Fm3gusNk8SHLCi7vSUa4Zfo --url devnet
+ ```
+ Record the current `Upgrade Authority` for each, and the current `marketplace.minter` / admin `authority` for `skill_license` (read the `Marketplace` account). Confirm against `DEPLOYMENT.md`.
+2. **Stand up the multisig.** Use Squads (the standard Solana multisig). Create the vault with the intended cosigner set (recommend ≥ 2-of-3 to start, ≥ 3-of-5 to match the EVM roadmap). The Squads **vault PDA** becomes the new upgrade authority. Record the multisig address + members (roles, not key material) in the runbook.
+3. **Migrate upgrade authority on devnet first.**
+ ```bash
+ solana program set-upgrade-authority \
+ <PROGRAM_ID> \
+ --new-upgrade-authority <SQUADS_VAULT_PDA> \
+ --url devnet
+ ```
+ Then verify, redeploy a no-op upgrade *through the multisig* to prove the new authority signs, and only then repeat on mainnet for `skill_license` (and devnet→mainnet as appropriate for `agent_invocation`). The set-upgrade-authority transfer must be signed by the **current** authority — coordinate so that key is available for the one-time transfer, then retired.
+4. **Separate the `skill_license` admin from the minter (production hardening).** Per `DEPLOYMENT.md`, production should initialize the marketplace with a distinct cold **admin authority** so the minter can be rotated by a key that is never on a server. If the marketplace was bootstrapped with `admin == minter`, document the remediation (the admin signs `set_minter` to point at the backend minter; admin itself moves to cold custody). Use `buildInitializeMarketplaceIx({ authority, minter })` / `set_minter` from `api/_lib/skill-license-onchain.js`.
+5. **Write the rotation runbook (`KEY_ROTATION.md`).** One section per secret, each with trigger (scheduled / suspected compromise), exact command, verification, and who-can-execute:
+ - **Solana minter** (`SKILL_LICENSE_MINTER_KEY`): generate new keypair → admin signs `set_minter(new_minter)` → update the Vercel secret → re-run `scripts/skill-license-smoke.mjs` to confirm minting works with the new key. (No redeploy needed; on-chain instruction exists.)
+ - **Program upgrade authority**: `set-upgrade-authority` from the multisig to a new authority (only if cosigner set changes / compromise).
+ - **EVM `AgentPayments` owner**: `transferOwnership(<newOwner>)` (OpenZeppelin `Ownable`) → verify `owner()` → record in `DEPLOYMENTS.md`.
+ - **EVM registry owners**: same `transferOwnership` toward the 3-of-5 Safe per `specs/SECURITY.md` roadmap (document commands + the per-chain list; mark execution as the follow-up task).
+ - **Validator key** (`VALIDATOR_PRIVATE_KEY`): rotate via `scripts/erc8004/provision-validator-key.mjs`, `addValidator(new)` / `removeValidator(old)` per chain; align with `specs/SECURITY.md` V4.
+6. **Record new authorities.** Update `contracts/skill-license/DEPLOYMENT.md` and `contracts/agent-invocation` docs with the multisig as the new upgrade authority (and the admin/minter split), and add/point to the new runbook from `contracts/DEPLOYMENTS.md`. Keep all key material out of the repo — names and roles only.
+7. **Changelog?** Custody migration is security infra users care about. Append a holder-readable `data/changelog.json` entry (tags: `security`, `infra`) — e.g. "On-chain program upgrade authority moved to a multisig; key-rotation procedures published" — then `npm run build:pages`. (If you judge it purely internal, skip per CLAUDE.md; security custody generally qualifies.)
+
+## 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
+- `solana program show <PROGRAM_ID>` reports the **multisig vault** as `Upgrade Authority` for both programs (devnet proven, mainnet for `skill_license`).
+- A test upgrade (no-op) executes only after multisig threshold approval; an upgrade attempt signed by the old deployer key fails.
+- `skill_license` minter rotation rehearsed end-to-end on devnet via `scripts/skill-license-smoke.mjs` (re-runnable, exits non-zero on failure) — admin signs `set_minter`, new minter mints successfully.
+- EVM: `cast call <AgentPayments> "owner()(address)"` matches the documented owner; `transferOwnership` commands in the runbook are copy-paste correct (dry-run with `cast call`/`estimate`).
+- `KEY_ROTATION.md` has an executable, verified path for every secret; no secret value appears in the repo (`git diff` review).
+
+## 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 one-time `set-upgrade-authority` transfer needs the current authority key present — use it for the transfer, then retire it; never leave it as a live fallback.
diff --git a/src/credits.js b/src/credits.js
index 23811623c..1ed3f56b0 100644
--- a/src/credits.js
+++ b/src/credits.js
@@ -71,7 +71,8 @@ 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>';
+ host.innerHTML =
+ '<div class="muted" style="font-size:0.85rem">Pricing loads shortly.</div>';
return;
}
for (const b of buys.slice(0, 8)) {
@@ -112,7 +113,10 @@ function renderLedger(items) {
}
function escapeHtml(s) {
- return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
+ return String(s).replace(
+ /[&<>"]/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c],
+ );
}
function renderAll(data) {
@@ -255,7 +259,13 @@ async function doDeposit() {
let tx;
if (state.asset === 'SOL') {
- tx = await buildSolTransfer({ web3, conn, from: address, to: state.deposit.wallet, amountSol: amount });
+ tx = await buildSolTransfer({
+ web3,
+ conn,
+ from: address,
+ to: state.deposit.wallet,
+ amountSol: amount,
+ });
} else {
const spl = await import('@solana/spl-token');
tx = await buildThreeTransfer({
@@ -273,7 +283,11 @@ async function doDeposit() {
tx.recentBlockhash = blockhash;
tx.lastValidBlockHeight = lastValidBlockHeight;
- const txBase64 = btoa(String.fromCharCode(...tx.serialize({ requireAllSignatures: false, verifySignatures: false })));
+ 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);
@@ -296,12 +310,17 @@ async function verifyAndApply(txSignature, asset) {
});
const data = await r.json().catch(() => ({}));
if (!r.ok) {
- throw Object.assign(new Error(data.error_description || 'Deposit could not be verified.'), { data });
+ 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');
+ setStatus(
+ `Added ${fmtUsd(data.credited_usd)} (${fmtAmount(data.amount)} ${asset}). New balance ${fmtUsd(data.balance_usd)}.`,
+ 'ok',
+ );
}
$('amount').value = '';
$('manual-sig').value = '';
diff --git a/tests/credits.test.js b/tests/credits.test.js
index 30796aed4..9db0343a2 100644
--- a/tests/credits.test.js
+++ b/tests/credits.test.js
@@ -25,16 +25,13 @@ vi.mock('../api/_lib/three-tier.js', () => ({
holderDiscountBps: async () => tier.bps,
}));
-const {
- getCreditAccount,
- creditAccount,
- debitCredits,
- chargeCreditsForAction,
- refundCredits,
-} = await import('../api/_lib/credits.js');
+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' });
+ return Object.assign(new Error('duplicate key value violates unique constraint'), {
+ code: '23505',
+ });
}
beforeEach(() => {
@@ -55,7 +52,9 @@ describe('getCreditAccount', () => {
lifetimeSpentUsd: 0,
});
- db.queue.push([{ balance_usd: '12.500000', lifetime_deposited_usd: '20', lifetime_spent_usd: '7.5' }]);
+ 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,
@@ -66,7 +65,9 @@ describe('getCreditAccount', () => {
describe('creditAccount', () => {
it('rejects a non-positive amount', async () => {
- await expect(creditAccount({ userId: 'u1', amountUsd: 0, idempotencyKey: 'k' })).rejects.toMatchObject({
+ await expect(
+ creditAccount({ userId: 'u1', amountUsd: 0, idempotencyKey: 'k' }),
+ ).rejects.toMatchObject({
code: 'bad_request',
});
});
@@ -103,7 +104,9 @@ describe('creditAccount', () => {
describe('debitCredits', () => {
it('rejects a non-positive amount', async () => {
- await expect(debitCredits({ userId: 'u1', amountUsd: 0, idempotencyKey: 'k' })).rejects.toMatchObject({
+ await expect(
+ debitCredits({ userId: 'u1', amountUsd: 0, idempotencyKey: 'k' }),
+ ).rejects.toMatchObject({
code: 'bad_request',
});
});
@@ -116,10 +119,17 @@ describe('debitCredits', () => {
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' }]);
+ 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 });
+ ).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 () => {