Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(backlog): add work orders for LLM lanes, BNB testnet deploys, OKX chat bot, Telegram bots, and x402scan listing
nirholasda347f7647b4
diff --git a/ISSUES.md b/ISSUES.mdindex 360368551..d009550a7 100644--- a/ISSUES.md+++ b/ISSUES.md@@ -169,28 +169,7 @@ Found by the 2026-07-30 documentation audit, which read the handlers behindevery surface it documented. Only the production-affecting findings are listedhere; the code-quality items from that pass are not production issues.-9. **`/api/avatar/optimize?draco=1` is broken on the running image** (needs a- rebuild, not engineering). It returns `500 transcode_failed` with- `draco.createCompressedPrimitive is not a function`. This is dependency- drift in the deployed image, not a code bug, and the obvious diagnosis is- wrong: `buildTranscodeIo()` IS present in the deployed commit, and this- repo's pinned tree encodes Draco correctly (verified locally, 888,060 bytes- out). The image resolved an older `@gltf-transform` than the pinned `^4.4.0`,- whose Draco writer calls an encoder interface `[email protected]` does not- expose. Every other `optimize` parameter returns a real GLB in production.- Action: rebuild, and confirm the build installs from the lockfile rather- than resolving fresh. The related silent-expression defect is fixed in- code (2026-07-31): a render/expression request against a model lacking- the requested morph targets now reports itself via- `x-render-expression: applied|partial|none` (+ `x-render-expression-missing`)- on `/api/avatar/render`, and the MCP render tool names the missing- morphs; pinned by `tests/api/avatar-render-expression-report.test.js`.- Ships with the next deploy. (The oversized-`glbUrl` stall listed here is fixed: the 50 MB- cap is now counted while streaming and aborts the transfer, so a chunked- source with no `content-length` returns `413` instead of being buffered in- full, and an unresponsive source times out as `504` rather than holding the- request open. Covered by `tests/avatar-optimize-source-cap.test.js`.)-10. **Live R2 CORS does not match `scripts/set-r2-cors.mjs`** (owner action:+9. **Live R2 CORS does not match `scripts/set-r2-cors.mjs`** (owner action:one credential). The script sets `AllowedOrigins: ['*']` for GET/HEAD, butthe live policy still echoes only the old allowlist, so a third-party origingets no `access-control-allow-origin`. Re-running it removes the need for the@@ -206,11 +185,24 @@ here; the code-quality items from that pass are not production issues.----## Recently closed (2026-07-30; do not re-open without new evidence)+## Recently closed (do not re-open without new evidence)Kept briefly because each one was previously mis-stated on this list, and thewrong version is what a future reader would otherwise trust.+- **`/api/avatar/optimize?draco=1` (closed 2026-08-01).** It returned+ `500 transcode_failed` with `draco.createCompressedPrimitive is not a function`+ because the deployed image had resolved an older `@gltf-transform` than the+ pinned `^4.4.0`. This was always dependency drift in the image, never a code+ bug. The 2026-08-01 rebuild fixed it, verified live against production:+ `curl "https://three.ws/api/avatar/optimize?src=https://three.ws/avatars/cesium-man.glb&draco=1"`+ returns `200` with a 129,972-byte GLB stamped `glTF-Transform v4.4.0`. The two+ sibling defects filed under the same item also shipped: the silent-expression+ report (`x-render-expression` on `/api/avatar/render`, pinned by+ `tests/api/avatar-render-expression-report.test.js`) and the oversized-source+ stall (streaming 50 MB cap returning `413`/`504`, covered by+ `tests/avatar-optimize-source-cap.test.js`).+- **The autopilot spend default.** `POST /api/agents/:id/autopilot/run` read`body?.dry_run === true`, so a bare `POST {}` ran a REAL cycle while thesibling runner on the same wallet (`api/agents/wallet-intents.js`) readdiff --git a/api/_lib/x402/sponsor-runway.js b/api/_lib/x402/sponsor-runway.jsnew file mode 100644index 000000000..033b2f80f--- /dev/null+++ b/api/_lib/x402/sponsor-runway.js@@ -0,0 +1,283 @@+// @ts-check+// api/_lib/x402/sponsor-runway.js+//+// Sponsor fee-wallet RUNWAY: how many days of settling the fee payer can still+// afford, measured from what it actually spent, plus the alert that fires before+// it bites.+//+// Why this module exists+// ----------------------+// The sponsor wallet (X402_FEE_PAYER_SOLANA) pays the SOL fee on every platform+// settle. Below X402_SPONSOR_SOL_FLOOR_LAMPORTS the self-facilitator refuses to+// settle, and buildRequirements() then WITHDRAWS the Solana accept from every 402+// challenge (sponsorKnownBelowFloor(), api/_lib/x402-paid-endpoint.js). The+// outward symptom is not a clean outage: settlements collapse while rail faults+// stay flat, because the Solana-only ring never attempts a payment there is+// nothing to reject. The settle sensor names that cause (`sponsor_floor` in+// ops/x402-settle-health.js), but naming it AFTER the collapse is a post-mortem.+// The runway is the signal that precedes it, and until now it was rendered on a+// dashboard nobody watches at 3am and acted on by nothing.+//+// Two rules the numbers obey+// --------------------------+// 1. BURN IS MEASURED, NEVER REMEMBERED. It comes from `fee_lamports` over+// successful settles in `x402_self_facilitator_log` across a stated window.+// The folklore figure carried in old triage notes ("1 to 2 SOL/day") is off by+// roughly 10x against the measured 0.06 to 0.09 SOL/day (ISSUES.md item 6), and+// a funding ask sized from it would be wrong by an order of magnitude. Every+// consumer therefore carries the window alongside the number: a rate without+// its window is a rumour.+// 2. RUNWAY IS MEASURED TO THE FLOOR, NOT TO ZERO. Settling stops at the floor,+// so the operationally meaningful figure is (balance − floor) / burn. The+// to-zero figure is still reported (`runway_days`) because it is what the+// board has always shown and what a funding ask is sized against, but the+// STATUS and the alert key off `runway_days_to_floor`.+//+// Everything here except measureSponsorBurn() is pure, so the thresholds and the+// alert copy are unit-tested without a chain or a database+// (tests/x402-sponsor-runway.test.js).++import { LAMPORTS_PER_SOL } from './ring-floors.js';++/** Window the burn rate is measured over. Long enough to smooth a bursty ring. */+export const SPONSOR_BURN_WINDOW_DAYS = clampNumber(+ process.env.X402_SPONSOR_BURN_WINDOW_DAYS,+ 7,+ { min: 1, max: 90 },+);++/**+ * Days of runway below which the sponsor alert fires. Three days is the smallest+ * threshold that still leaves a weekend of slack: the reclaim self-heal runs on a+ * cron and an owner top-up needs a human, so a one-day warning is a warning+ * nobody can act on.+ */+export const SPONSOR_RUNWAY_ALERT_DAYS = clampNumber(+ process.env.X402_SPONSOR_RUNWAY_ALERT_DAYS,+ 3,+ { min: 0.25, max: 60 },+);++function clampNumber(raw, fallback, { min, max }) {+ const n = Number(raw);+ if (!Number.isFinite(n) || n <= 0) return fallback;+ return Math.min(max, Math.max(min, n));+}++function round(n, places) {+ const f = 10 ** places;+ return Math.round(n * f) / f;+}++/**+ * @typedef {{ address: string|null, sol: number|null, floor_sol: number|null,+ * spendable_sol: number|null, burn_sol_per_day: number|null,+ * burn_window_days: number, settles_in_window: number,+ * runway_days: number|null, runway_days_to_floor: number|null,+ * alert_days: number, status: 'ok'|'warn'|'critical'|'unknown',+ * reason: string, should_alert: boolean }} SponsorRunway+ */++/**+ * Turn a live sponsor balance and a measured burn rate into a runway verdict.+ * Pure — no clock, no DB, no RPC.+ *+ * Statuses:+ * `critical` the wallet is at or under its floor. Settlement is already being+ * refused and the Solana accept is already withdrawn.+ * `warn` runway to the floor is under `alertDays`. Still settling, but the+ * window to act is closing.+ * `ok` runway to the floor is at or above `alertDays`.+ * `unknown` no balance, or no measured burn in the window (a genuinely idle+ * rail divides by zero; that is not a fault and must never page).+ *+ * @param {object} input+ * @param {number|null} [input.sol] live sponsor balance, SOL+ * @param {number|null} [input.floorSol] facilitator hard floor, SOL+ * @param {number|null} [input.burnSolPerDay] measured burn, SOL/day+ * @param {number} [input.settles] successful settles in the window+ * @param {number} [input.windowDays] window the burn was measured over+ * @param {number} [input.alertDays] threshold for `warn`+ * @param {string|null} [input.address] sponsor address, carried for the alert+ * @returns {{ address: string|null, sol: number|null, floor_sol: number|null,+ * spendable_sol: number|null, burn_sol_per_day: number|null,+ * burn_window_days: number, settles_in_window: number,+ * runway_days: number|null, runway_days_to_floor: number|null,+ * alert_days: number, status: 'ok'|'warn'|'critical'|'unknown',+ * reason: string, should_alert: boolean }}+ */+export function computeSponsorRunway({+ sol = null,+ floorSol = null,+ burnSolPerDay = null,+ settles = 0,+ windowDays = SPONSOR_BURN_WINDOW_DAYS,+ alertDays = SPONSOR_RUNWAY_ALERT_DAYS,+ address = null,+} = {}) {+ const balance = Number.isFinite(Number(sol)) ? Number(sol) : null;+ const floor = Number.isFinite(Number(floorSol)) ? Number(floorSol) : null;+ const burn = Number.isFinite(Number(burnSolPerDay)) && Number(burnSolPerDay) > 0+ ? Number(burnSolPerDay)+ : null;+ const spendable = balance != null && floor != null ? round(balance - floor, 9) : null;++ const base = {+ address,+ sol: balance,+ floor_sol: floor,+ spendable_sol: spendable,+ burn_sol_per_day: burn == null ? null : round(burn, 6),+ burn_window_days: windowDays,+ settles_in_window: Number(settles) || 0,+ alert_days: alertDays,+ };++ if (balance == null) {+ return {+ ...base,+ runway_days: null,+ runway_days_to_floor: null,+ status: /** @type {const} */ ('unknown'),+ reason: 'sponsor balance unreadable',+ should_alert: false,+ };+ }++ // Already under the floor: the rail is down right now. This verdict does not+ // need a burn rate, and refusing to report it without one is exactly how a+ // live outage reads as `unknown`.+ if (floor != null && balance <= floor) {+ return {+ ...base,+ runway_days: burn == null ? null : round(balance / burn, 2),+ runway_days_to_floor: 0,+ status: /** @type {const} */ ('critical'),+ reason: 'at or below the settle floor',+ should_alert: true,+ };+ }++ if (burn == null) {+ return {+ ...base,+ runway_days: null,+ runway_days_to_floor: null,+ status: /** @type {const} */ ('unknown'),+ reason: `no settle fees recorded in the last ${windowDays} day(s)`,+ should_alert: false,+ };+ }++ const runwayDays = round(balance / burn, 2);+ const runwayToFloor = spendable == null ? runwayDays : round(Math.max(0, spendable) / burn, 2);+ const warn = runwayToFloor < alertDays;+ return {+ ...base,+ runway_days: runwayDays,+ runway_days_to_floor: runwayToFloor,+ status: warn ? /** @type {const} */ ('warn') : /** @type {const} */ ('ok'),+ reason: warn+ ? `under the ${alertDays}-day threshold`+ : `above the ${alertDays}-day threshold`,+ should_alert: warn,+ };+}++/**+ * Render the ops alert for a runway verdict. Separated from the send so the copy+ * is testable: the bridge-down alert shipped a template that interpolated its own+ * source text and logged `${detail}` instead of the numbers, which made the page+ * useless exactly when someone was reading it at speed. Every number below is a+ * field of `r`, and the test asserts the rendered string, not the template.+ *+ * @param {ReturnType<typeof computeSponsorRunway>} r+ * @returns {{ title: string, detail: string, signature: string, severity: 'critical'|'warn' }}+ */+export function formatSponsorRunwayAlert(r) {+ const critical = r.status === 'critical';+ const addr = r.address || 'unconfigured';+ const sol = r.sol == null ? 'unknown' : `${r.sol.toFixed(4)} SOL`;+ const floor = r.floor_sol == null ? 'unknown' : `${r.floor_sol.toFixed(4)} SOL`;+ const burn = r.burn_sol_per_day == null+ ? 'not measurable'+ : `${r.burn_sol_per_day.toFixed(4)} SOL/day`;+ const days = r.runway_days_to_floor == null ? 'unknown' : `${r.runway_days_to_floor.toFixed(1)} day(s)`;+ const toEmpty = r.runway_days == null ? 'unknown' : `${r.runway_days.toFixed(1)} day(s)`;+ const topUp = r.burn_sol_per_day == null+ ? null+ : round(r.burn_sol_per_day * 14 + (r.floor_sol || 0) - (r.sol || 0), 3);++ const title = critical+ ? `🚨 x402 sponsor UNDER its settle floor (${sol})`+ : `⛽ x402 sponsor runway ${days} left`;++ const lines = [+ `Sponsor ${addr} holds ${sol} against a ${floor} settle floor.`,+ `Measured burn ${burn} from ${r.settles_in_window} successful settle(s) over the last ` ++ `${r.burn_window_days} day(s) (fee_lamports in x402_self_facilitator_log, never a remembered constant).`,+ `Runway: ${days} above the floor, ${toEmpty} to empty. Alert threshold ${r.alert_days} day(s).`,+ critical+ ? 'Settlement is being REFUSED right now: sponsorKnownBelowFloor() withdraws the Solana accept from ' ++ 'every 402 challenge, so the ring has nothing payable and settles stop while rail faults stay flat.'+ : 'Below the floor the Solana accept is withdrawn from every 402 challenge and settles stop while rail ' ++ 'faults stay flat, so this will not look like a rail outage when it lands.',+ 'Free self-heal first: POST /api/cron/treasury-topup?dry=1 (Bearer CRON_SECRET) to see the reclaim plan, ' ++ 'then without ?dry=1 to apply. Owner SOL is needed only when every source reports at_or_below_floor.',+ topUp != null && topUp > 0+ ? `A top-up of about ${topUp.toFixed(3)} SOL buys 14 days at the measured burn. Send it to the SPONSOR or ` ++ 'the economy master, NEVER to per-agent wallets (that strands SOL and kills the rail).'+ : 'Top up the SPONSOR or the economy master, NEVER per-agent wallets (that strands SOL and kills the rail).',+ 'See docs/ops/payment-outcomes.md.',+ ];++ return {+ title,+ detail: lines.join(' '),+ // Coalesce on the wallet, not the numbers: the balance moves every read and+ // a balance-keyed signature would post a fresh alert every ten minutes.+ signature: `x402-sponsor-runway:${addr}`,+ severity: critical ? 'critical' : 'warn',+ };+}++/**+ * Measure the sponsor's burn from the settle ledger. The only impure function+ * here. Fail-soft: a missing DB or absent table resolves to an unmeasured result+ * rather than throwing into a health read.+ *+ * @param {any} sql tagged-template SQL client+ * @param {{ windowDays?: number }} [opts]+ * @returns {Promise<{ measured: boolean, settles: number, lamports: number,+ * window_days: number, burn_sol_per_day: number|null, error?: string }>}+ */+export async function measureSponsorBurn(sql, { windowDays = SPONSOR_BURN_WINDOW_DAYS } = {}) {+ const window_days = windowDays;+ try {+ const [row] = await sql`+ SELECT count(*)::int AS settles,+ coalesce(sum(fee_lamports), 0)::bigint AS lamports+ FROM x402_self_facilitator_log+ WHERE ts >= now() - ${`${window_days} days`}::interval+ AND action = 'settle' AND ok = true+ `;+ const lamports = Number(row?.lamports || 0);+ const settles = Number(row?.settles || 0);+ return {+ measured: true,+ settles,+ lamports,+ window_days,+ burn_sol_per_day: lamports > 0 ? round(lamports / window_days / LAMPORTS_PER_SOL, 6) : null,+ };+ } catch (err) {+ return {+ measured: false,+ settles: 0,+ lamports: 0,+ window_days,+ burn_sol_per_day: null,+ error: err?.message || 'settle log unreadable',+ };+ }+}diff --git a/api/_lib/x402/wallet-balance-monitor.js b/api/_lib/x402/wallet-balance-monitor.jsindex 89e224839..6324e36dc 100644--- a/api/_lib/x402/wallet-balance-monitor.js+++ b/api/_lib/x402/wallet-balance-monitor.js@@ -44,6 +44,13 @@ import { randomUUID } from 'node:crypto';import { fetchWithTimeout, loadSeedKeypair, USDC_MINT } from './pay.js';import { SPONSOR_SOL_FLOOR_LAMPORTS } from './self-facilitator.js';import { ringFloorSpecs, evaluateRingWallet, LAMPORTS_PER_SOL } from './ring-floors.js';+import {+ computeSponsorRunway,+ formatSponsorRunwayAlert,+ measureSponsorBurn,+ SPONSOR_BURN_WINDOW_DAYS,+ SPONSOR_RUNWAY_ALERT_DAYS,+} from './sponsor-runway.js';import { sql as defaultSql } from '../db.js';import { env } from '../env.js';import { sendOpsAlert } from '../alerts.js';@@ -218,7 +225,10 @@ function resolveRingAddresses() {* { readBalance } async (address) => { lamports, usdcAtomic } — override the* on-chain reader (used by tests to avoid RPC + spl-token)* { sendAlert } override sendOpsAlert (tests assert on it)- * @returns {Promise<{ configured: boolean, wallets: object[], breaches: string[] }>}+ * { sql } override the SQL client the burn measurement reads+ * { measureBurn } override the burn measurement entirely (tests, dry runs)+ * @returns {Promise<{ configured: boolean, wallets: object[], breaches: string[],+ * sponsorRunway: import('./sponsor-runway.js').SponsorRunway|null }>}*/export async function checkRingWallets(ctx = {}) {const redis = ctx.redis || null;@@ -226,7 +236,7 @@ export async function checkRingWallets(ctx = {}) {const addrs = resolveRingAddresses();const anyConfigured = Boolean(addrs.payer || addrs.treasury || addrs.sponsor);if (!anyConfigured) {- return { configured: false, wallets: [], breaches: [] };+ return { configured: false, wallets: [], breaches: [], sponsorRunway: null };}// On-chain balance reader — injectable for tests. Reads SOL always and USDC@@ -287,11 +297,47 @@ export async function checkRingWallets(ctx = {}) {}}+ // ── Sponsor RUNWAY ────────────────────────────────────────────────────────+ // The floor check above answers "is the fee wallet dead yet?". This answers+ // "how long until it is", which is the only version of the question anyone can+ // act on. Burn is measured from the settle ledger every run (see+ // sponsor-runway.js for why a remembered constant is not acceptable here), and+ // the runway is taken to the FACILITATOR hard floor rather than the ring's 1.5x+ // watch floor, because the hard floor is where settling actually stops.+ const sponsorEntry = wallets.find((w) => w.role === 'sponsor' && w.configured) || null;+ let sponsorRunway = null;+ if (sponsorEntry) {+ const sql = ctx.sql || (await import('../db.js')).sql;+ const burn = ctx.measureBurn+ ? await ctx.measureBurn({ windowDays: SPONSOR_BURN_WINDOW_DAYS })+ : await measureSponsorBurn(sql, { windowDays: SPONSOR_BURN_WINDOW_DAYS });+ sponsorRunway = computeSponsorRunway({+ address: sponsorEntry.address,+ sol: sponsorEntry.sol,+ floorSol: SPONSOR_SOL_FLOOR_LAMPORTS / LAMPORTS_PER_SOL,+ burnSolPerDay: burn.burn_sol_per_day,+ settles: burn.settles,+ windowDays: burn.window_days,+ alertDays: SPONSOR_RUNWAY_ALERT_DAYS,+ });+ if (sponsorRunway.should_alert) {+ const a = formatSponsorRunwayAlert(sponsorRunway);+ await sendAlert(a.title, a.detail, { signature: a.signature, severity: a.severity });+ }+ log.info('x402_sponsor_runway', {+ status: sponsorRunway.status,+ sol: sponsorRunway.sol,+ burn_sol_per_day: sponsorRunway.burn_sol_per_day,+ runway_days_to_floor: sponsorRunway.runway_days_to_floor,+ window_days: sponsorRunway.burn_window_days,+ });+ }+// Cheap consumer snapshot (dashboard / health) — mirrors the seed-wallet key.if (redis) {try {await redis.set(REDIS_RING_KEY, JSON.stringify({- ts: new Date().toISOString(), wallets, breaches,+ ts: new Date().toISOString(), wallets, breaches, sponsor_runway: sponsorRunway,}), { ex: ALERT_TTL_SECONDS });} catch (err) {log.warn('ring_balance_redis_write_failed', { message: err?.message });@@ -306,7 +352,7 @@ export async function checkRingWallets(ctx = {}) {});}- return { configured: true, wallets, breaches };+ return { configured: true, wallets, breaches, sponsorRunway };}/**@@ -410,9 +456,9 @@ export async function run(ctx = {}) {// Independent of the seed-wallet reading above: these are the closed-loop// ring's own wallets, watched on-chain against their role floors so the loop// never halts on a drained sponsor or an empty payer float. Never throws.- let ring = { configured: false, wallets: [], breaches: [] };+ let ring = { configured: false, wallets: [], breaches: [], sponsorRunway: null };try {- ring = await checkRingWallets({ redis });+ ring = await checkRingWallets({ redis, sql });} catch (err) {log.warn('ring_balance_check_failed', { message: err?.message });}diff --git a/data/changelog.json b/data/changelog.jsonindex 82b44b741..9d55792d3 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-01",+ "title": "Your own avatar can sign now, not just the two that shipped with the page",+ "summary": "Sign language ran on two fixed rigs. You could watch the platform's avatars sign, but never your own, which is backwards for a feature whose whole point is that an avatar communicates. The Avatar setting on the sign language page and the ASL alphabet page now has a third option that opens the avatar gallery: pick any avatar you own, or any public one, and it takes over the signing on the spot, keeping the speed and signing hand you already chose. Your pick is remembered and carries between both pages. It works because a sign is described anatomically, an index fingertip on the chin rather than a fixed coordinate, so the same vocabulary is measured onto your avatar's own skeleton, whatever its proportions. An avatar that genuinely cannot sign, a model with no skeleton or no finger bones, is not left standing there mute: the page says which avatar it is and puts the working one back.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/sign-language"+ },{"date": "2026-08-01","title": "Docs search now lands on the exact section you typed",diff --git a/docs/sign-language.md b/docs/sign-language.mdindex 42e7759e3..8ff3911df 100644--- a/docs/sign-language.md+++ b/docs/sign-language.md@@ -36,10 +36,24 @@ Three settings sit under the input, and all three are remembered on your next vi|---|---|---|| **Speed** | 0.5×, 0.75×, 1× | Signing is content, not decoration. Learners and many viewers want it slower, and slowing it must not mean losing it || **Signing hand** | Right-handed, Left-handed | About one signer in ten is left-dominant. The whole sign mirrors, not just the hand |-| **Avatar** | Classic, Expressive face | The classic rig is light and animates smoothly everywhere but carries no face blendshapes. The expressive rig shows the [non-manual markers](#the-face-is-grammar) a signed question needs |+| **Avatar** | Classic, Expressive face, your own | The classic rig is light and animates smoothly everywhere but carries no face blendshapes. The expressive rig shows the [non-manual markers](#the-face-is-grammar) a signed question needs. The third pill opens the avatar gallery: see [Sign with your own avatar](#sign-with-your-own-avatar) |If you have `prefers-reduced-motion` turned on, the page never auto-plays: signing starts only when you ask for it.+### Sign with your own avatar++The **Avatar** setting's third pill (`Your avatar…`) opens the three.ws avatar gallery: your own avatars and every public one. Pick one and it takes the hero's place immediately, keeping the speed and signing hand you already set.++It works because signs are anatomy, not coordinates. A sign says "index fingertip on the chin", and the solver measures your avatar's skeleton to find where its chin is, so the same entry lands correctly on a tall rig, a short one, long fingers or small hands. Nothing about the vocabulary is per-avatar, which is also why the [clips retarget](#how-it-works) instead of being rebuilt.++Once picked, the avatar is remembered on that device and is already on stage on [/asl-alphabet](https://three.ws/asl-alphabet) too. Click its pill again to swap to a different one; the built-in pills switch back without a trip through the gallery.++Some avatars cannot sign. A model with no skeleton, or a humanoid rig with no finger bones, has nothing to form a handshape with. Rather than leave a mute avatar on stage, the page says so and puts the rig that was working back:++> Nova can't sign: it has no usable skeleton. Classic is back on stage.++Anything created by the [Avatar Studio](https://three.ws/create) or by [/forge](https://three.ws/forge) with a humanoid rig signs. If your own model does not, run it through [rig repair](https://three.ws/rig-doctor) first.+## What it signs, and what it spellsA signer spells names and loanwords and *signs* everything else. The avatar does the same. These 32 words have a real sign, with a handshape, a place on the body, and a movement:@@ -93,7 +107,7 @@ Another 41 everyday spellings route to those same signs, so ordinary sentences w- **Practice reading it**, which is the harder half. The avatar spells a letter or a word, you type what you read, and your streak is kept on the device.- Deep links: `?letter=W` opens a letter, `?spell=HELLO` spells a word.-Speed, signing hand, and avatar are the same settings as /sign-language, stored under the same key, so a left-handed signer sets that once for both pages.+Speed, signing hand, and avatar are the same settings as /sign-language, stored under the same key, so a left-handed signer sets that once for both pages. That includes [your own avatar](#sign-with-your-own-avatar): pick it on either page and it forms the letters on both.## Fingerspell and export in the Animation Studio@@ -382,7 +396,7 @@ In ASL the face carries grammar: raised brows mark a yes/no question, furrowed bhead: { tilt: 3, nod: -3 } },```-Markers apply on any avatar shipping ARKit face shapes. An avatar without them still signs; it just loses the marker. On [/sign-language](https://three.ws/sign-language) the **Avatar** setting switches the hero between the light classic rig and an expressive rig whose face actually shows them.+Markers apply on any avatar shipping ARKit face shapes, including [one of your own](#sign-with-your-own-avatar). An avatar without them still signs; it just loses the marker. On [/sign-language](https://three.ws/sign-language) the **Avatar** setting switches the hero between the light classic rig and an expressive rig whose face actually shows them.## Motion capture with handsdiff --git a/pages/monitor.html b/pages/monitor.htmlindex 8f14804c6..0d410b79a 100644--- a/pages/monitor.html+++ b/pages/monitor.html@@ -93,6 +93,11 @@.mon-grid {display: grid; gap: 8px;grid-template-columns: repeat(12, minmax(0, 1fr));+ /* Capped rows are what makes this a board rather than a stack of+ pages: a panel with 30 rows scrolls inside itself instead of+ stretching its whole row, which would also hand the 3D spotlight+ an absurdly tall viewport and sink the avatar out of frame. */+ grid-auto-rows: minmax(220px, 460px);}.panel {background: var(--mon-surface); border: 1px solid var(--mon-border);@@ -133,6 +138,9 @@.span-8 { grid-column: span 8; }.span-12 { grid-column: span 12; }.tall { min-height: 430px; }+ @media (max-width: 680px) {+ .mon-grid { grid-auto-rows: minmax(220px, 380px); }+ }@media (max-width: 1180px) {.span-3, .span-4, .span-5 { grid-column: span 6; }.span-6, .span-8 { grid-column: span 12; }diff --git a/prompts/README.md b/prompts/README.mdindex 9b7d317f0..d29a73793 100644--- a/prompts/README.md+++ b/prompts/README.md@@ -13,6 +13,7 @@ Internal work-order packs for Claude agents. Each subdirectory is a campaign: a| Directory | What it is ||---|---|+| [backlog/](backlog/) | The open backlog, one work order per item: everything [../ISSUES.md](../ISSUES.md) and the retired campaign logs still carry, each with a measured starting state and a definition of done. || [bnb-chain/](bnb-chain/) | BNB Chain campaign: payments and gasless-rail work orders with a verified-facts context file. || [fable-audit/](fable-audit/) | One work order per finding from the 2026-07-11 deep audit, with severity, exact defect location, fix, and verification. || [gcp-credits/](gcp-credits/) | Prompt pack for the GCP credit program: GPU worker deploys, catalog and animation seeding. |diff --git a/prompts/backlog/00-INDEX.md b/prompts/backlog/00-INDEX.mdnew file mode 100644index 000000000..fb2523202--- /dev/null+++ b/prompts/backlog/00-INDEX.md@@ -0,0 +1,95 @@+# backlog/: the open work, one prompt per item++Every file here is a **self-contained work order**. Paste one into a fresh Claude+Code chat in this repo and run it to 100% without further input. Read this index+first; every work order assumes it.++The pack exists because the open items were scattered across [../../ISSUES.md](../../ISSUES.md),+retired campaign progress logs, and agent memory. A tracker line tells you a thing+is broken. A work order tells you how to finish it.++---++## Verification snapshot (2026-08-01, measured, not remembered)++Re-measure before you trust any number below. Commands are in each work order.++| Fact | Value | How it was read |+|---|---|---|+| Production commit | `6cc0370dc`, revision `three-ws-api-00353-tzp` | `curl -s https://three.ws/api/version` |+| Deploy gap | **none**; prod is at `main` HEAD | compared to `git rev-parse --short HEAD` |+| `x402_settle` | **down**, 25.9% (504/1948 paid attempts, 3h) | `curl -s https://three.ws/api/healthz` |+| Settle reject class | `fee_runway_exhausted` 85,331 vs `broadcast_failed` 562 | same, `x402.self_facilitator.settle.fail_reasons` |+| Solana RPC lanes | `1/3 paid lanes serving` | same, `subsystems[].name == rpc_lanes` |+| Forge generation | 100% (43/43 finished, 6h) | same |+| Fact-check benchmark | `ran: false` (honest empty state, never run) | `curl -s https://three.ws/api/fact-check-benchmark` |+| `optimize?draco=1` | **fixed**, 200 with a 129,972-byte GLB | `curl "https://three.ws/api/avatar/optimize?src=https://three.ws/avatars/cesium-man.glb&draco=1"` |+| Media CORS at the site edge | `access-control-allow-origin: *` | `curl -I -H 'Origin: https://example.org' https://three.ws/avatars/cesium-man.glb` |++Two of these overturn stale tracker text: the Draco transcode failure closed with+the 2026-08-01 rebuild, and there is no deploy gap right now, so "ships with the+next deploy" is no longer an excuse for anything in this pack.++---++## Run order++Nothing here is strictly sequential, but the money rail gates the platform's+observable health, so 01 to 03 come first.++| # | Work order | Blocked on | Owner action needed |+|---|---|---|---|+| 01 | [x402 settle: clear `fee_runway_exhausted`](01-x402-settle-runway.md) | nothing (config-only updates are pre-approved) | one `gcloud auth login` if auth is dead |+| 02 | [Solana RPC capacity and call-shape routing](02-solana-rpc-capacity.md) | nothing | plan top-up (optional, work order routes around it) |+| 03 | [Sponsor runway: measure, alert, self-heal](03-sponsor-runway-automation.md) | 01 lands first | ~1 SOL top-up (optional) |+| 04 | [Publish a real fact-check benchmark run](04-fact-check-benchmark-run.md) | one env var | set `INTERNAL_API_KEY` on the service |+| 05 | [R2 bucket CORS: verify, then fix at the origin](05-r2-bucket-cors.md) | one credential | mint an R2 admin token |+| 06 | [LLM lanes: kill the dead backstops, close the Claude gap](06-llm-lane-resilience.md) | nothing | Vertex Model Garden entitlement |+| 07 | [BNB testnet: deploy the two finished contracts](07-bnb-testnet-deploys.md) | one funded EOA | fund a throwaway testnet key |+| 08 | [OKX chat bot: move off the codespace](08-okx-chat-bot-always-on.md) | nothing | one email OTP login |+| 09 | [Telegram bots: durable hosting for both feeds](09-telegram-bots-durability.md) | nothing | none |+| 10 | [x402scan listing: finish the last three steps](10-x402scan-listing.md) | one PAT or one comment | classic PAT, or the owner comments |++---++## Shared rules (every work order obeys these)++1. **CLAUDE.md wins.** Read it before you start. The stop-and-ask gates are real:+ irreversible spends, `git push` and production deploys, other-coin commits,+ unrecoverable data deletion. Everything else: proceed, then report.+2. **Config-only `gcloud run services update` is pre-approved.** Use+ `--update-env-vars` (merges). Never `--set-env-vars` (replaces the whole set).+3. **Moving funds is not config.** Any transfer, reclaim, swap, or top-up needs an+ explicit owner yes with recipient and amount rendered first, even when the+ endpoint that does it is a cron you can already call.+4. **Measure before and after.** Every work order names the exact command that+ proves its claim. A fix without a re-read is not a fix.+5. **The gate.** `npm run gate` at the start and again before you claim done.+ `gate-after` must be no worse than `gate-before`.+6. **`npm run check:rules -- --paths <files you touched>`** before committing.+ Concurrent agents share this worktree, so stage explicit paths, never `-A`.+7. **User-visible change means a `data/changelog.json` entry** plus the docs layer+ that applies (see the Documentation section of CLAUDE.md).+8. **Log your outcome in [PROGRESS.md](PROGRESS.md)** when you finish or hand off.+ It is the only memory between chats.++## Commit gate applies to four of these++Work orders 07, 08, 09, and 10 reference crypto projects other than `$THREE`+(a second chain, a marketplace, a launchpad, a registry). Building and running+them is fine. **Committing a diff that names any of them requires explicit owner+approval first**, per CLAUDE.md. Each of those files repeats the warning at the+top. The other six touch only platform infrastructure and `$THREE`.++## The diagnosis reflex that keeps being right++Before debugging any production symptom, check three things in this order:++```sh+curl -s https://three.ws/api/version # is prod at main, or are you debugging old code?+curl -s https://three.ws/api/healthz # which subsystem is actually down, with counts+npm run db:status # are migrations pending behind you+```++More than one session in this repo has been spent debugging a fix that had already+shipped, or one that never had.diff --git a/prompts/backlog/01-x402-settle-runway.md b/prompts/backlog/01-x402-settle-runway.mdnew file mode 100644index 000000000..6de8693ab--- /dev/null+++ b/prompts/backlog/01-x402-settle-runway.md@@ -0,0 +1,134 @@+# 01. x402 settle: clear `fee_runway_exhausted` and hold the rate above 90%++Read [00-INDEX.md](00-INDEX.md) first. This is the highest-priority open item:+the only subsystem reporting **down** on the live healthz.++## What is wrong++`x402_settle` is at 25.9% (504 of 1948 paid attempts over 3 hours). The rail+faults look external (`http_502` x1180) but they are **our own facilitator+rejecting settles**: a facilitator settle rejection maps to 502 in+`api/x402-facilitator/[action].js` (respondError defaults to 502) and the ring+records it as `http_502` in `api/_lib/x402/pay.js`.++The reject reason is not ambiguous. Since boot the self-facilitator counters read:++```+settle: ok 4143, failed 85955+fail_reasons: fee_runway_exhausted 85331, broadcast_failed 562,+ signature_already_settled 56, idempotent_replay 4, not_confirmed 2+```++`fee_runway_exhausted` outnumbers every rail-shaped failure by more than 100x.+That reason comes from `assessWalletFeeBudget()` in+[api/_lib/x402/wallet-fee-governor.js](../../api/_lib/x402/wallet-fee-governor.js):+the wallet's daily fee budget is its spendable SOL (balance minus the hard floor)+divided by `X402_WALLET_FEE_RUNWAY_DAYS`, never below+`X402_WALLET_FEE_MIN_BUDGET_LAMPORTS`. A near-floor wallet gets a budget of about+0.01 SOL/day, which at roughly 6,000 to 8,000 lamports per settle is a few+thousand settles, so the budget exhausts hours after each 00:00 UTC reset and the+wave resumes.++**The upstream cause is a mis-tuned self-heal trigger, not an empty treasury.**+`ECONOMY_MASTER_OPERATING_SOL` in production sits *below* the master wallet+balance (code default is 0.15), so `master_deficit_sol` computes as 0, the+treasury-topup cron sees nothing to do, and reclaimable SOL sitting in agent+wallets is never pulled back to the wallet that pays fees.++This is a config and plumbing problem. Do not open with a funding request.++## Diagnose (do this first, do not skip)++```sh+# 1. The class, from outside, no credentials needed.+curl -s https://three.ws/api/healthz \+ | python3 -c "import json,sys; d=json.load(sys.stdin); print(json.dumps(d['x402']['self_facilitator'],indent=1))"++# 2. The other class. A hit here means a DIFFERENT fix (see the floor doctrine below).+npm run logs -- -s three-ws-api --grep "fee_wallet_below_floor" --since 1h+```++When you grep the service logs directly, use a **bare quoted string**, never+`textPayload:"..."`. This service logs structured JSON, so a `textPayload:` query+returns zero rows and exits 0, which reads as "class ruled out" while the cause is+live. That exact trap cost a full misdiagnosis:++```sh+gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" "fee_runway_exhausted"' \+ --freshness=6h --project aerial-vehicle-466722-p5+```++Then read the treasury engine's own view, which is read-only and safe:++```sh+curl -s -X POST "https://three.ws/api/cron/treasury-topup?dry=1" \+ -H "Authorization: Bearer $CRON_SECRET" # CRON_SECRET is in .env+```++Read **`spendable_sol`, not `master_sol`**. A reserve set close to the balance+mutes the whole engine while the balance still looks healthy.++## Fix++Three levers, in this order. The first two are config-only and pre-approved.++1. **Make the deficit real so reclaim self-heals.**+ ```sh+ gcloud run services update three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 \+ --update-env-vars ECONOMY_MASTER_OPERATING_SOL=0.3+ ```+ Verify the deficit turns positive in the `?dry=1` output above.++2. **Widen the daily budget from the same balance.**+ ```sh+ gcloud run services update three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 \+ --update-env-vars X402_WALLET_FEE_RUNWAY_DAYS=1+ ```+ This triples the budget without spending anything. Confirm the projection with+ `/economy-lab`, which runs the real governor client-side through+ [api/_lib/x402/runway-sim.js](../../api/_lib/x402/runway-sim.js), seeded from+ `GET /api/x402/runway-lab`. Model the change there before you apply it.++3. **Actually move the reclaimable SOL.** A non-dry+ `POST /api/cron/treasury-topup` moves funds between platform wallets. That is+ **stop-and-ask gate 1**: render the source wallet, destination, and amount, and+ get an explicit owner yes before firing it. Never top up per-agent wallets;+ that strands SOL and kills the rail.++## Do not do these++- Do not lower `X402_SPONSOR_SOL_FLOOR_LAMPORTS` to make the symptom go away. The+ floor is a different guard for a different failure (`fee_wallet_below_floor`),+ and the last time it tripped the shortfall was 0.000187 SOL: the refill leg was+ blocked, not the floor set wrong.+- Do not size a funding ask from remembered numbers. Measured burn is roughly+ 0.06 to 0.09 SOL/day from `fee_lamports` over successful settles. The+ "1 to 2 SOL/day" figure in old triage notes is off by about 10x.+- Do not attribute this wave to the RPC lanes. They explain `broadcast_failed`+ and `not_confirmed` (562 and 2), which is under 1% of the failures.++## Make it not recur++Config that drifts silently is how this class returns. Land at least one of:++- A healthz-level assertion that `ECONOMY_MASTER_OPERATING_SOL` is **above** the+ master balance's operating point, surfaced as a degraded reason string rather+ than a silent zero deficit.+- A test over the governor's config surface pinning the relationship between+ runway days, min budget, and the measured per-settle fee, so a future default+ change cannot re-create a sub-day budget unnoticed. Extend+ `tests/x402-wallet-fee-governor.test.js`.++## Definition of done++- [ ] `x402_settle` reports **ok** on `https://three.ws/api/healthz`, above 90%,+ read at least 3 hours after the change so a full budget window is covered.+- [ ] `fee_runway_exhausted` is no longer the top reject class.+- [ ] `POST /api/cron/treasury-topup?dry=1` shows a non-zero deficit and a+ non-zero reclaim plan.+- [ ] The recurrence guard is committed with a test, `npm run gate` green.+- [ ] `data/changelog.json` entry (tag: `fix`, `infra`) describing the recovery in+ holder-readable language.+- [ ] [PROGRESS.md](PROGRESS.md) updated with before/after settle rates.diff --git a/prompts/backlog/02-solana-rpc-capacity.md b/prompts/backlog/02-solana-rpc-capacity.mdnew file mode 100644index 000000000..c325cbf49--- /dev/null+++ b/prompts/backlog/02-solana-rpc-capacity.md@@ -0,0 +1,86 @@+# 02. Solana RPC: route by call shape, survive on 1 of 3 paid lanes++Read [00-INDEX.md](00-INDEX.md) first.++## What is wrong++Healthz reports `rpc_lanes: 1/3 paid lanes serving`. All three paid plans have hit+their caps at various points in the last two weeks (Helius `-32429 max usage+reached`, QuickNode `-32003 daily request limit reached`, both Alchemy apps+`429 Monthly capacity limit exceeded`, and the two Alchemy keys share one account+quota so the second is not a spare). Production currently runs primarily on free+lanes, which caps the achievable settle rate and produces `broadcast_failed`,+`Blockhash not found`, and malformed-response parse errors.++GCP credits cannot solve this: Blockchain Node Engine is Ethereum-only, so there+is no GCP-hosted Solana RPC to fail over to.++## The trap that makes every naive probe wrong++**Free lanes are not interchangeable, and `getBalance` cannot tell them apart.**+All the free lanes pass `getBalance`, `getLatestBlockhash`, and+`getSignatureStatuses`. On `getTokenAccountsByOwner` filtered by `programId`, the+call every token and USDC balance reader makes constantly:++- PublicNode returns **HTTP 403 `blocked parameter: params.1.programId`**+- Leo RPC returns **-32603**+- Only MagicBlock and `api.mainnet-beta.solana.com` serve it++That is why those two hold the top two slots today. Also: never probe with+`getHealth`. It is unmetered and returns ok on a fully exhausted endpoint.++## The work++1. **Build a capability matrix probe, not a liveness probe.** Write+ `scripts/probe-rpc-lanes.mjs` that runs every lane in `SOLANA_RPC_URL` plus+ `SOLANA_RPC_FALLBACK_URLS` against the **call shapes production actually+ makes**: `getBalance`, `getLatestBlockhash`, `getSignatureStatuses`,+ `getTokenAccountsByOwner` (programId filter), `getProgramAccounts`,+ `sendTransaction` (simulate only), `logsSubscribe` where WS is configured.+ Output a table of lane by method with the exact error code on refusal. Metered+ calls only.++2. **Make the router refuse to promote a lane that cannot serve the shape.** The+ failover chain in `api/_lib/solana/connection.js` currently ranks lanes without+ knowing which methods each supports, which is how a 403 on a `programId` filter+ got sized as an auth failure and parked a whole node for 30 minutes on ordinary+ traffic. Add per-method capability so a method-level refusal demotes the lane+ for that method only, with its own short cooldown, and never counts as an auth+ fault. Cover it with a test that asserts a `blocked parameter` 403 does not+ trigger the auth path.++3. **Cut call volume where it is free to cut.** The ring cadence knobs already+ exist. Audit which pipelines poll on a timer and could be event-driven or+ longer-interval without user-visible change. Land the reductions behind the+ existing config so they can be tuned without a deploy.++4. **Surface quota state honestly.** The exhausted paid lanes re-enter rotation on+ their own when quota resets (`QUOTA_COOLDOWN_MS` is 6h). Show, on the ops+ surface, which lanes are cooling down and when each is expected back, so the+ next reader does not re-diagnose "all lanes dead" during a normal cooldown.++## Verify++```sh+node scripts/probe-rpc-lanes.mjs # the new matrix, all lanes, all shapes+curl -s https://three.ws/api/healthz | python3 -c "import json,sys;print([s for s in json.load(sys.stdin)['subsystems']['subsystems'] if s['name']=='rpc_lanes'])"+npm run gate+```++## Owner action (optional, the work order does not wait on it)++Restoring one paid plan lifts the ceiling: free lanes cap the achievable settle+rate at roughly 82 to 95%. Top up or upgrade Helius, QuickNode, or Alchemy. State+the cost and the measured ceiling in your report and let the owner decide. Do not+block any of the four tasks above on it.++## Definition of done++- [ ] `scripts/probe-rpc-lanes.mjs` exists, runs offline-safe against live lanes,+ and prints a lane-by-method matrix with error codes.+- [ ] A method-level refusal no longer parks a lane as an auth failure; test+ committed.+- [ ] Ops surface shows per-lane quota cooldown with expected recovery time.+- [ ] `npm run gate` green, `npm run check:rules -- --paths <touched>` clean.+- [ ] `docs/ops/` documents the capability matrix and the `getHealth` trap.+- [ ] `data/changelog.json` entry (tag: `infra`).diff --git a/prompts/backlog/03-sponsor-runway-automation.md b/prompts/backlog/03-sponsor-runway-automation.mdnew file mode 100644index 000000000..74102eb0e--- /dev/null+++ b/prompts/backlog/03-sponsor-runway-automation.md@@ -0,0 +1,81 @@+# 03. Sponsor runway: measure it, alert on it, let it self-heal++Read [00-INDEX.md](00-INDEX.md) first. Run [01](01-x402-settle-runway.md) before+this one: a widened fee budget changes the burn this work order measures.++## What is wrong++The x402 sponsor wallet (`WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW`, the fee+payer for platform settles) runs close to its floor. The last measurement put it+at 0.0318 SOL against a 0.03 floor with a measured burn of 0.060 SOL/day: roughly+half a day of runway. The number is already computed and rendered by+`GET /api/ops/payment-outcomes` and the "Payment outcomes" panel on `/admin/ops`+(see [docs/ops/payment-outcomes.md](../../docs/ops/payment-outcomes.md)), but+nothing acts on it and nothing warns before it bites.++The failure mode this creates is not a clean outage. Below the floor,+`sponsorKnownBelowFloor()` makes `buildRequirements()` in+`api/_lib/x402-paid-endpoint.js` **withdraw the Solana accept from every 402+challenge**, so the Solana-only ring never attempts a payment and there is nothing+to reject. Settlements collapse while rail faults stay flat, which is the exact+opposite of what a reader expects, and the whole thing is invisible unless you+look at the accepts:++```sh+curl -s https://three.ws/api/x402/three-intel | jq '.accepts[].network'+# only eip155:8453 means the Solana accept has been withdrawn+```++## The work++1. **Publish the runway where a human will see it before it hurts.** The panel+ exists; the alert does not. Wire a threshold alert (days of runway below N,+ default 3) into the existing alerting path, with a message that names the+ wallet, the balance, the floor, the measured burn, and the computed days. Do+ not interpolate the template into its own source text: the bridge-down alert+ shipped exactly that bug and logged its own template instead of the numbers.++2. **Measure burn from data, never from memory.** Derive it from `fee_lamports`+ over successful settles across a 7-day window. Recorded burn has been quoted at+ 10x reality in past triage notes; the alert must carry its own measurement and+ the window it covers.++3. **Close the invisible-failure gap.** Add the withdrawn-Solana-accept condition+ as a first-class degraded reason on the settle sensor, distinct from a rail+ fault, so the outward symptom ("settlements fell, faults flat") maps to the+ right cause without a human remembering this document.++4. **Make reclaim observable.** `reclaimIdleAgentSol` writes **no ledger row on+ failure** (unlike the engine leg's `inflow_failed`), so a failing reclaim is+ invisible. Write a row on failure with the reason. The audit trail that proves+ whether the send loop ran at all is `usage_events` where `tool='economy_reclaim'`.++## Funding is an owner decision, not your call++At the measured burn, roughly 1 SOL covers about 16 days. Render the numbers and+ask; do not move funds yourself. Any transfer is stop-and-ask gate 1. **Never top+up per-agent wallets:** that strands SOL in wallets that do not pay fees and kills+the rail. Top-ups go to the master or the sponsor only.++## Verify++```sh+# Runway panel, authenticated (ops secret or admin session)+curl -s -H "x-ops-secret: $OPS_SECRET" https://three.ws/api/ops/payment-outcomes++# The accepts probe: both networks present means the Solana accept is live+curl -s https://three.ws/api/x402/three-intel | jq '.accepts[].network'++npm run gate+```++## Definition of done++- [ ] A runway alert fires below the configured threshold and its message contains+ real interpolated numbers, proven by a test over the formatter.+- [ ] Burn is computed from `fee_lamports` over a stated window and the window is+ shown next to the number.+- [ ] The settle sensor distinguishes `sponsor_floor` from `rail` causes.+- [ ] A failed agent reclaim writes a ledger row naming the reason.+- [ ] `docs/ops/payment-outcomes.md` updated to describe the alert and thresholds.+- [ ] `data/changelog.json` entry (tag: `infra`), `npm run gate` green.diff --git a/prompts/backlog/04-fact-check-benchmark-run.md b/prompts/backlog/04-fact-check-benchmark-run.mdnew file mode 100644index 000000000..b1fa6c9fc--- /dev/null+++ b/prompts/backlog/04-fact-check-benchmark-run.md@@ -0,0 +1,74 @@+# 04. Publish a real fact-check benchmark run++Read [00-INDEX.md](00-INDEX.md) first.++## Where this stands++Two of the three original problems are closed and verified live:++- Web search leads with Vertex-grounded Google Search. A live call to+ `POST /api/x402/fact-check` returned `supported` at 0.98 confidence with+ `vertexaisearch.cloud.google.com` grounding sources.+- `GET /api/fact-check-benchmark` returns `ran: false` instead of serving a stale+ run, so `/fact-check` renders its honest "not yet run" state rather than a+ misleading accuracy number. Confirmed again 2026-08-01.++What remains is the measurement itself. `scripts/fact-check-benchmark.mjs` targets+the **paid** endpoint `https://three.ws/api/x402/fact-check`, which answers a small+free allowance and then 402s, so a 40-claim run needs a bypass. Neither bypass+currently exists: there is no token carrying the `x402:bypass` OAuth scope, and+`INTERNAL_API_KEY` (the `x-api-key` service path in+[api/_lib/x402/access-control.js](../../api/_lib/x402/access-control.js)) is unset+both locally and on the `three-ws-api` Cloud Run service.++## The work++1. **Set the bypass.** Config-only, pre-approved:+ ```sh+ gcloud run services update three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 \+ --update-env-vars INTERNAL_API_KEY=<generated>+ ```+ Generate a strong value, store it where the other service secrets live, and+ pass it to the runner as `x-api-key`. `FACT_CHECK_BYPASS_TOKEN` is the+ alternative path if you prefer a scoped token over a service key; pick one and+ document which.++2. **Run it.**+ ```sh+ node scripts/fact-check-benchmark.mjs+ ```+ The runner refuses to publish any run with more than 10% errored claims, so a+ degraded run cannot poison the page. If it refuses, fix the errors rather than+ loosening the threshold: an errored claim usually means an LLM lane or the RPC+ chain is failing, which is work orders [02](02-solana-rpc-capacity.md) and+ [06](06-llm-lane-resilience.md), not this one.++3. **Verify the page tells the truth.** `/fact-check` must render the new run with+ its date, sample size, and methodology link. Check the empty state still works+ by reading the handler, not by deleting the run.++4. **Make it repeatable.** A benchmark that can only be run by the person who set+ the key rots. Document the exact invocation in `docs/`, and consider wiring it+ as a scheduled run so the published number carries a recent date. If you+ schedule it, add the cron to `vercel.json` (which `scripts/create-gcp-scheduler.mjs`+ reads) and note the cron count change against `npm run check:claude`.++## Verify++```sh+curl -s https://three.ws/api/fact-check-benchmark | python3 -m json.tool+curl -s -o /dev/null -w '%{http_code}\n' https://three.ws/fact-check+npm run gate+```++## Definition of done++- [ ] `GET /api/fact-check-benchmark` returns `ran: true` with a real report,+ sample size, and run timestamp.+- [ ] `/fact-check` renders that run in a browser with no console errors.+- [ ] The bypass mechanism (which one, where the key lives, how to rotate it) is+ documented in `docs/`.+- [ ] Errored-claim rate from the run is stated in [PROGRESS.md](PROGRESS.md).+- [ ] `data/changelog.json` entry (tag: `feature` or `improvement`) announcing the+ published accuracy number in plain language.diff --git a/prompts/backlog/05-r2-bucket-cors.md b/prompts/backlog/05-r2-bucket-cors.mdnew file mode 100644index 000000000..761d0b203--- /dev/null+++ b/prompts/backlog/05-r2-bucket-cors.md@@ -0,0 +1,80 @@+# 05. R2 bucket CORS: verify what is actually broken, then fix it at the origin++Read [00-INDEX.md](00-INDEX.md) first.++## Start by narrowing the claim++The tracker says third-party origins get no `access-control-allow-origin` on media+reads. That is **not true at the site edge**. Measured 2026-08-01:++```sh+curl -I -H "Origin: https://example.org" https://three.ws/avatars/cesium-man.glb+# HTTP/2 200+# access-control-allow-origin: *+# access-control-allow-methods: GET, HEAD, OPTIONS+```++So anything loading media through `three.ws` already works cross-origin. What is+unverified is the **bucket origin**: the public `r2.dev` host and the presigned+`PUT` path used by the upload flow. `scripts/set-r2-cors.mjs` sets+`AllowedOrigins: ['*']` for GET/HEAD plus a write rule for presigned uploads, and+the live bucket policy is believed to still echo an older allowlist.++**Your first task is a measurement, not a fix.** Determine, for each of these,+whether CORS is correct today:++1. Public bucket host (`r2.dev`) GET/HEAD from a foreign origin.+2. Presigned `PUT` preflight from a browser origin (the avatar upload modal).+3. The `three.ws` edge path (already known good, re-confirm).++If 1 and 2 pass, this item is closed: say so with the evidence, drop it from+[../../ISSUES.md](../../ISSUES.md), and stop.++## If the bucket policy is wrong++```sh+node scripts/set-r2-cors.mjs --get # show live policy+node scripts/set-r2-cors.mjs --dry-run # print the policy that would be pushed+node scripts/set-r2-cors.mjs # apply, idempotent+```++The blocker is credentials, not code. The only R2 token on this machine (`S3_*`+in `.env`, bucket `chatty-storage`) is **object-scoped** and returns+`403 AccessDenied` on `GetBucketCors` and `PutBucketCors`.++**Owner action, one credential:** mint an "Admin Read & Write" R2 token scoped to+the bucket, then put it in `.env.local` as `R2_ACCESS_KEY_ID` /+`R2_SECRET_ACCESS_KEY` and re-run the script. The script's `--get` path already+prints the exact steps instead of crashing.++## Two cleanups while you are in here++- **The script's own usage docs are wrong.** Its header says+ `vercel env pull .env` to get credentials. `vercel env pull` returns **empty**+ for secret-type vars (a documented trap in CLAUDE.md), and production env now+ lives on the Cloud Run service. Rewrite that comment block to name the real+ sources: `.env.local` for an R2 admin token, `gcloud run services describe` for+ runtime values.+- **Decide the fate of the `/api/glb` proxy.** A permissive bucket policy removes+ the need for it in client-side viewers, but it stays the right advice for+ notebooks and unusual dev ports. Do not delete it. Do update the docs that+ recommend it so a reader knows when each path applies.++## Verify++```sh+node scripts/set-r2-cors.mjs --get+curl -I -H "Origin: https://example.org" <public r2.dev object url>+npm run audit:docs+```++## Definition of done++- [ ] A measured table of the three surfaces above with pass/fail and headers.+- [ ] Either the bucket policy is correct and applied, or the item is closed with+ evidence and removed from ISSUES.md.+- [ ] `scripts/set-r2-cors.mjs` no longer instructs the reader to use+ `vercel env pull`.+- [ ] Docs recommending `/api/glb` state when the proxy is needed and when a+ direct fetch is fine.+- [ ] `npm run audit:docs` clean.diff --git a/prompts/backlog/06-llm-lane-resilience.md b/prompts/backlog/06-llm-lane-resilience.mdnew file mode 100644index 000000000..da4fbbc25--- /dev/null+++ b/prompts/backlog/06-llm-lane-resilience.md@@ -0,0 +1,99 @@+# 06. LLM lanes: retire the dead backstops, close the Claude gap, fix the metering lie++Read [00-INDEX.md](00-INDEX.md) first.++## What is wrong++Three separate defects wear one label ("LLM backstops are dead"). Treat them+separately.++**1. The paid backstops are unreachable.** `OPENAI_API_KEY` is set on the service+but the account returns `billing_not_active` 429s, so every OpenAI paid backstop is+out. The OpenRouter platform key burned its credit on paid-model routing. Traffic+survives on the free lanes (Groq, NIM) plus the Vertex Gemini credits anchor.++**2. The metering does not show it.** `llm-pricing` records OpenRouter spend as+**$0**, so the credit burn that killed the key was invisible right up until it was+gone. A cost lane that reports zero is worse than one that reports nothing.++**3. Claude reachability is split, and the docs describe the design instead of the+deployed state.** Verified against the live service:++- `/brain` (`api/brain/chat.js`) **does** reach Claude, through the OpenRouter+ mirrors (`anthropic/claude-*`), because `buildPrimary()` falls back to+ `spec.openrouterModel` when the native key is absent.+- Everything else (`api/chat.js`, `api/_lib/llm.js`, the embed proxy+ `api/llm/anthropic.js`) reaches Anthropic only via `api.anthropic.com` with+ `ANTHROPIC_API_KEY`, which is absent from `.env`, `.env.local`, and the+ `three-ws-api` service. Those paths get no Claude at all.+- Vertex Claude is off **and** unentitled: `VERTEX_CLAUDE_ENABLED=0`,+ `VERTEX_CLAUDE_PRIMARY=0`, and `rawPredict` returns 404 "project does not have+ access" for every Claude id in both `global` and `us-east5`. Flipping the flag+ alone would 404 every request.++## The work++1. **Make the free-lane path first-class, not a degradation.** Since paid lanes+ are out, the free chain carries production. Audit its failover for the same+ defect class found elsewhere in this repo: a fallback that only catches parse+ errors is bypassed exactly when the provider fails. Prove each rung is+ reachable with a test that simulates the rung above failing at the transport+ level, not just returning bad JSON.++2. **Fix the metering.** OpenRouter spend must be recorded at its real cost in+ `llm-pricing`. A lane whose cost cannot be determined should record `unknown`+ and raise, never `0`. Add a check that fails when any lane with non-zero+ traffic reports exactly zero cost over a window.++3. **Prepare the Claude key rollout so it is one command.** When+ `ANTHROPIC_API_KEY` arrives:+ ```sh+ gcloud run services update three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 --update-env-vars ANTHROPIC_API_KEY=...+ ```+ Never `--set-env-vars`. Fresh accounts start at **Tier 1** rate limits, so keep+ Claude off the x402 ring and any high-QPS lane; chat, brain, and reflection+ backstop traffic only until the tier grows. `claude-fable-5` requires 30-day+ data retention on the org and returns 400 under zero data retention.+ `claude-mythos-5` is deliberately kept out of the `/brain` menu.++4. **Correct the docs that describe Vertex Claude as the live credits-billed+ primary.** It is the design, not the deployed state. Any doc claiming Claude+ traffic bills to GCP credits today is wrong until Model Garden entitlement lands+ and `rawPredict` stops 404ing. Fix those lines in the same change.++5. **Flag, do not silently ship, the OpenRouter-mirror decision.** `api/chat.js`+ and `_lib/llm.js` have no OpenRouter mirror for Claude the way `/brain` does.+ Adding one would work immediately but draws real spend on the platform key for+ ordinary agent traffic. `isPaidModel()` in `_lib/chat-models.js` is the existing+ gate for exactly this shape. Implement it behind that gate, default off, and+ state the cost in your report.++## Owner actions (name them, do not wait on them)++- Reactivate OpenAI billing, or fund the OpenRouter key, or accept free-lane-only+ service.+- Accept Anthropic terms in Vertex Model Garden for project+ `aerial-vehicle-466722-p5` to bill Claude to the GCP credits. Then re-probe+ `rawPredict` and set `VERTEX_CLAUDE_ENABLED=1`; the Claude 5 ids are already in+ `VERTEX_ANTHROPIC_MODELS`.++## Verify++```sh+curl -s https://three.ws/api/healthz | python3 -c "import json,sys;print(json.load(sys.stdin)['subsystems']['degraded'])"+npm run gate+```++Probe each lane directly rather than trusting a config read: a set key is not a+working key, which is the entire lesson of defect 1.++## Definition of done++- [ ] Every free-lane rung proven reachable by a transport-level failure test.+- [ ] No lane with traffic reports exactly `$0`; a check fails if one does.+- [ ] The key-arrival path is a single documented command with rate-limit guidance.+- [ ] Every doc claiming Vertex Claude is live today is corrected.+- [ ] The OpenRouter-mirror option is implemented behind `isPaidModel()`, default+ off, with the cost stated.+- [ ] `npm run gate` green, `data/changelog.json` entry (tag: `infra`).diff --git a/prompts/backlog/07-bnb-testnet-deploys.md b/prompts/backlog/07-bnb-testnet-deploys.mdnew file mode 100644index 000000000..95b78e980--- /dev/null+++ b/prompts/backlog/07-bnb-testnet-deploys.md@@ -0,0 +1,76 @@+# 07. Deploy the two finished testnet contracts++Read [00-INDEX.md](00-INDEX.md) first.++> **Commit gate.** This work order and its deliverables reference a chain other+> than Solana. Per CLAUDE.md, any commit whose diff references a crypto project+> other than `$THREE` needs explicit owner approval before staging. Build freely;+> ask before committing.++## What is wrong++`GreenfieldVault` and `WorldMoves` are code-complete and dry-run verified, and+neither has ever been deployed publicly. Every proof in the retired campaign ran+against an anvil fork or a local instance because no funded deployer key exists:+`BNB_TESTNET_DEPLOYER_KEY` is absent from the shell env, the root `.env`, and+`contracts/.env`, and the public faucet is reCAPTCHA-gated so an agent cannot+self-serve it.++No code change is needed. The moment the addresses exist,+`/api/bnb/world-config` starts returning `deployed: true` for real visitors and+the sender, reader, and ghost paths light up as already proven.++Full history: [../bnb-chain/PROGRESS.md](../bnb-chain/PROGRESS.md). Deploy+addresses and script names: [../../contracts/DEPLOYMENTS.md](../../contracts/DEPLOYMENTS.md).++## The work++1. **Re-verify the dry runs still pass** against the current tree before asking+ for anything. A stale claim of "ready to deploy" is worse than no claim.+ ```sh+ cd contracts+ forge script script/DeployGreenfieldVault.s.sol+ forge script script/DeployWorldMoves.s.sol+ ```++2. **Owner action, one funded key.** Fund a throwaway EOA at+ `https://www.bnbchain.org/en/testnet-faucet` (reCAPTCHA, so a human must do+ it), then set `BNB_TESTNET_DEPLOYER_KEY` in `contracts/.env`.+ `GREENFIELD_VAULT_OPERATOR_KEY` falls back to the same key.++3. **Deploy, then wire the address.** Deploying to a public testnet spends funds+ from a key: render the network, the deployer address, and the estimated cost+ and get an explicit owner yes first (stop-and-ask gate 1).+ ```sh+ forge script script/DeployGreenfieldVault.s.sol --broadcast+ forge script script/DeployWorldMoves.s.sol --broadcast+ ```+ Then set `WORLD_MOVES_ADDRESS_TESTNET` on the service with+ `--update-env-vars` and confirm:+ ```sh+ curl -s https://three.ws/api/bnb/world-config | python3 -m json.tool+ ```++4. **Prove the read and write paths against the real deployment**, not the fork.+ Every path the campaign proved locally gets one live re-run, and the evidence+ goes in [PROGRESS.md](PROGRESS.md) with transaction hashes.++5. **Update `contracts/DEPLOYMENTS.md`** with the live addresses, the network, the+ deploy block, and the verification link.++## Keep Solana first++This is an additive testnet surface. It does not change where the platform lives.+Do not re-point, migrate, or de-prioritize any Solana infrastructure as part of+this work, and lead your report with the Solana position if you touch anything+shared.++## Definition of done++- [ ] Both dry runs re-verified green against the current tree.+- [ ] Both contracts deployed with transaction hashes recorded.+- [ ] `WORLD_MOVES_ADDRESS_TESTNET` set; `/api/bnb/world-config` returns+ `deployed: true` to an anonymous caller.+- [ ] Sender, reader, and ghost paths exercised against the live deployment.+- [ ] `contracts/DEPLOYMENTS.md` updated.+- [ ] Owner approval obtained before any commit containing this content.diff --git a/prompts/backlog/08-okx-chat-bot-always-on.md b/prompts/backlog/08-okx-chat-bot-always-on.mdnew file mode 100644index 000000000..ee6c76715--- /dev/null+++ b/prompts/backlog/08-okx-chat-bot-always-on.md@@ -0,0 +1,77 @@+# 08. OKX marketplace chat bot: get it off the codespace++Read [00-INDEX.md](00-INDEX.md) first.++> **Commit gate.** Content here references a marketplace outside the `$THREE`+> ecosystem. Get owner approval before committing anything that names it.++## What is wrong++Chat for the marketplace listing (agent #2632, "three.ws 3D Studio") is delivered+by a **local `okx-a2a` daemon plus a wallet session**, both outside this repo. It+goes offline on its own: a codespace rebuild wipes the CLIs and an idle nap kills+the daemon (observed alive at 21:09, stale pid by 03:13). The marketplace's own+tests then report "timeout, no delivery in 30 min", which is what got the listing+flagged offline once already.++Right now the daemon is staged with skills linked and the wallet session is logged+out.++## Immediate revive (do this first, it takes one command)++```sh+npm run okx:bot # scripts/okx-bot-revive.mjs+# exit 0 = online+# exit 2 = staged but logged out; it prints the login URL and the poll commands+```++The login needs a human: email OTP as `[email protected]`. Run this immediately+before any retest window. The wiring table is in+[../okx-ai/RUNBOOK.md](../okx-ai/RUNBOOK.md) section 0.5.++## The durable fix++A codespace cannot stay up on its own, so the real deliverable is an always-on+host. Build it:++1. **Containerize the daemon and its session state.** The daemon spawns the AI CLI+ in `~/.okx-agent-task/workspace`, and that directory's `CLAUDE.md` and+ `.claude/skills` are the **only** context chat answers have. It is empty by+ default, which means a naive host ships an agent that knows nothing about+ three.ws. Bake real context in.++2. **Do not replace the adapter with a one-shot responder.** The adapter does not+ read a reply out of the CLI's stdout; the AI subsession sends the reply itself+ via the `okx-a2a` CLI. A simple LLM responder would break the task lifecycle,+ not just chat. Custom hosts are supported through+ `OKX_A2A_AI_<PROVIDER>_COMMAND` and `..._EXEC_ARGS_JSON`, but whatever runs+ there must be genuinely agentic.++3. **Deploy to Cloud Run** in `aerial-vehicle-466722-p5`, pinning the+ `three-ws-build@` build service account and the `three-ws@` runtime service+ account (the default compute SA was deleted). Config-only env updates are+ pre-approved; the deploy itself is owner-gated, so prepare it to one command.++4. **Add a liveness signal.** The listing goes offline silently today. Expose a+ health endpoint and wire it into the same monitoring that watches the rest of+ the fleet, so "the bot is logged out" becomes an alert instead of a discovery.++5. **Session renewal.** The wallet session expires and needs a human OTP. Make the+ host detect an expired session and emit an actionable alert naming the exact+ command, rather than failing chat silently.++## Owner actions++- One email OTP login when the session is logged out.+- An AI-provider credential for the headless box, if the host cannot reuse this+ machine's.++## Definition of done++- [ ] `npm run okx:bot` exits 0, chat delivery verified end to end with a real+ inbound message.+- [ ] The daemon runs on an always-on host, not this codespace.+- [ ] Its workspace carries real three.ws context, verified by asking it a+ platform question and reading the answer.+- [ ] A health endpoint exists and an offline session raises an alert.+- [ ] [../okx-ai/PROGRESS.md](../okx-ai/PROGRESS.md) updated with the host details.diff --git a/prompts/backlog/09-telegram-bots-durability.md b/prompts/backlog/09-telegram-bots-durability.mdnew file mode 100644index 000000000..fd80cc50b--- /dev/null+++ b/prompts/backlog/09-telegram-bots-durability.md@@ -0,0 +1,81 @@+# 09. Telegram feed bots: durable hosting for both channels++Read [00-INDEX.md](00-INDEX.md) first.++> **Commit gate.** These bots track a launchpad other than `$THREE`. The code+> lives in a different repo (`nirholas/pump-fun-sdk`), so nothing here should land+> in three.ws without owner approval. Build and deploy freely; ask before+> committing anything that names the launchpad into this repo.++## What is wrong++Two live feeds run as **local processes in this codespace**, which means both die+on every rebuild and every idle nap:++| Feed | Directory | Port | State |+|---|---|---|---|+| Graduation and migration tracker | `/workspaces/pump-fun-sdk/channel-bot` | 3900 | live since 2026-08-01 20:46 UTC |+| All-claims firehose | `/workspaces/pump-fun-sdk/pumpkit/packages/allclaims` | 3901 | live since 2026-08-01 21:14 UTC |++Revive either with `npm start` from its directory. Durable hosting is one+`./deploy-cloudrun.sh` away for the first and unwritten for the second.++## The work++1. **Deploy both to Cloud Run.** `channel-bot/deploy-cloudrun.sh` exists and is the+ template. Write the equivalent for the all-claims package. Pin the+ `three-ws-build@` and `three-ws@` service accounts.++2. **Never use `--set-env-vars` for these.** Their config breaks the flag: the RPC+ URL list contains commas and the channel id can contain `@`, so neither the+ default separator nor the `^@^` alternate delimiter is safe. `deploy-cloudrun.sh`+ writes a YAML env file instead. Do the same for the second bot.++3. **Keep the bot identities separate.** Each feed has its own bot and its own+ channel. Reusing one token across both is unsupported and crosses the feeds.+ Put the **numeric `-100…` chat id** in `CHANNEL_ID`, never the handle: the+ shared `t.me` link is not always the username, and `getChat?chat_id=@handle`+ returns `chat not found` even with the bot already an admin. Recover the real+ id from `getUpdates?allowed_updates=["my_chat_member"]`, whose promotion event+ carries the chat id, username, and full admin rights object.++4. **Keep websockets, do not fall back to polling.** `getSignaturesForAddress`+ limit-20 per 30s against the program samples a handful of valid transactions+ per minute out of thousands, so events get missed entirely. The code only+ enables WS when `SOLANA_WS_URL` is explicitly set. `wss://rpc.magicblock.app/mainnet`+ carries the full firehose on the free tier (measured 4,545 events per 20s) and+ `wss://solana-rpc.publicnode.com` also works keyless. The three.ws Helius key is+ plan-exhausted and its WS handshakes 429 forever, so do not point these at it.++5. **Sync the stale decoders.** `@pumpkit/core` and `@pumpkit/channel` are March+ snapshots missing the post-2026-05-21 V2 layouts (quote-mint claims, lifetime+ claimed, fake social-claim detection). The current decoder lives in+ `channel-bot/src/claim-monitor.ts`. Either sync pumpkit from it or make every+ future bot copy from channel-bot, and write down which, because this trap has+ already been hit once.++6. **Process hygiene for whoever debugs this next.** The bot's cmdline is+ `node dist/index.js` (relative), so `pkill -f "channel-bot/dist/index.js"`+ silently matches nothing. Match on cwd via `/proc/<pid>/cwd`, and never kill a+ same-named process whose cwd is `/workspaces/three.ws`.++## Verify++```sh+curl -s localhost:3900/stats # or the Cloud Run URL once deployed+curl -s localhost:3901/stats+```++Baseline for the firehose once live: roughly 20 claims/min detected, digest every+60s, zero post failures. Flood control matters: Telegram caps around 20 posts/min+per channel, so large claims post individually and the rest batch into a digest,+with a sliding-window budget reserving one slot for the digest.++## Definition of done++- [ ] Both bots run on Cloud Run, surviving a codespace rebuild.+- [ ] Each uses its own token and numeric channel id, verified by a live post.+- [ ] WS mode confirmed active on both, with event rates recorded.+- [ ] The decoder sync decision is made, executed, and written down.+- [ ] A README in each bot directory documents deploy, env, and revival.+- [ ] Owner approval obtained before committing any of this into three.ws.diff --git a/prompts/backlog/10-x402scan-listing.md b/prompts/backlog/10-x402scan-listing.mdnew file mode 100644index 000000000..02c1dac2f--- /dev/null+++ b/prompts/backlog/10-x402scan-listing.md@@ -0,0 +1,70 @@+# 10. Finish the x402scan listing++Read [00-INDEX.md](00-INDEX.md) first.++> **Commit gate.** This touches a third-party registry. Any commit into three.ws+> whose diff names it needs owner approval first.++## Where this stands++The indexer lists settlements per facilitator address from a registry in the+upstream repo. Our self-hosted Solana facilitator settles from fee payer+`WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW`.++Done already:++- **PR #1032** (branch `add-three-ws-facilitator`) adds the three.ws facilitator.+ Open since 2026-07-17, mergeable, no reviews.+- The `discoveryConfig` addition was pushed to that branch on 2026-07-25.+- `GET https://three.ws/api/x402-facilitator/discovery/resources` is **live in+ production**: the facilitator-standard v1 catalog, projected in+ [api/_lib/x402/discovery-resources.js](../../api/_lib/x402/discovery-resources.js)+ over `buildX402DiscoveryDoc()` from [api/wk.js](../../api/wk.js).++Three steps remain.++## The work++1. **Re-verify the PR is still mergeable and the discovery endpoint still+ matches** what the PR claims. Six weeks of drift on either side breaks a+ listing quietly.+ ```sh+ gh pr view 1032 --repo <upstream> --json state,mergeable,reviews+ curl -s https://three.ws/api/x402-facilitator/discovery/resources | python3 -m json.tool | head -40+ ```++2. **Post the reviewer-verification comment on PR #1032.** This is the one step+ that has been blocked: the fine-grained PAT on this machine is scoped to+ `nirholas` repos and returns "Resource not accessible by personal access token"+ when commenting on a third-party repo. Two ways through, both owner-owned:+ a classic PAT with `public_repo`, or the owner comments directly. Prepare the+ comment text in full so it is a copy-paste for the owner, including the live+ discovery URL, the facilitator address, and the settlement evidence.++3. **Register the origin.** Sign in at the indexer with the platform wallet and+ register origin `https://three.ws`. Wallet sign-in is a signature, not a spend,+ but it binds an identity: render what is being signed and get an owner yes.++4. **Optional Base leg.** The code already routes Base settlement through CDP when+ `CDP_API_KEY_ID` and `CDP_API_KEY_SECRET` are set on Cloud Run. Creating those+ keys is an owner action. It is a nice-to-have: **never re-point Solana+ settlement to a third-party facilitator for visibility.** Listing is additive,+ Solana stays self-hosted, and an EVM-only directory is a footnote, not a goal.++## Verify++```sh+curl -s https://three.ws/api/x402-facilitator/discovery/resources \+ | python3 -c "import json,sys; d=json.load(sys.stdin); print(len(d.get('items', d.get('resources', []))), 'resources')"+npm run gate+```++## Definition of done++- [ ] PR #1032 state re-read and reported (merged, stale, or awaiting the comment).+- [ ] The verification comment is either posted or handed to the owner as+ copy-paste-ready text with every link resolved.+- [ ] Origin registration done or blocked with the exact blocker named.+- [ ] The discovery endpoint's live output matches what the PR registers.+- [ ] Solana settlement unchanged and still self-hosted. State this explicitly.+- [ ] [PROGRESS.md](PROGRESS.md) updated.diff --git a/prompts/backlog/PROGRESS.md b/prompts/backlog/PROGRESS.mdnew file mode 100644index 000000000..81bfa4651--- /dev/null+++ b/prompts/backlog/PROGRESS.md@@ -0,0 +1,29 @@+# backlog/ progress log++Cross-chat handoff. Append one block per work order attempt: what you measured,+what you changed, what is left, and who owns it. Newest at the bottom.++Format:++```+## <date>: <NN work-order name>+Measured: <the numbers you read, with the command>+Did: <what changed, with commit SHAs or env var names>+Left: <exactly what remains, and who owns it>+```++---++## 2026-08-01: pack created++Measured (see the snapshot table in [00-INDEX.md](00-INDEX.md)): prod at `6cc0370dc`+with no deploy gap, `x402_settle` down at 25.9% with `fee_runway_exhausted` at+85,331 rejects against 562 `broadcast_failed`, RPC lanes at 1/3 paid serving,+forge at 100%, fact-check benchmark unrun, Draco transcode fixed on the running+image, media CORS at the site edge already permissive.++Did: wrote ten work orders covering every open item carried by ISSUES.md and the+retired campaign logs. Dropped the Draco item from ISSUES.md against live+evidence rather than leaving a fixed item on the tracker.++Left: all ten work orders are unstarted.diff --git a/prompts/gcp-credits/05-catalog-animation-seeding.md b/prompts/gcp-credits/05-catalog-animation-seeding.mdindex 847339b27..f346dd88b 100644--- a/prompts/gcp-credits/05-catalog-animation-seeding.md+++ b/prompts/gcp-credits/05-catalog-animation-seeding.md@@ -1,99 +1,108 @@-# 05 — Bulk catalog & animation seeding on the self-hosted GPU fleet+# GCP-05: Bulk catalog and animation seeding on the self-hosted GPU fleet++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/gcp-credits/05-catalog-animation-seeding.md`".+It is complete on its own. Also read `prompts/gcp-credits/README.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question, a plan you did not execute, or "should I proceed?".+2. Blockers have pre-answered routes at the bottom. Use them and keep going.+3. CLAUDE.md hard rules: no mocks, no fake data, no TODO comments, no em-dash or en-dash+ characters. Stage explicit paths only; other agents share this worktree.+4. GPU spend on the self-hosted fleet is pre-approved (credits). Curation beats volume: a+ catalog of 5,000 junk meshes is worse than today's catalog.## Mission-Use the self-hosted GPU lanes (prompt 04) to mass-produce durable platform content that outlives-the credits: a much larger curated avatar catalog and a generative text→motion animation library-listed in the marketplace. This is the "credits → permanent assets" play. Quality-gate-everything — a catalog of 5,000 junk meshes is worse than today's catalog. Verify the browsing-surfaces hold up at the new scale.--## Prerequisites (stop and report if missing)--- Prompt 04 live in at least preview: `MODEL_TRELLIS_URL` etc. set, self-host lanes healthy,- `FORGE_SELFHOST_PRIMARY` available. text2motion service deployed (`GCP_TEXT2MOTION_URL`).--## Context (from prior code audit; re-verify)--- **Seed cron exists:** `api/cron/forge-seed-cron.js` runs ~per-minute, generates real avatars- on the free NIM draft lane, attributes each to a fresh OG-username user, publishes to the- avatars table. Prompt library: `api/_lib/seed-prompts.js` (200+ prompts).-- **Catalog surfaces:** `api/avatars/`, `/gallery`, `/dashboard/avatars`, curated GLBs in- `public/avatars/`.-- **Animation marketplace:** `api/marketplace/animations.js` (creator-listed clips) with x402- download route `api/x402/animation-download.js`. The Mixamo library (2,800+ retargeted clips)- is already live at `/animations`, served from R2 (`animations/library/clips/*.json` +- `manifest.json`, endpoint `GET /api/animations/library`).-- **Vision QA available:** `api/vision.js` / `api/_lib/vision.js` can describe a render — usable- as an automated quality gate.-- Assets land in R2 via `api/_lib/r2.js` (`forge/…` prefixes); thumbnails already part of the- pipeline.+Turn credits into durable platform content: a much larger curated avatar catalog and a+generated text-to-motion clip library, both quality-gated, both browsable at the new scale.++## Step 0: re-derive current state (trust nothing below)++```bash+gcloud run services list --region us-central1 --project aerial-vehicle-466722-p5 \+ --format="value(metadata.name,status.conditions[0].status)" | grep -E "trellis|text2motion|rig|hunyuan"+gcloud run services describe three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 --format=yaml | grep -E "GCP_TEXT2MOTION_URL|MODEL_TRELLIS_URL|FORGE_SELFHOST_PRIMARY|SEED_CRON_BATCH"+sed -n '1,40p' api/cron/forge-seed-cron.js+node -e "const d=require('./data/motion-prompts.json');console.log(Object.keys(d), d.prompts?.length)"+curl -s "https://three.ws/api/animations/library?limit=1" | head -20+psql "$DATABASE_URL" -c "select count(*) from avatars" 2>/dev/null || echo "use api/_lib/db helpers instead"+```++Known as of 2026-08-01: `data/motion-prompts.json` exists (the task-6 prompt library),+`api/cron/forge-seed-cron.js`, `api/_lib/seed-prompts.js`, `api/marketplace/animations.js`,+`api/x402/animation-download.js` and `api/animations/library.js` all exist;+`scripts/gcp/seed-avatars.mjs` does not. Verify each before deciding what is left.## Tasks-### A. Avatar catalog seeding (target: +3,000–5,000 *curated* avatars)--1. **Upgrade the seed cron** to use the self-hosted lane when `FORGE_SELFHOST_PRIMARY=1`- (it should inherit this from prompt 04's routing — verify, don't assume) and make its- cadence/batch size env-tunable (`SEED_CRON_BATCH`, default = current behavior).-2. **Expand `seed-prompts.js`** meaningfully: broaden coverage (professions, fantasy, sci-fi,- animals-as-props vs humanoids, styles) with attention to what makes good *rigged* avatars —- humanoid, front-facing, full-body. Keep prompts coin-neutral (no third-party crypto- references — commit gate).-3. **Automated quality gate before publish:** render thumbnail → `api/vision.js` check- (humanoid? complete body? not a blob?) + mesh sanity (vertex count bounds, has texture).- Failing assets are not published (keep them in R2 under a `forge/rejected/` prefix with the- reason, for tuning). Track accept rate.-4. **Rig the keepers:** run accepted avatars through UniRig so catalog entries are- animation-ready (that's the product bar — a catalog avatar that T-poses is half-built).- Verify a sample in the viewer with idle/walk clips playing.-5. **Batch runner:** a resumable script `scripts/gcp/seed-avatars.mjs` (checkpoint file, safe- to re-run, parallelism tuned to deployed GPU count) for bulk runs beyond the cron cadence.- Run it for a first real batch (e.g. 500) end to end before scaling up; report accept rate- and $/accepted-asset, then continue to target if quality holds.--### B. Animation library seeding (target: +500–1,000 curated motion clips)--6. **Prompt set for text2motion:** build a motion prompt library (locomotion variants, emotes,- dances, combat, idles, interactions) — a data file, not hardcoded.-7. **Batch generate → retarget → publish:** generate clips via `GCP_TEXT2MOTION_URL`, convert- to the canonical-skeleton clip JSON format the library uses (match the Mixamo library's- format exactly — inspect existing clips in R2/`public/animations/`), upload under a distinct- prefix (`animations/library/generated/…`), and update the manifest. QA gate: clip duration- sane, no NaN keyframes, plays on the default rig without foot-sliding disasters (spot-check- a sample visually in the viewer).-8. **Marketplace listing:** list the generated set in `api/marketplace/animations.js` under a- platform creator identity, priced consistently with existing listings, downloadable via the- existing x402 route. Free tier: consider adding a rotating subset to the free library —- owner-visible decision; implement the mechanism, note the policy choice in the report.--### C. Scale-proofing the surfaces--9. With the catalog at 5–10× size: verify `/gallery`, `/dashboard/avatars`, `/animations`, and- the marketplace list endpoints paginate (not fetch-all), thumbnails lazy-load, and API- responses stay bounded. Fix what breaks — pagination, indexes on the avatars table, manifest- sharding if the animation manifest gets huge. Test at realistic counts, not 10 items.--## Guardrails--- Curation over volume. If accept rate is poor, stop scaling and tune prompts/gates first;- report honestly.-- All batch spend is on self-host lanes (credits) — never let a bulk run fall through to- Replicate; assert the backend in the batch script and abort on fallthrough.-- Cron changes must be no-ops when the new env vars are unset.--## Acceptance criteria--- [ ] Seed cron upgraded + env-tunable; quality gate live with measured accept rate.-- [ ] First avatar batch published: rigged, animated in viewer, browsable in gallery.-- [ ] Generated motion clips live in library + marketplace; sample visually verified.-- [ ] Scale test at target counts passes on all four surfaces; fixes committed.-- [ ] $/accepted-asset and accept-rate numbers in `docs/gcp-credits.md`.-- [ ] `npm test` green; `git diff` reviewed (no `api/` esbuild-mangled files).--## Wrap-up--Changelog entries (users notice: bigger catalog, new generated-animations collection) —-plain language. Update docs (`docs/gcp-credits.md`; marketplace/animations docs if they exist).-Commit explicit paths, push `threews` (+ attempt `threeD`). Report: counts published, accept-rates, spend, and remaining headroom.+### A. Avatar catalog seeding (target: several thousand curated avatars)++1. **Point the seed cron at the self-hosted lane** when `FORGE_SELFHOST_PRIMARY=1`, and make+ cadence and batch size env-tunable (`SEED_CRON_BATCH`, default equals current behavior, so+ the change is a no-op when unset).+2. **Broaden `api/_lib/seed-prompts.js`**: professions, fantasy, sci-fi, styles, with attention+ to what makes a good rigged avatar (humanoid, front-facing, full-body). Keep every prompt+ coin-neutral: no crypto project other than $THREE, ever, in committed content.+3. **Automated quality gate before publish**: render a thumbnail, run it through the vision+ check (`api/vision.js` / `api/_lib/vision.js`) for humanoid, complete body, not a blob, plus+ mesh sanity (vertex-count bounds, has texture). Rejected assets stay in R2 under a+ `forge/rejected/` prefix with the reason, for tuning. Track and report accept rate.+4. **Rig the keepers** through the rig worker so catalog entries are animation-ready, and spot+ check a sample in the viewer with idle and walk clips playing. A catalog avatar that T-poses+ is half-built.+5. **Resumable batch runner** `scripts/gcp/seed-avatars.mjs`: checkpoint file, safe to re-run,+ parallelism tuned to the deployed GPU count, asserts the backend actually used and aborts on+ fallthrough to any paid third-party lane. Run one real batch of 500 end to end, report+ accept rate and cost per accepted asset, then continue only if quality holds.++### B. Animation library seeding (target: several hundred curated clips)++6. **Use `data/motion-prompts.json`** as the prompt library (extend it if categories are thin;+ it is data, never hardcoded).+7. **Generate, retarget, publish**: clips through `GCP_TEXT2MOTION_URL`, converted to the exact+ canonical-skeleton clip JSON the library already serves (inspect a real clip from+ `GET /api/animations/library` first and match it byte-shape), uploaded under a distinct+ prefix, manifest updated. Quality gate: sane duration, no NaN keyframes, plays on the default+ rig without foot-sliding. Spot-check a sample visually.+8. **List the generated set** in `api/marketplace/animations.js` under a platform creator+ identity, priced consistently with existing listings, downloadable through the existing x402+ route. Implement a rotating free subset mechanism and record the policy choice you made.++### C. Scale-proofing++9. At 5 to 10 times the current catalog size, verify `/gallery`, `/dashboard/avatars`,+ `/animations` and the marketplace list endpoints paginate rather than fetch-all, that+ thumbnails lazy-load, and that API responses stay bounded. Fix what breaks: pagination,+ indexes on the avatars table, manifest sharding. Test at realistic counts, not ten items.++## Definition of done++- [ ] Seed cron on the self-hosted lane and env-tunable; quality gate live with a measured+ accept rate.+- [ ] First avatar batch published: rigged, animated in the viewer, browsable in the gallery.+- [ ] Generated motion clips live in the library and the marketplace, sample visually verified.+- [ ] Scale test at target counts passes on all four surfaces, with the fixes committed.+- [ ] Cost per accepted asset and accept rate recorded in `docs/gcp-credits.md`.+- [ ] `npm test` green; `git diff` reviewed (no esbuild-mangled `api/` files: check `head -1`+ for `__defProp`).+- [ ] `data/changelog.json` entries for the bigger catalog and the new generated-animation+ collection, in plain language.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| A self-host lane is not Ready | Deploy or scale it (credits approved) using the bind-first pattern in `workers/model-trellis/main.py`. If a lane genuinely cannot come up, seed with the lanes that are up and report which one is missing. |+| Accept rate is poor | Stop scaling, tune prompts and gates first, and report the numbers honestly. Volume without curation fails this work order. |+| A batch would fall through to a paid third-party lane | Assert the backend in the batch script and abort. Never let bulk spend leave the credits. |+| Database migration needed for an index | `npm run db:status` first (it previews), then `npm run db:migrate` applies every pending migration immediately with no dry run. Read the pending list before running it. |+| Vision QA rejects everything | Inspect ten rejected thumbnails yourself before touching the threshold; a broken render pipeline looks exactly like a strict gate. |++## Report format++Counts published, accept rates, spend, cost per accepted asset, the four scale-test results,+and any single remaining owner action. No recap of this file.diff --git a/prompts/okx-ai/04-e2e-real-payment-test.md b/prompts/okx-ai/04-e2e-real-payment-test.mdindex 95a1b73a5..01ee83f1d 100644--- a/prompts/okx-ai/04-e2e-real-payment-test.md+++ b/prompts/okx-ai/04-e2e-real-payment-test.md@@ -1,90 +1,121 @@-# Work Order 04: End-to-end REAL payment test (we pay ourselves and verify settlement)+# OKX-04: End-to-end real payment test (we pay ourselves and verify settlement)-Read `prompts/okx-ai/00-CONTEXT.md`, `specs/okx-agent-payments.md`, and-`prompts/okx-ai/PROGRESS.md` (02 + 03 must be done). Read `/workspaces/three.ws/CLAUDE.md`.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/okx-ai/04-e2e-real-payment-test.md`".+Read `prompts/okx-ai/00-CONTEXT.md`, `prompts/okx-ai/RUNBOOK.md`, `specs/okx-agent-payments.md`+and `CLAUDE.md` first. Append your outcome to `prompts/okx-ai/PROGRESS.md` at the end.++## Binding operating clause++1. Finish 100% of everything that does not move money. Never end with a question about scope,+ design, or "should I proceed?".+2. **Two exceptions, and only two, where you stop and wait for the owner** (CLAUDE.md+ stop-and-ask gates, which override the autonomy rule):+ - spending real funds: render recipient, amount, token and chain, then wait for an explicit+ yes;+ - the email OTP for `[email protected]`, which only a human can read.+ Batch both into ONE message. Do everything else before you send it, and everything else that+ does not depend on it afterwards.+3. CLAUDE.md hard rules: no mocks, no simulated payments where a real one is specified, no TODO+ comments, no em-dash or en-dash characters. Stage explicit paths only.+4. Owner has pre-authorized OKX, X Layer, chain 196 and the marketplace fee token in commits+ for this work stream. Anything outside that scope still needs the gate.## Mission-Before resubmitting the listing, prove the whole machine with real money: act as an OKX-buyer agent, pay our own endpoint through the OKX Agent Payments Protocol on X Layer,-receive the artifact, and confirm settlement landed in our wallet on-chain. If OKX's-reviewer does exactly this and anything breaks, we get rejected again, so we do it first,-against production, and we do not stop at the first green result.--**The owner has explicitly committed to funding wallets for this. Compute what you need,-present the funding request, and wait, do not simulate instead.**--## Phase 1, Funding plan--1. Session preflight (00-CONTEXT). Identify the buyer wallet the CLI signs with- (`onchainos wallet status`; the TEE account's X Layer address, surface it).-2. Compute required funds and present ONE consolidated funding request to the owner:- - Fee token (`0x779d…3736`) for: cheapest service ($0.01), one mid service, the flagship- Text→Rigged Avatar ($0.50), ×2 for retries + margin.- - Gas (OKB on X Layer) if the chosen scheme requires buyer-side gas, the spec says- whether the facilitator sponsors gas (Permit2/EIP-3009 paths usually do); cite it.- - Exact addresses, chain, token contract, amounts. Wait for the owner's confirmation.-3. Verify funds arrived on-chain before proceeding (balance query via CLI or X Layer RPC).--## Phase 2, The gauntlet (production endpoints, real payments)--Run each numbered case; capture EVERYTHING (commands, headers, decoded challenges, tx-hashes) into `prompts/okx-ai/e2e-evidence/` as you go:--1. **Free lane**: health + catalog endpoints, correct, live data, no payment demanded.-2. **Cheapest paid service** ($0.01 Text→3D): unpaid call → 402; `onchainos payment pay`- → authorization header; replay → job runs → real GLB delivered. Download the GLB,- verify it parses and has geometry (not zero-byte, not an error JSON saved as .glb).-3. **Flagship** ($0.50 Text→Rigged Avatar): same flow; verify the GLB additionally contains- a skeleton + skinned mesh (bones present, skin weights non-empty, use the repo's- existing GLB inspection utils from the rig/retarget test suite).-4. **Settlement verification (the part everyone skips, do not skip):** for each payment,- find the settlement tx on X Layer (explorer/RPC), confirm the fee token transfer to OUR- payTo `0x75d0…cf69` for the exact advertised amount, and confirm any `PAYMENT-RESPONSE`- header matches the on-chain reality. Record tx hashes.-5. **Adversarial cases** (all against production, all must fail SAFELY, tool must not run,- error must be actionable, a fresh challenge must be offered where applicable):- a. Replay the same authorization header twice → second attempt rejected (no double-spend- of one payment, no free second job).- b. Tampered amount: pay the $0.01 challenge, attempt replay against the $0.50 service.- c. Expired/stale challenge (wait out `maxTimeoutSeconds` or mint a stale one) → rejected- with fresh challenge.- d. Garbage payment header → clean 4xx, no crash, no tool execution.-6. **Failure refund/no-charge semantics:** force a failing job (invalid input that passes- payment but fails generation, e.g. rig a non-humanoid prop through the humanoid-gated- lane). Verify our pay-only-on-success promise holds mechanically: either the payment is- not settled, or the documented refund path executes. Whatever the code actually does,- confirm it matches what our listing/docs PROMISE, a mismatch is a release blocker: fix- the code or fix the promise (and its docs) before proceeding.-7. **Legacy rails regression:** one paid call over an existing rail (Base/Solana per- existing test rig) still works.--## Phase 3, Fix loop--Any failure: diagnose root cause, fix (code per 02/03 conventions), redeploy, re-run the-FULL failed case plus cases 2 and 5a (regression floor). Repeat until the entire gauntlet-passes in one clean sequence. Log each iteration in PROGRESS.md, iterations are evidence-of rigor, not embarrassment.+Prove the whole machine with real money before resubmitting: act as an OKX buyer agent, pay our+own endpoint through the OKX Agent Payments Protocol on X Layer, receive the artifact, and+confirm settlement landed on-chain. If OKX's reviewer does this and anything breaks, we get+rejected again.++## Step 0: everything you can do before any money moves++```bash+export PATH="$HOME/.local/bin:$PATH"+onchainos --version && onchainos wallet status+curl -s https://three.ws/api/okx/3d/health | head -40+curl -s https://three.ws/api/okx/3d/catalog | head -60+curl -si -X POST https://three.ws/api/okx/3d/text-to-3d -H 'content-type: application/json' \+ -d '{"prompt":"a small ceramic teapot"}' | head -30 # expect HTTP 402+node scripts/okx-listing-payload.mjs | head -40+npx vitest run tests/api/okx-3d-services.test.js+```++Confirm: the free lane serves real data with no payment demanded, the 402 challenge carries an+`eip155:196` entry first, and the live catalog matches `api/_lib/okx-catalog.js` exactly (the+three-copy rule: module equals live equals submission). Any drift is a defect to fix now,+before spending anything.++## Phase 1: funding request (the one owner message)++1. Identify the buyer wallet the CLI signs with (`onchainos wallet status`) and read its+ current fee-token and gas balances on X Layer.+2. Compute exactly what the gauntlet needs: cheapest service, one mid service, the flagship+ avatar service, times two for retries and margin, plus gas if the chosen scheme requires+ buyer-side gas (cite the spec on whether the facilitator sponsors it).+3. Send ONE message containing: the exact amounts, the token contract, the chain, the receiving+ address, and the OTP request if login is also needed. Then wait. Do not simulate a payment+ instead.+4. When funds land, verify the balance on-chain before proceeding.++## Phase 2: the gauntlet (production endpoints, real payments)++Capture every command, header, decoded challenge and tx hash into `prompts/okx-ai/e2e-evidence/`+as you go. Run each case individually; no case is "covered by" another.++1. **Free lane**: health and catalog return correct live data, no payment demanded.+2. **Cheapest paid service**: unpaid call returns 402, `onchainos payment pay` returns an+ authorization header, the replay runs the job, a real GLB is delivered. Download it and+ verify it parses and has geometry (not a zero-byte file, not an error JSON saved as `.glb`).+3. **Flagship service**: same flow, and the GLB additionally contains a skeleton and skinned+ mesh (bones present, skin weights non-empty, verified programmatically with the repo's GLB+ inspection utilities, not assumed).+4. **Settlement verification, never skipped**: for each payment find the settlement tx on+ X Layer, confirm the fee-token transfer to our payTo wallet for the exact advertised amount,+ and confirm any `PAYMENT-RESPONSE` header matches on-chain reality. Record tx hashes.+5. **Adversarial cases**, all against production, all must fail safely with the tool not+ running and an actionable error:+ a. replay the same authorization header twice, second attempt rejected;+ b. pay the cheapest challenge, attempt to replay it against the flagship service;+ c. expired or stale challenge, rejected with a fresh challenge offered;+ d. garbage payment header, clean 4xx, no crash, no tool execution.+6. **Failure semantics**: force a failing job (input that passes payment but fails generation)+ and verify our pay-only-on-success promise holds mechanically. A mismatch between code and+ the promise in our listing or docs is a release blocker: fix the code or fix the promise.+7. **Legacy rails regression**: one paid call over an existing rail still works.++## Phase 3: fix loop++Any failure: root-cause it, fix it, redeploy, and re-run the failed case plus cases 2 and 5a as+the regression floor. Repeat until the entire gauntlet passes in one clean sequence. Log each+iteration in PROGRESS.md; iterations are evidence of rigor.## Definition of done-- [ ] Entire gauntlet green in one final clean run; evidence directory complete (add to- .gitignore if artifacts are large; summarize + link hashes in PROGRESS.md either way)-- [ ] At least 3 real settlements on X Layer with tx hashes recorded, amounts matching- advertised prices exactly-- [ ] All 4 adversarial cases fail safely (evidence captured)-- [ ] Pay-only-on-success promise verified mechanically or promise corrected everywhere-- [ ] Any code fixes committed per repo rules + pushed to `threews` (only push target)-- [ ] `docs/okx-marketplace.md` updated with a "verified behavior" section: settlement- timing, refund semantics, replay protection, stated from evidence, not intention-- [ ] `data/changelog.json`: only if user-visible behavior changed in the fix loop-- [ ] `prompts/okx-ai/PROGRESS.md` appended: gauntlet table (case → result → evidence- pointer), remaining risks, explicit GO/NO-GO for Work Order 05--## Anti-laziness gates--- No case is "covered by" another case. Run all of them, individually, against production.-- A 200 response is not success, success is the artifact being real (GLB parses, skeleton- present) AND the money being on-chain in our wallet.-- If you cannot verify settlement on-chain, the test is not passed. Find the tx or find- the bug.+- [ ] Entire gauntlet green in one final clean run, evidence directory complete.+- [ ] At least 3 real settlements on X Layer with tx hashes and amounts matching advertised+ prices exactly.+- [ ] All 4 adversarial cases fail safely, with captured evidence.+- [ ] Pay-only-on-success verified mechanically, or the promise corrected everywhere it appears.+- [ ] `docs/okx-marketplace.md` has a "verified behavior" section stating settlement timing,+ refund semantics and replay protection from evidence, not intention.+- [ ] `data/changelog.json` entry only if user-visible behavior changed in the fix loop.+- [ ] `prompts/okx-ai/PROGRESS.md` appended: case-by-case table, remaining risks, and an+ explicit GO or NO-GO for OKX-05.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| Wallet not logged in | `onchainos wallet login [email protected] --locale en_US`, then include the OTP request in your single owner message. Never guess a code. |+| The bot or daemon is offline | `npm run okx:bot` (`scripts/okx-bot-revive.mjs`) installs, starts and reports health. Exit 2 means staged but logged out. |+| A deploy is needed for a fix | Deploys are owner-gated. Prepare everything so the ship is one command, state it, and continue with what does not need it. |+| Catalog drift between module, live endpoint and listing | Fix the module first, then redeploy, then re-verify the live endpoint. The three copies must never diverge, even for one review cycle. |+| Settlement tx not found | The test is not passed. Find the tx or find the bug; never mark a 200 response as success. |+| `gcloud` auth dead | Not needed for this work order. Note it and carry on. |++## Report format++The gauntlet table (case, result, evidence pointer), the tx hashes, what you fixed in the loop,+the GO or NO-GO, and the single owner action if one remains.diff --git a/prompts/okx-ai/05-relisting-resubmission.md b/prompts/okx-ai/05-relisting-resubmission.mdindex 4769b1b15..8b2d2c2df 100644--- a/prompts/okx-ai/05-relisting-resubmission.md+++ b/prompts/okx-ai/05-relisting-resubmission.md@@ -1,81 +1,102 @@-# Work Order 05: Update agent #2632 and resubmit the listing+# OKX-05: Update agent #2632 and resubmit the listing-Read `prompts/okx-ai/00-CONTEXT.md` and `prompts/okx-ai/PROGRESS.md` end to end. **Hard-gate: 04 must show an explicit GO.** If there is no GO from 04, stop and say so. Read-`/workspaces/three.ws/CLAUDE.md`.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/okx-ai/05-relisting-resubmission.md`".+Read `prompts/okx-ai/00-CONTEXT.md`, all of `prompts/okx-ai/PROGRESS.md`,+`prompts/okx-ai/RUNBOOK.md` and `CLAUDE.md` first.++## Binding operating clause++1. Finish 100% of everything that is not an on-chain write or an OTP. Never end with a question+ about scope or design.+2. **Stop and wait only twice, batched into one message:** the email OTP for `[email protected]`,+ and the human confirmation of the diff card before the irreversible on-chain update. Both+ are CLAUDE.md gates that override the autonomy rule.+3. Never deactivate or delete agent #2632. All changes go through update plus re-activate; the+ ID, its wallet binding and its history are assets.+4. CLAUDE.md hard rules apply. Stage explicit paths only. No em-dash or en-dash characters.## Mission-Resubmit "three.ws 3D Studio" (#2632) with the decomposed service catalog and the now-real-OKX payment rail. This is the shot that reverses the rejection, treat the submission-itself as a product: every string a reviewer reads, every endpoint they probe, must be-exact. **Update the existing agent #2632, never deactivate, never re-create; the ID, its-wallet binding, and its history are assets.**--## Step 1, Pre-submission verification sweep--You are the reviewer for an hour. Against PRODUCTION:--1. Every endpoint in 03's final catalog: unpaid `curl -i` → OKX-valid 402 (or free content- for the free lane). Any drift from what 03/04 recorded = stop and fix first.-2. Diff every service's name/description/price/URL between the catalog module- (`api/_lib/okx-catalog.js`), the live free catalog endpoint, and the table you're about- to submit. Must be identical, three copies, zero drift.-3. Validate every description against OKX limits (2-part format; each part ≤200 chars in- East-Asian display width, CJK=2/ASCII=1; no links/tech-stack/example-prompts inside- service descriptions, those rules are in `.claude/skills/okx-agent-identity/references/invariants.md`,- which read in full before this step, along with `references/update.md`).-4. Agent-level profile: keep the existing description unless evidence says it hurt review- (do not silently rewrite identity copy); profile photo URL must be the existing OKX CDN- asset (`https://static.okx.com/cdn/.../49eab781-....png`), OKX rejects non-CDN links.--## Step 2, The update flow (interactive, human in the loop)--Session preflight per 00-CONTEXT (login = [email protected]; the human relays the OTP).--Follow the okx-agent-identity update flow **exactly** (`.claude/skills/okx-agent-identity/`-SKILL.md + references/update.md): fetch current state via `agent get-agents --agent-ids 2632`-first; build the `--service` JSON with per-service `operation` deltas (`create` for new-entries, `update`/`delete` with `id` for existing ones, pull existing service ids via-`agent service-list --agent-id 2632`); `serviceType: "A2MCP"`, `fee` as plain quoted number-string, `endpoint` = the per-service production URL; run the validate-listing QA; render the-diff card and get the human's explicit confirm before the write. The skill's confirmation-gates exist for a reason, an on-chain write is irreversible; do not shortcut them even-though this is "our own" agent.--## Step 3, Resubmit for review--Per the rejection email, resubmission happens through the agent flow: after the update-lands, run the activate step (`--preferred-language en-US` is required, see invariants.md-flag gotchas). Confirm the CLI/backend response shows the listing entered review-(approval status moves off "Listing rejected" to pending/in-review). Capture the exact-before/after approval-status values.--## Step 4, Record + set the watch--- PROGRESS.md: submitted catalog (verbatim), tx/CLI outputs, timestamp, approval status- after submission, and the daily check command:- `onchainos agent get-my-agents` (or `get-agents --agent-ids 2632`).-- `data/changelog.json`: no entry yet, the changelog entry ships when the listing is- APPROVED (07 owns that), not when submitted.+Resubmit "three.ws 3D Studio" (#2632) with the decomposed service catalog and the real OKX+payment rail. Treat the submission itself as a product: every string a reviewer reads and every+endpoint they probe must be exact.++## Step 0: gate check and full pre-submission sweep (all autonomous)++OKX-04 must have recorded an explicit GO in `PROGRESS.md`. If it did not, run the parts of+OKX-04 that need no funding, report exactly what is missing, and do not submit.++Then be the reviewer for an hour, against production:++```bash+curl -s https://three.ws/api/okx/3d/catalog | python3 -m json.tool | head -80+for s in $(node scripts/okx-listing-payload.mjs --slugs 2>/dev/null || echo text-to-3d); do+ echo "== $s"; curl -si -X POST "https://three.ws/api/okx/3d/$s" \+ -H 'content-type: application/json' -d '{}' | head -12+done+onchainos agent get-agents --agent-ids 2632+onchainos agent service-list --agent-id 2632+node scripts/okx-listing-payload.mjs --delta # feed it the service-list output per its usage+```++1. Every endpoint in the catalog returns an OKX-valid 402 unpaid (or free content for the free+ lane). Any drift from what OKX-04 recorded: stop and fix that first.+2. Three-way string diff: catalog module (`api/_lib/okx-catalog.js`), the live catalog endpoint,+ and the payload you are about to submit. Identical, zero drift.+3. Validate every description against OKX limits (two-part format, each part within 200 chars of+ East-Asian display width where CJK counts 2 and ASCII 1, no links, no tech stack, no example+ prompts inside service descriptions). The rules are in+ `.claude/skills/okx-agent-identity/references/invariants.md`; read it and `references/update.md`+ in full before this step.+4. Agent-level profile: keep the existing description unless evidence says it hurt review. The+ profile photo URL must be the existing OKX CDN asset; OKX rejects non-CDN links.++## Step 1: the update flow (the one owner interaction)++Session preflight per 00-CONTEXT. Follow the okx-agent-identity update flow exactly: fetch+current state with `agent get-agents --agent-ids 2632`, pull existing service ids with+`agent service-list --agent-id 2632`, build the `--service` JSON with per-service `operation`+deltas (`create` for new, `update`/`delete` with `id` for existing), `serviceType: "A2MCP"`,+`fee` as a plain quoted number string, `endpoint` as the per-service production URL. Run the+validate-listing QA. Render the diff card and get the human's explicit confirm before the write.+The confirmation gates exist because an on-chain write is irreversible; do not shortcut them+even though this is our own agent.++## Step 2: resubmit for review++After the update lands, run the activate step (`--preferred-language en-US` is required; see the+flag gotchas in invariants.md). Confirm the response shows the listing entered review (approval+status moves off "Listing rejected"). Capture the exact before and after approval-status values.++## Step 3: record and set the watch++- `PROGRESS.md`: the submitted catalog verbatim, CLI outputs, timestamp, approval status after+ submission, and the daily check command (`onchainos agent get-agents --agent-ids 2632`).+- No `data/changelog.json` entry yet. The changelog entry ships when the listing is approved;+ OKX-07 owns that.## Definition of done-- [ ] Pre-submission sweep: every catalog endpoint verified live + three-way string diff clean-- [ ] Update executed through the skill's full flow (pre-fetch, deltas by service id,- validate, human-confirmed diff card), no bypassed gates-- [ ] Resubmission confirmed: approval status captured before + after, listing is in review-- [ ] Nothing was deactivated/deleted; agent is still #2632-- [ ] PROGRESS.md appended with the full submission record-- [ ] Any incidental fixes committed (explicit paths) + pushed to `threews` (only push target)--## Anti-laziness gates--- Do not paraphrase, trim, or "improve" 03's final descriptions during entry, submit the- validated strings byte-for-byte. If entry-time validation rejects one, fix it in the- catalog module FIRST, redeploy, re-verify the free catalog endpoint, then resubmit, the- three copies must never diverge, even for one review cycle.-- If the CLI or backend errors mid-update, read- `.claude/skills/okx-agent-identity/references/errors.md` and resolve properly, never- retry-loop a business error, never leave the listing half-updated without recording- exactly which services landed.+- [ ] Pre-submission sweep done: every catalog endpoint verified live, three-way string diff+ clean.+- [ ] Update executed through the skill's full flow with no bypassed gates.+- [ ] Resubmission confirmed: approval status captured before and after, listing in review.+- [ ] Nothing deactivated or deleted; the agent is still #2632.+- [ ] `PROGRESS.md` appended with the full submission record.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| Not logged in | `onchainos wallet login [email protected] --locale en_US`, then request the OTP in your single owner message. |+| A validated string is rejected at entry time | Fix it in the catalog module first, redeploy, re-verify the live catalog endpoint, then resubmit. Never paraphrase at entry time; the three copies must never diverge. |+| The CLI or backend errors mid-update | Read `.claude/skills/okx-agent-identity/references/errors.md` and resolve properly. Never retry-loop a business error, and never leave the listing half-updated without recording exactly which services landed. |+| A deploy is required first | Deploys are owner-gated. Prepare it so the ship is one command and say so; do every non-deploy step now. |+| OKX-04 has no GO | Run every OKX-04 step that needs no funding, report the gap precisely, do not submit. |++## Report format++The three-way diff result, the submitted payload, before and after approval status, and the+single owner action if one remains.diff --git a/prompts/okx-ai/06-agent-pfp-wedge.md b/prompts/okx-ai/06-agent-pfp-wedge.mddeleted file mode 100644index 8d26ea076..000000000--- a/prompts/okx-ai/06-agent-pfp-wedge.md+++ /dev/null@@ -1,92 +0,0 @@-# Work Order 06: "Agent Identity Studio": 3D avatars for OKX.AI agents themselves--Read `prompts/okx-ai/00-CONTEXT.md`, `prompts/okx-ai/PROGRESS.md` (02 must be done; runs in-parallel with 04/05 otherwise), and `/workspaces/three.ws/CLAUDE.md`.--## Mission--The sharpest wedge on OKX.AI: **our customers are the other agents on the platform.** Every-registered agent has a `profilePicture`, and OKX's own identity flow includes a set-avatar-step (`onchainos agent upload` + update). Almost all current agents use flat generated-images. We sell them a distinctive 3D identity: text/brand brief → 3D avatar → posed,-lit, high-res renders sized for the OKX CDN avatar slot, plus the underlying rigged GLB-so their identity works anywhere in 3D (three.ws scenes, games, metaverse embeds).--This is a product, not a listing blurb. Build it end to end.--## Product definition--**Service: "Agent Identity Studio"**, one A2MCP service (joins the 03 catalog):--- **Input** (JSON): agent name, personality/brand description, style hints (optional),- reference image URL (optional).-- **Pipeline** (all capabilities already exist in this codebase, wire, don't rebuild):- 1. Brief → avatar prompt (existing prompt-shaping used by the avatar lane).- 2. `forge_avatar`-equivalent chain: mesh generation + humanoid auto-rig.- 3. Pose + frame: 3-5 distinct poses from the pose/clip library (rigged, retargeted),- rendered against clean backdrops, headshot crop for the PFP slot + full-body shot.- Rendering: check what already exists for server-side GLB rendering (screenshot workers,- preview pipelines) before adding anything new. Real renders of THEIR avatar, never- stock/template output.- 4. Deliverables: PNG set (PFP-cropped square + full-body), the rigged GLB, and a three.ws- viewer link (existing viewer URL pattern).-- **Price**: single flat price. Anchor: flagship avatar is $0.50 (03); this bundles- generation + rig + renders → $1.00–$2.00. Confirm unit cost math (GPU lane cost per call)- and record it; must clear cost with margin.-- **Job pattern**: async job + free status/preview polling, same contract as 03 services.--## Requirements--1. **Wired into the 03 architecture**: entry in the catalog module, own endpoint URL, own- OKX 402, tests alongside the other services, not a parallel one-off.-2. **Output quality is the product.** Generate at least 3 full pipeline runs from genuinely- different briefs (e.g. a finance data agent, a creative/art agent, a trading bot).- Inspect every deliverable: PFP reads clearly at 128×128 (OKX list size), full-body is- coherent, GLB is rigged (skeleton + skin weights verified with the repo's GLB inspection- utils). If any output is mediocre, fix the pipeline (prompt shaping, pose choice,- framing, lighting) and rerun. CLAUDE.md: "would someone screenshot this?" is the bar.-3. **Dogfood publicly**: run OUR agent's own brief through it and (via the okx-agent-identity- upload/update flow, with the human confirming the on-chain write) set #2632's profile- photo to the result. Our listing's face becomes our portfolio piece. Coordinate with 05:- if 05 hasn't submitted yet, hand the asset to 05 via PROGRESS.md instead of racing it- with a second update; if 05 already submitted and the listing is mid-review, do NOT touch- the listing, record the asset and defer the swap to 07 (post-approval).-4. **Showcase page on three.ws**: a gallery page (following existing page/site conventions +- design tokens) showing the demo identities, each with renders + embedded 3D viewer.- This is the `link` target for the changelog entry and the proof-of-quality URL the- listing description can reference. Register it in `data/pages.json`.--## Testing--- Full 03-style integration: unpaid 402 → pay (real, X Layer, per 04's runbook, request- funding if the wallet is dry) → job → all three deliverable types verified real.-- Edge cases: brief in Chinese (half the marketplace is zh, output must not degrade),- absurdly long brief (truncate/handle honestly), reference image 404 (clean actionable- error, no charge settled for undeliverable work, consistent with 04's verified- pay-only-on-success semantics).-- `npm test` green; preview deploy verified.--## Definition of done--- [ ] Service live on preview + production, in catalog module, tested paid E2E with a real- X Layer payment-- [ ] 3+ demo identities generated, inspected, iterated to genuinely excellent-- [ ] #2632's own avatar produced (set live, or handed off per requirement 3's coordination- rule, recorded either way)-- [ ] Showcase page live, in `data/pages.json`, linked from the site's nav per existing- conventions-- [ ] Docs: service section added to `docs/okx-marketplace.md` with a runnable example-- [ ] `data/changelog.json` entry (tags: `feature`; link: the showcase page path)-- [ ] PROGRESS.md appended (incl. unit-cost math, price decision, demo asset URLs, and the- catalog delta for 05/07 to fold into the listing)-- [ ] Self-reviewed diff; committed (explicit paths) + pushed to `threews` (only push target)--## Anti-laziness gates--- The demo briefs must be REAL runs of the full pipeline, saved with their inputs, not- cherry-picked outputs from manual retries you can't reproduce. If it took prompt-shaping- fixes to get quality reliably, those fixes live in code now.-- Renders at final crop size are the acceptance test, a beautiful 1024px render that turns- to mud at 128px fails requirement 2.-- "GLB is rigged" means you verified bones + weights programmatically, not that the- generator lane usually rigs things.diff --git a/prompts/okx-ai/07-final-audit-and-watch.md b/prompts/okx-ai/07-final-audit-and-watch.mdindex cb7f529c0..6f4507bc5 100644--- a/prompts/okx-ai/07-final-audit-and-watch.md+++ b/prompts/okx-ai/07-final-audit-and-watch.md@@ -1,86 +1,94 @@-# Work Order 07: Final audit, docs closure, approval watch, first-sale readiness+# OKX-07: Final audit, docs closure, approval watch, first-sale readiness++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/okx-ai/07-final-audit-and-watch.md`".+Read `prompts/okx-ai/00-CONTEXT.md`, all of `prompts/okx-ai/PROGRESS.md`,+`prompts/okx-ai/RUNBOOK.md` and `CLAUDE.md` first.++## Binding operating clause++1. Finish 100%. Trust nothing in `PROGRESS.md` until you have re-verified it yourself today.+ This work order exists precisely because earlier work orders claimed done.+2. Stop only for a real payment or an OTP, batched into one message, per the CLAUDE.md gates.+3. CLAUDE.md hard rules: no mocks, no TODO comments, no em-dash or en-dash characters. Stage+ explicit paths only.++## Part 1: independent adversarial audit (against production, today)++1. Unpaid 402 on the cheapest and the flagship endpoints, still spec-valid. Challenges drift+ when unrelated deploys touch shared code.+2. One real paid call end to end including the on-chain settlement check (OKX-04's runbook;+ request funding in your single owner message if the wallet is dry).+3. Replay protection spot check (OKX-04 case 5a) still rejects.+4. Free lane: health honest, catalog identical to the module and to the submitted listing+ (`onchainos agent service-list --agent-id 2632`).+5. Audit every file this work stream touched (derive the list from `PROGRESS.md` plus+ `git log --since` the stream's start) against the CLAUDE.md rules: no TODOs, no dead paths,+ no half-wired states, no scratch files, repo root clean. Fix what you find; do not file it.+6. `npm test` green; `npm run build:pages` green (it validates changelog entries);+ `npm run audit:docs` clean.++## Part 2: docs closure sweep++Read each as a zero-context outsider and verify it is correct, not merely present:++- [ ] `specs/okx-agent-payments.md` matches implemented reality, including every OKX-04 fix.+- [ ] `docs/okx-marketplace.md` documents every service and every curl example actually runs+ (run them), and is linked from `docs/start-here.md`.+- [ ] `docs/agent-identities.md` still matches the shipped Agent Identity Studio.+- [ ] `STRUCTURE.md` has rows for every surface this stream added.+- [ ] `data/pages.json` registers every new page.+- [ ] `data/changelog.json` entries are present and well-formed; any claim OKX-04 disproved is+ corrected. A doc that promises what the code does not do is a release blocker.+- [ ] Every new package or worker directory has a README.++## Part 3: approval watch and launch execution-Read `prompts/okx-ai/00-CONTEXT.md` and ALL of `prompts/okx-ai/PROGRESS.md`. 01–05 must be-complete (06 ideally too). Read `/workspaces/three.ws/CLAUDE.md`.--## Mission--Close the loop: independently audit everything shipped in this work stream, close every-docs/changelog gap, watch the resubmission through review, and make sure the day we get-approved is the day we're ready to sell, not the day we start scrambling.--## Part 1, Independent adversarial audit--Trust nothing in PROGRESS.md until re-verified. Sample-run the critical path yourself,-against production, TODAY:--1. Unpaid 402 on the cheapest and flagship endpoints → still spec-valid (challenges drift- when unrelated deploys touch shared code).-2. One real paid call end to end incl. on-chain settlement check (04's runbook; request- funding if dry).-3. Replay-protection spot check (04 case 5a), still rejects.-4. Free lane: health honest, catalog 1:1 with the catalog module and with the submitted- listing (pull the live listing: `onchainos agent service-list --agent-id 2632`).-5. Run the repo's completionist audit (the completionist agent) over every file this work- stream touched (derive from PROGRESS.md + `git log --since` the stream's start). Fix- everything it finds: no TODOs, no dead paths, no half-wired states, no stray scratch- files, repo root clean.-6. `npm test` green; `npm run build:pages` green (validates changelog entries).+1. Check current approval status (`onchainos agent get-agents --agent-ids 2632`).+2. `prompts/okx-ai/RUNBOOK.md` already exists. Verify every command in it by running it, fix+ whatever has drifted, and keep it good enough for a zero-context operator to run launch day+ alone.+3. **Execute the branch that matches reality, do not just document it:**+ - **Approved**: confirm activation, add the holder-visible `data/changelog.json` entry+ announcing the listing (tag `feature`), let the changelog cron deliver it (never run+ `changelog:push` manually, its file state double-posts against the cron's DB state), and+ verify the listing renders correctly to a buyer+ (`onchainos agent search --query "3D avatar rigging GLB"`).+ - **Rejected again**: capture the exact `approvalRemark` and email text, append it to+ `PROGRESS.md`, map the stated reason to the responsible work order, fix it, and re-run+ OKX-05.+ - **Still pending**: record the status and the date, and leave the watch command in the+ RUNBOOK. Do not idle-loop or leave a daemon running.+4. First-sale ops in the RUNBOOK: where sales and feedback show up (`soldCount`,+ `feedback-list`), how revenue arrives (the payTo wallet from OKX-04's evidence), where errors+ surface (`api/_mcp/payments.js`), and what to monitor daily.++## Part 4: memory++Write or update the agent-memory file for this work stream so future sessions do not re-derive+it: agent #2632 state, what shipped, where the evidence lives, the RUNBOOK location, the+current watch status. Update `MEMORY.md`.-## Part 2, Docs closure sweep+## Definition of done-Per CLAUDE.md's Documentation section, verify each layer exists and is CORRECT (read them-as a zero-context outsider):+- [ ] Part 1 audit run with evidence pasted; every finding fixed, not filed.+- [ ] Part 2 checklist green item by item, each verified rather than assumed.+- [ ] RUNBOOK commands all personally executed and corrected where they had drifted.+- [ ] Approval status checked and recorded, and the matching branch EXECUTED.+- [ ] Memory file written; `PROGRESS.md` closed out with the final state of the whole stream.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.-- [ ] `specs/okx-agent-payments.md`, matches implemented reality, incl. every 04 fix-- [ ] `docs/okx-marketplace.md`, every service documented, every curl example actually- runs (run them), linked from `docs/start-here.md`-- [ ] `STRUCTURE.md`, rows for the new surface(s)-- [ ] `data/pages.json`, any new pages registered (06's showcase)-- [ ] `data/changelog.json`, entries from 02/03/06 present + well-formed; stale claims- corrected (docs that promise what 04 disproved are release blockers)-- [ ] README(s) in any new package/worker directories created by this stream+## Never blocked (pre-answered)-## Part 3, Approval watch + launch runbook+| Blocker | Do this |+|---|---|+| The bot is offline | `npm run okx:bot`. Exit 0 means online, exit 2 means staged but logged out (login URL printed). |+| Wallet dry or logged out | One batched owner message with the funding table and the OTP request. Everything else proceeds without it. |+| A doc claim cannot be reproduced | That is a defect in the doc, not in your test. Correct the doc in the same session. |+| A deploy would be needed to fix a live string | Deploys are owner-gated. Prepare it as one command, say so, and finish everything else. |+| Approval has not moved in days | Record the status, keep the watch command in the RUNBOOK, and end the session. Never poll in a loop. |-1. Check current approval status (`onchainos agent get-agents --agent-ids 2632`).-2. Write `prompts/okx-ai/RUNBOOK.md`, the operator's guide for the human + future agents:- - Daily status-check one-liner; how to read approval states (approvalDisplayStatus map).- - **If APPROVED**: activation confirmation; the launch checklist, changelog entry- announcing the listing (tags: `feature`; this is THE holder-visible moment), Telegram- changelog push per repo process, set 06's avatar live if deferred, verify the listing- renders correctly in the marketplace UI (search for us as a buyer would:- `onchainos agent search --query "3D avatar rigging GLB"`, confirm we appear, cells- read well, prices right).- - **If REJECTED again**: capture the exact remark (`approvalRemark` + email), append to- PROGRESS.md, map the stated reason to the responsible work order, fix, re-run 05.- - **First-sale ops**: how to see sales/feedback (`soldCount`, `feedback-list`), how- revenue arrives (payTo wallet, from 04's evidence), where errors surface- (existing error-reporting path from api/_mcp/payments.js), what to monitor daily.-3. If the platform exposes review timing/messaging via the task/chat surface, note in the- RUNBOOK how the human triggers the check (the okx-task-watch flow exists for live- monitoring, reference it as the tool for the human to invoke, don't leave a daemon).--## Part 4, Memory--Write/update the agent-memory file for this work stream (per the memory system in the-system prompt) so future sessions don't re-derive: agent #2632 state, what shipped, where-evidence lives, RUNBOOK location, current watch status. Update `MEMORY.md` index.--## Definition of done+## Report format-- [ ] Part 1 audit run with evidence pasted; every finding fixed, not filed-- [ ] Part 2 checklist fully green (each item verified, not assumed)-- [ ] RUNBOOK.md written and complete enough that a zero-context operator could run launch- day from it alone-- [ ] Approval status checked and recorded; if already decided, the corresponding RUNBOOK- branch EXECUTED (launch checklist or rejection loop), not just written-- [ ] Memory file written; PROGRESS.md closed out with final state of the whole stream-- [ ] All changes committed (explicit paths) + pushed to `threews` (only push target)--## Anti-laziness gates--- This audit exists BECAUSE the prior work orders claimed done. Re-verify with fresh eyes;- every "verified in 04" claim you re-test and confirm, say so; every one you can't- reproduce is a defect to fix now.-- Do not write the RUNBOOK from imagination, every command in it must be one you ran.+Which PROGRESS claims you re-verified and which failed re-verification, the docs checklist+result, the executed launch branch, and the single owner action if one remains.diff --git a/prompts/quality-bar/03-gpu-fleet-scaleout.md b/prompts/quality-bar/03-gpu-fleet-scaleout.mdindex 9f1a5393d..188b787fe 100644--- a/prompts/quality-bar/03-gpu-fleet-scaleout.md+++ b/prompts/quality-bar/03-gpu-fleet-scaleout.md@@ -1,57 +1,95 @@-# 03: GPU fleet scale-out and cold-start UX+# QB-03: GPU fleet scale-out and cold-start honesty-Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/quality-bar/03-gpu-fleet-scaleout.md`".+It is complete on its own. Also read `prompts/quality-bar/_shared.md` and `CLAUDE.md`.-## Mission+## Binding operating clause-Turn the single-GPU-per-model setup into a fleet that absorbs real traffic with credits:-fix the broken TripoSG worker, deploy text2motion, raise scale ceilings once quota lands, and-make every remaining cold start honest and pleasant in the UI. Users should never stare at a-silent spinner because a GPU was cold.+1. Finish 100%. Never end this session with a question, a plan you did not execute, or+ "should I proceed?". The owner is not available and does not want to be asked.+2. Every blocker has a pre-answered route in "Never blocked" at the bottom. Use it, note what+ you did in the report, keep going. If one part is genuinely impossible in this environment,+ ship every other part in full and name the single missing action in the report.+3. CLAUDE.md hard rules apply: no mocks, no stubs, no TODO comments, no fake progress, no+ em-dash or en-dash characters anywhere you write. Stage explicit paths only; other agents+ share this worktree. Do not `git push` unless the owner's message asked for it.+4. GCP spend is pre-approved (credits). Never trade quality for cost.++## Step 0: re-derive current state (do this first, trust nothing below)++This file's claims rot. Measure before you plan:++```bash+gcloud run services list --region us-central1 --project aerial-vehicle-466722-p5 \+ --format="table(metadata.name, status.conditions[0].status)"+gcloud alpha quotas preferences list --project=aerial-vehicle-466722-p5 2>&1 | head -40+gcloud run services describe three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 --format=yaml \+ | grep -E "GCP_(TRIPOSG|TEXT2MOTION|HUNYUAN3D)_URL|MODEL_TRELLIS_URL"+curl -s "https://three.ws/api/forge?health" | head -40+```++As of 2026-08-01, `model-triposg`, `model-text2motion`, `model-trellis`, `model-triposr`,+`model-hunyuan3d` and `model-rig` were all Ready, so the original work order's "fix TripoSG"+and "deploy text2motion" tasks are shipped. Confirm that yourself, record the evidence, and+spend the session on what is still open.## Tasks-1. **Quota watch, then scale.** Poll `gcloud alpha quotas preferences list- --project=aerial-vehicle-466722-p5` until `NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion`- grantedValue rises above 3 (increase to 16 filed 07-16). Then: `model-trellis` maxScale 3- (keep min 1), `model-hunyuan3d` min 1 / max 2 (after prompt 02 lands it), `unirig` max 2,- `model-triposr` min 0 / max 2. Verify each update leaves the service Ready. If the grant is- denied or stalls for the whole session, file a fresh preference at a smaller ask (8) and- document; do everything else regardless.-2. **Fix model-triposg.** It fails Cloud Run health checks (container never binds 8080 in time;- the swarm fixed the CUDA build in 827e2f5c4, so the remaining issue is startup shape). Apply- the standard pattern the other workers use (read `workers/model-trellis/main.py`): bind the- port and return healthz immediately, load weights lazily in a background thread, report- `loading` status until ready, and set `--timeout=600` plus a generous startup probe on the- service. Rebuild, deploy to Ready, prove a generation through it, then wire `GCP_TRIPOSG_URL`.-3. **Deploy model-text2motion** (`workers/model-text2motion/`) the same way and set- `GCP_TEXT2MOTION_URL`. Prove one text→motion clip end to end and note where the product- consumes it (animation library / `src/animation-retarget.js` consumers).-4. **Cold-start honesty in the UI.** `api/_lib/forge-lane-health.js` already computes cold-start- ETA. Make sure `/forge` (and every surface that polls a generation: `/ar`, MCP tool- responses, agent screens) surfaces a real state: "GPU waking up, ~90s" with elapsed/remaining,- then live stage labels (queued / shape / texture / finishing). No fake progress bars, real- stages only. Skeleton previews over spinners.-5. **Keep-warm strategy.** With min-instances set, add a Cloud Scheduler ping only where- min-instances is deliberately 0 (triposr, text2motion): a `*/10` healthz touch during peak- hours (14:00-04:00 UTC) so first users rarely hit full cold starts. Crons are Cloud- Scheduler jobs (NOT GitHub Actions); follow an existing job's shape in the runbook.-6. **Load test.** Fire 10 concurrent real generations through the router (mixed tiers) and- record queue behavior, failover events, and p50/p95 completion. Fix anything that dropped a- job silently; `api/_lib/forge-scale.js` owns concurrency limits.+1. **Scale ceilings.** Read the granted L4 quota+ (`NvidiaL4GpuAllocNoZonalRedundancyPerProjectRegion`). Within the grant, set+ `model-trellis` min 1 / max 3, `model-hunyuan3d` min 1 / max 2, `model-rig` max 2,+ `model-triposr` min 0 / max 2. Verify each service stays Ready after the update+ (`gcloud run services describe <name> --region us-central1 --format="value(status.conditions[0].status)"`).+ If the grant is smaller than the plan needs, scale to what fits, file a fresh preference+ at a smaller ask, and record both.+2. **Cold-start honesty in every polling surface.** `api/_lib/forge-lane-health.js` already+ computes a cold-start ETA. Every surface that polls a generation must render a real state:+ which lane, "GPU waking up, about Ns" with elapsed and remaining, then live stage labels+ (queued, shape, texture, finishing). Surfaces to check and fix: `/forge`+ (`pages/forge.html`, `src/forge*.js`), `/create`, MCP tool responses in `api/_mcp3d/` and+ `api/_mcp-studio/`, and any agent screen showing generation progress. Skeletons, never+ spinners. No fake progress: every number comes from the API response.+3. **Keep-warm only where minScale is 0.** For each such worker add a Cloud Scheduler healthz+ ping during peak hours (14:00 to 04:00 UTC, `*/10`). Crons are Cloud Scheduler jobs synced+ from `vercel.json`'s `crons` array by `scripts/create-gcp-scheduler.mjs`; follow an existing+ job's shape and `docs/ops/gcp-production.md`. Never propose GitHub Actions.+4. **Load test through the router, not the workers.** Fire 10 concurrent real generations at+ `POST https://three.ws/api/forge` across mixed tiers, poll each to a finished GLB, and+ record queue behavior, failover events, p50 and p95 completion. A job that dies silently is+ a defect: fix it (`api/_lib/forge-scale.js` owns concurrency limits) and re-run.+5. **Prove a lane, do not assume it.** A lane counts as live only when a real prompt returned a+ real GLB through `/api/forge` and that GLB parses with geometry. Direct worker curl does not+ count. Save the returned URLs in the report.## Definition of done-- TripoSG and text2motion Ready and proven through the router with saved outputs.-- Scale ceilings raised per quota (or the denial documented with the retry filed).-- Every generation surface shows real stage/ETA states at 320/768/1440 widths.-- Load test numbers in the report; changelog entry for the user-visible speed/reliability gain.+- [ ] Scale ceilings applied within quota (or a smaller-ask request filed and recorded); every+ touched service still Ready.+- [ ] Cold-start and stage states render real data on `/forge` at 320, 768 and 1440 px,+ verified in a real browser via `npm run dev`, zero console errors from your code.+- [ ] Keep-warm scheduler jobs exist for every minScale=0 GPU worker, listed in the report.+- [ ] Load-test table (lane, tier, p50, p95, failovers, dropped jobs) with zero silent drops+ after your fixes.+- [ ] `npm test` green (never pipe it through `tail`, that masks the exit code).+- [ ] `data/changelog.json` entry for the visible speed and reliability gain, holder language,+ validated by `npm run build:pages`.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| `gcloud` auth dead (`invalid_rapt`) | It is the sperax.io Workspace reauth policy, not token expiry. Do every non-gcloud task in full, put the exact gcloud commands in the report as ready-to-run one-liners, and note that one `gcloud auth login` clears them. |+| Quota stuck reconciling | Proceed with everything else; the scale-up commands go in the report. |+| Worker weights missing | Stage from `gs://three-ws-model-weights` or the worker README's source. Staging weights is part of the task. |+| A worker will not bind in time | Use the bind-first plus background-load pattern from `workers/model-trellis/main.py`, plus `--timeout=600` and a generous startup probe. |+| Scheduler job needs a service account | Use the `three-ws@` runtime SA pattern from `docs/ops/gcp-production.md`. |+| A third-party lane is down | Every lane has a failover chain in `api/forge.js`. Use it; adding a missing rung is part of the task. |-## Anticipated blockers, pre-answered+## Report format-- Quota stuck in reconciling all session: proceed with everything else; the scale-up commands- go in the report as ready-to-run one-liners.-- TripoSG weights missing from `three-ws-model-weights`: fetch the official release weights and- stage them (record source URL + size).-- Scheduler job creation needs a service account: use the existing `three-ws@` runtime SA- pattern from `docs/ops/gcp-production.md`.+What shipped, what was already shipped before you started plus the evidence that proved it,+the load-test table, every command that changed cloud state, and the single owner action if one+remains. No recap of this file.diff --git a/prompts/quality-bar/04-pbr-texture-material-realism.md b/prompts/quality-bar/04-pbr-texture-material-realism.mdindex 99557474d..8a214d2f7 100644--- a/prompts/quality-bar/04-pbr-texture-material-realism.md+++ b/prompts/quality-bar/04-pbr-texture-material-realism.md@@ -1,64 +1,88 @@-# 04: PBR texture and material realism+# QB-04: PBR texture and material realism-Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/quality-bar/04-pbr-texture-material-realism.md`".+It is complete on its own. Also read `prompts/quality-bar/_shared.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question, a plan you did not execute, or "should I proceed?".+2. Every blocker has a pre-answered route at the bottom. Use it and keep going.+3. CLAUDE.md hard rules: no mocks, no stubs, no TODO comments, no em-dash or en-dash+ characters. Stage explicit paths only. Do not push unless asked.+4. GPU and Vertex spend is pre-approved. Never downgrade quality to save credits.## Mission-Close the material gap. A perfect mesh still looks fake with a flat albedo texture. Every GLB-the platform produces should carry a complete PBR set (albedo + normal + roughness/metallic,-AO where the pipeline can bake it) tuned per material class, so skin reads as skin and metal-reads as metal under the viewers' image-based lighting.+A perfect mesh still looks fake with a flat albedo texture. Every GLB the platform produces+should carry a complete PBR set (albedo, normal, roughness/metallic, AO where bakeable) tuned+per material class, so skin reads as skin and metal reads as metal under the viewers'+image-based lighting.-## Current state (verify)+## Step 0: re-derive current state (trust nothing below)-- `workers/texture/` is the SDXL texture worker; the swarm raised its SDXL settings to the- platform bar today (02f1d0230). `workers/remesh/`, `workers/stylize/` exist as services.-- `restyle_material` MCP tool re-skins GLBs from an instruction or PBR preset- (see `api/` MCP handlers). TRELLIS and Hunyuan3D emit their own textures.+```bash+ls workers/texture workers/remesh workers/stylize+grep -rn "restyle_material" api/_mcp3d/ api/_mcp/ mcp-server/src/tools/ | head+gcloud run services list --region us-central1 --project aerial-vehicle-466722-p5 \+ --format="value(metadata.name)" | grep -E "texture|remesh|stylize"+sed -n '1,40p' scripts/compress-glbs.mjs+```++Then generate one real GLB per live lane through `POST https://three.ws/api/forge` and inspect+which PBR channels each actually emits. `@gltf-transform/core` and `three` are already in the+dependency tree; do not add a library for this.## Tasks-1. **Audit what each lane actually emits.** For TRELLIS, Hunyuan3D, TripoSR/SG outputs: open- real GLBs (three.js or `@gltf-transform/core`, both in the dependency tree) and inspect- which PBR channels exist. Build a small `scripts/` inspection tool if none exists, and- record a channel matrix per lane in the report.-2. **Derive missing maps.** Where a lane emits albedo-only, add a post-stage in the texture- worker (GPU, credits approved): normal-from-height estimation and a roughness/metallic- inference pass keyed by the director's material classification from prompt 01 (person /- metal / wood / fabric / plastic / glass). Wire it into the forge pipeline as an opt-out- final stage, not a separate user step.-3. **Material presets that match reality.** Extend `restyle_material`'s preset library with- measured-value presets (real-world roughness/metallic/IOR values: skin 0.45-0.6 roughness,- nonmetal 0.0 metallic, brushed steel anisotropy hints, car paint clearcoat via- `KHR_materials_clearcoat`, glass via `KHR_materials_transmission`). Registered three.js- loaders already handle these extensions; verify each preset renders correctly in the- platform viewer before shipping it.-4. **Skin, eyes, hair for avatars.** For `text_to_avatar` / `forge_avatar` outputs, ensure the- avatar path applies: subtle subsurface approximation (three.js `MeshPhysicalMaterial`- thickness/attenuation or a baked SSS tint), separate eye material with high specular and- clear cornea, hair with alpha-cutout double-sided setup. This is what makes people look IRL- instead of mannequin.-5. **Texture resolution by tier.** Free tier keeps current sizes; standard/high go to 2K/4K- albedo with matching normal maps (GPU cost is credits). Confirm GLB payload stays sane with- KTX2/Basis compression where the viewer path supports it (`three/examples/jsm/loaders/KTX2Loader`- is available; test on mobile Safari before defaulting it on).-6. **Prove it.** Benchmark set (prompt 09 set, or create per prompt 01 task 6) rendered in the- platform viewer, before/after per lane. Skin/metal/glass/wood subjects mandatory.+1. **Channel matrix.** Build `scripts/inspect-glb-materials.mjs` (if no equivalent exists) that+ prints, per material: which of baseColor, normal, metallicRoughness, occlusion and emissive+ textures exist, their resolutions, and the extension list. Run it over one real output per+ lane. The matrix goes in the report and in `workers/texture/README.md`.+2. **Derive the missing maps.** Where a lane emits albedo only, add a post-stage in+ `workers/texture/` (GPU, credits approved): normal-from-height estimation plus a+ roughness/metallic inference pass keyed by the director's material classification+ (`api/_lib/forge-director-prompts.js`). Wire it into the forge pipeline as a final, opt-out+ stage, never a separate user step.+3. **Measured-value presets.** Extend `restyle_material`'s preset library with real-world+ values: skin roughness 0.45 to 0.6, nonmetal metallic 0.0, brushed-steel anisotropy hints,+ car paint via `KHR_materials_clearcoat`, glass via `KHR_materials_transmission`. Render each+ preset in the platform viewer under every HDRI the viewer ships before shipping it.+4. **Skin, eyes, hair for avatars.** For `text_to_avatar` and `forge_avatar` outputs: subsurface+ approximation (`MeshPhysicalMaterial` thickness/attenuation or a baked SSS tint), a separate+ eye material with high specular and a clear cornea, hair with an alpha-cutout double-sided+ setup. This is the difference between a person and a mannequin.+5. **Texture resolution by tier.** Free tier keeps current sizes; standard and high go to 2K/4K+ albedo with matching normals. Keep payloads sane by extending the existing meshopt plus WebP+ chain in `scripts/compress-glbs.mjs` rather than writing a second encoder. Verify a+ 4K-textured GLB still loads under Playwright WebKit and Android Chrome emulation; if it does+ not, tier the delivery (viewer fetches compressed, download offers full-res).+6. **Prove it.** Run the fixed benchmark set (`data/quality-bench/prompts.json`) through+ `node scripts/quality-bench.mjs` before and after, covering skin, metal, glass and wood+ subjects. `node scripts/quality-bench.mjs --compare=latest,previous` exits nonzero on a mean+ drop greater than 1.0; that gate must pass.## Definition of done-- Channel matrix documented; every lane emits or gains a full PBR set.-- Presets verified in-viewer; avatar skin/eye/hair path shipped and screenshotted.-- Mobile payload check done (a 4K-textured GLB must still load on a mid phone; if not, tier the- delivery: viewer fetches compressed, download button offers full-res).-- Changelog entry + `workers/texture/README.md` updated. Pathspec commits only.--## Anticipated blockers, pre-answered--- KTX2 encode tooling: `toktx` or `@gltf-transform/cli` with the basisu encoder; add as a dev- dependency or use the container the texture worker builds, do not hand-roll an encoder.-- Normal-map estimation model choice: prefer what the texture worker already ships (SDXL- aux/controlnet stack) over adding a new model download; if adding one, it must come from the- weights bucket, not a runtime hub pull.-- A preset that looks wrong under one HDRI: test under all environment presets the viewer- ships (prompt 05 lists them) before tuning values.+- [ ] Channel matrix documented per lane; every lane emits or gains a full PBR set.+- [ ] Presets verified in-viewer under all shipped HDRIs, with screenshots.+- [ ] Avatar skin/eye/hair path shipped and screenshotted at 320, 768, 1440 px.+- [ ] Mobile payload check done, with real byte sizes.+- [ ] Quality-bench comparison run and no regression; numbers in the report.+- [ ] `npm test` green; `data/changelog.json` entry; `workers/texture/README.md` updated.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| KTX2 or WebP encode tooling | Use `@gltf-transform` plus the encoder already wired in `scripts/compress-glbs.mjs`. Never hand-roll an encoder. |+| A new model download looks necessary | Prefer what the texture worker already ships. If unavoidable, pull it from `gs://three-ws-model-weights`, never a runtime hub fetch. |+| A preset looks wrong under one HDRI | Test under every environment preset the viewer ships before tuning; record which HDRI drove the value. |+| Vertex refuses a prompt | The reason is in `promptFeedback.blockReason`, not `finishReason`. Rephrase and continue. |+| A GPU worker is cold or scaling | Expected. Wait or raise minScale within quota; never switch to a weaker lane to save time. |++## Report format++The channel matrix, before and after renders, the quality-bench delta, real byte sizes, and any+single remaining owner action. No recap of this file.diff --git a/prompts/quality-bar/06-forge-ux-flow.md b/prompts/quality-bar/06-forge-ux-flow.mdindex 829b24fa2..fadc4159e 100644--- a/prompts/quality-bar/06-forge-ux-flow.md+++ b/prompts/quality-bar/06-forge-ux-flow.md@@ -1,67 +1,83 @@-# 06: Forge UX, from prompt to proud screenshot+# QB-06: Forge UX, from prompt to proud screenshot-Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/quality-bar/06-forge-ux-flow.md`".+It is complete on its own. Also read `prompts/quality-bar/_shared.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question, a plan you did not execute, or "should I proceed?".+2. Blockers have pre-answered routes at the bottom. Use them and keep going.+3. CLAUDE.md hard rules: no mocks, no stubs, no TODO comments, no fake progress bars, no+ em-dash or en-dash characters. Stage explicit paths only. Do not push unless asked.## Mission-Make /forge feel like a flagship product: the flow from typing a prompt to holding a-share-worthy 3D result should be legible, alive, and impossible to dead-end. The failover-plumbing exists (3e22c3e82: poll-time lane failover, one-click engine switching); this prompt-is about the experience wrapped around it.+Make `/forge` feel like a flagship product: the path from typing a prompt to holding a+share-worthy 3D result should be legible, alive, and impossible to dead-end.++## Step 0: re-derive current state (trust nothing below)++```bash+npm run dev # port 3000, then walk /forge as a first-time user in a real browser+ls src/forge-compare.js src/forge-prompt-gen.js api/_lib/forge-lane-health.js+grep -n "starter\|chip" pages/forge.html | head -20+npm run audit:web -- --only /forge 2>/dev/null || node scripts/page-audit.mjs+```++Known shipped as of 2026-07-30, verify then skip: generation history persistence, the+side-by-side compare mode (`src/forge-compare.js`, `tests/forge-compare.test.js`, documented in+`docs/forge.md`), and the six curated starter prompts on `pages/forge.html`.## Tasks-1. **Walk the flow as a first-time user** (`npm run dev`, real browser, also 320px). Log every- moment of confusion: what is happening now, how long will it take, what do I do with the- result. Fix what you find; the list below is the floor, not the ceiling.+1. **Walk the flow as a first-time user** (`npm run dev`, real browser, also at 320 px). Write+ down every moment of confusion: what is happening now, how long will it take, what do I do+ with the result. Fix what you find. The list below is the floor, not the ceiling.2. **Generation timeline.** Replace passive waiting with a real stage timeline (enhancingprompt, generating reference views, sculpting mesh, painting textures, finishing) driven by- the actual poll states the API already returns, with elapsed time and the honest ETA from- `api/_lib/forge-lane-health.js`. Show the reference images as they are produced (prompt 01- makes them); watching the concept appear kills perceived latency.-3. **Result moment.** When the GLB lands: camera intro move, quality viewer (prompt 05 module),- and immediate actions with zero hunting: download GLB/USDZ, view in AR (/ar handoff), rig it- (auto-rig lane), refine it (`refine_model` conversational iteration), restyle materials,- place it IRL (/irl), share link with a real og-image of THIS model. Every action wired to- the existing feature, no dead buttons.-4. **History and comparison.** A signed-in user's generations persist (check the existing- storage; wire if half-built). Side-by-side compare two generations of the same prompt- (engine A vs engine B), which also showcases the engine-switch feature.- **DONE 2026-07-30.** History already persisted; the compare half shipped in- `src/forge-compare.js` (compare mode over the gallery, two-pane viewer, orbit- synced but radius kept per model since generations differ in scale, and a- same-prompt hint that fires only on a genuine two-engine A/B). Covered by- `tests/forge-compare.test.js`, documented in `docs/forge.md`, verified in a- real browser at 320/768/1440 with no console errors. Task 5's "6 starters"- was already satisfied (six chips in `pages/forge.html`), so both gaps this- work order still carried are now closed. What keeps it open: the definition- of done below also asks for every result-moment action clicked through to its- destination and `npm run audit:web` clean on /forge, neither of which this- session ran.-5. **Prompt help.** Subtle prompt-improvement affordance: show the director's enhanced prompt- after generation ("what we actually asked the model"), one-click "try a variation". Good- empty state: 6 curated example prompts with thumbnails that users can fire instantly.-6. **Error and retry UX.** Every failure path renders a designed state: what failed in plain+ the poll states the API already returns, with elapsed time and the honest ETA from+ `api/_lib/forge-lane-health.js`. Show reference images as they are produced; watching the+ concept appear kills perceived latency.+3. **Result moment.** When the GLB lands: a camera intro move, the quality viewer, and+ immediate actions with zero hunting: download GLB and USDZ, view in AR (`/ar` handoff), rig+ it, refine it (`refine_model`), restyle materials, place it IRL (`/irl`), share a link whose+ og-image renders this model. Click every one of those through to its destination and back.+ A dead button is a failed task.+4. **Prompt help.** After generation, show the director's enhanced prompt ("what we actually+ asked the model") with a one-click "try a variation".+5. **Error and retry UX.** Every failure path renders a designed state: what failed in plainlanguage, the automatic recovery that already happened (failover), and the one-click manual- options (switch engine buttons from 3e22c3e82). No raw error strings, no dead ends. Session- expiry mid-generation must preserve the job and resume after re-auth.-7. **Keyboard + a11y.** Cmd/Ctrl+Enter submits, Esc collapses panels, focus states everywhere,- ARIA labels on the viewer controls, prefers-reduced-motion respected on the intro move.+ options (engine switch). No raw error strings, no dead ends. Session expiry mid-generation+ must preserve the job and resume after re-auth; test that by clearing the session cookie+ mid-poll.+6. **Keyboard and accessibility.** Cmd/Ctrl+Enter submits, Esc collapses panels, focus-visible+ everywhere, ARIA labels on viewer controls, `prefers-reduced-motion` respected on the intro+ move. Confirm with `npm run audit:a11y`.## Definition of done-- The full walk-through repeated clean: no confusion points left, no console errors, all states- (loading/empty/error/success) designed at 320/768/1440.-- Every result-moment action clicked through to its destination feature and back.-- `npm test` green (respect the vitest-masks-e2e gotcha); `npm run audit:web` clean on /forge.-- Changelog entry in holder language. Screenshots of the result moment in the report; apply the- pride check before calling it done.--## Anticipated blockers, pre-answered--- Poll payloads missing a stage you want to display: extend the API response in `api/forge.js`- (additive field, keep old clients working) rather than faking states client-side.-- USDZ availability: the bake pipeline exists (iOS AR work, 8b23b8d9e); if a model lacks USDZ,- generate on demand through that path, show a brief "preparing AR file" state.-- Persistence store choice: use whatever `api/` already uses for user artifacts (R2 +- database rows); do not introduce new storage.+- [ ] The full walk-through repeats clean: no confusion points, no console errors, loading,+ empty, error and success states designed at 320, 768 and 1440 px.+- [ ] Every result-moment action clicked through to its destination feature and back, listed+ one by one in the report with what happened.+- [ ] `npm run audit:web` clean on `/forge`; `npm run audit:a11y` no new failures.+- [ ] `npm test` green (do not pipe through `tail`).+- [ ] `data/changelog.json` entry in holder language; screenshots of the result moment in the+ report.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| A poll payload lacks a stage you want to show | Extend the response in `api/forge.js` as an additive field (old clients keep working). Never fake a state client-side. |+| USDZ missing for a model | Generate on demand through the existing bake pipeline and show a brief honest "preparing AR file" state. |+| Persistence store choice | Use what `api/` already uses for user artifacts (R2 plus database rows). Do not introduce new storage. |+| The crawler reports WebGL or texture errors | `npm run audit:web` runs pages concurrently and produces false 3D failures. Re-check any 3D failure serially before reporting it. |+| A generation is slow because a GPU is cold | That is task 2's subject, not a blocker. Show the honest ETA. |++## Report format++The confusion list with what you changed for each, the action-by-action click-through table,+screenshots, and any single remaining owner action. No recap of this file.diff --git a/prompts/quality-bar/07-design-system-sweep.md b/prompts/quality-bar/07-design-system-sweep.mdindex 2770e4d02..6ce5f4a22 100644--- a/prompts/quality-bar/07-design-system-sweep.md+++ b/prompts/quality-bar/07-design-system-sweep.md@@ -1,55 +1,82 @@-# 07: Design-system consistency sweep (tokens, states, microinteractions)+# QB-07: Design-system consistency sweep (tokens, states, microinteractions)-Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/quality-bar/07-design-system-sweep.md`".+It is complete on its own. Also read `prompts/quality-bar/_shared.md`, `DESIGN-TOKENS.md`+and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question or an unexecuted plan. This is a sweep, so if the+ session cannot cover every surface, finish complete surfaces cleanly and list the remainder+ ordered by traffic. Never leave a surface half-migrated.+2. Blockers have pre-answered routes at the bottom.+3. CLAUDE.md hard rules: no mocks, no TODO comments, no commented-out code, no em-dash or+ en-dash characters. Stage explicit paths only, commit per surface.## Mission-Make 300+ pages feel like one product. Audit and enforce a single design language: tokens for-color/spacing/type/radius/shadow, consistent interactive states, designed empty/error/loading-states everywhere, and the microinteractions that signal quality.+Make 300+ pages feel like one product: one token sheet, consistent interactive states,+designed empty, error and loading states everywhere, and the microinteractions that signal+quality.++## Step 0: re-derive current state (trust nothing below)++```bash+npm run audit:tokens # scripts/audit-token-drift.mjs, the drift gate+npm run audit:console # console errors across pages+npm run audit:overlays+npm run audit:a11y # playwright axe pass on the top pages+grep -rn "#[0-9a-fA-F]\{6\}" src/ pages/ --include=*.css --include=*.html | wc -l+```++Record those numbers. They are your before-baseline and the report must show the after-numbers+next to them.## Tasks-1. **Token audit.** Find the real token sheet (`src/styles/`, root CSS custom properties).+1. **Token audit.** Find the canonical token sheet (`src/styles/`, `DESIGN-TOKENS.md`).Inventory hardcoded values across `src/`, `pages/`, `public/*.html` (colors, px spacing,font sizes, radii, shadows, z-indices). Consolidate to tokens; where two near-identical- values exist (#0a0a0b vs #0b0b0c), pick the canonical one. Ship the token sheet as the- single source with a short comment header documenting the scale.-2. **Interactive-state pass.** Every button, link, card, input across the platform gets hover,- active, focus-visible, and disabled states from shared classes/tokens. Focus rings visible- on dark AND light contexts. Grep for `cursor: pointer` elements missing states as a cheap- detector.-3. **State design sweep.** For each major surface (forge, markets, marketplace/agents,+ values exist, pick one canonical value and use it everywhere.+2. **Interactive-state pass.** Every button, link, card and input gets hover, active,+ focus-visible and disabled states from shared classes and tokens. Focus rings must be+ visible on dark and light contexts. Grep for `cursor: pointer` elements with no state rules+ as a cheap detector.+3. **State design sweep.** For each major surface (forge, markets, marketplace, agents,dashboard, wallet, launches, changelog, news, play, walk, irl, ar, scene studio, docs):- verify loading (skeletons, not spinners, matching final layout), empty (says what to DO,- with a working CTA, ideally an illustration or 3D flourish), error (plain language +- recovery action), and overflow (1,000 items, 200-char names, tiny screens). Fix inline;- keep a per-surface checklist in the report.-4. **Motion language.** One transition standard: durations (150ms micro, 250ms panel), one- easing curve set, opacity+transform only (no layout-thrashing animations),- prefers-reduced-motion honored globally. Element enter/exit intentional on the top surfaces.-5. **Typography and rhythm.** Consistent type scale and line-height rhythm; heading hierarchy- semantic (h1 once per page, no skipped levels); readable measure on text-heavy pages- (docs, news, changelog).-6. **Contrast and a11y floor.** Automated pass (axe-core via Playwright, already available in- the e2e stack) on the top 30 pages: fix contrast below AA, missing labels, keyboard traps.+ verify loading (skeletons matching the final layout, not spinners), empty (says what to do+ with a working call to action), error (plain language plus a recovery action), and overflow+ (1,000 items, 200-character names, tiny screens). Fix inline; keep a per-surface checklist.+4. **Motion language.** One standard: 150 ms micro, 250 ms panel, one easing set, opacity and+ transform only, `prefers-reduced-motion` honored globally.+5. **Typography and rhythm.** One type scale and line-height rhythm; semantic heading+ hierarchy (one h1 per page, no skipped levels); readable measure on text-heavy pages.+6. **Contrast and accessibility floor.** Fix everything `npm run audit:a11y` reports on the top+ 30 pages: contrast below AA, missing labels, keyboard traps.## Definition of done-- Token sheet canonical; a grep for raw hex colors in `src/` returns only the token sheet and- justified exceptions (third-party embeds), listed in the report.-- Per-surface state checklist complete with fixes shipped.-- axe pass results before/after in the report; `npm run audit:web` no new errors;- visual spot-check at 320/768/1440 on the top 10 pages.-- One changelog entry summarizing the visible polish in holder language.--## Anticipated blockers, pre-answered--- Scale: this is a sweep, so batch by surface and commit per surface (pathspec commits); if the- session cannot finish all surfaces, finish complete surfaces cleanly and list the remainder- ordered by traffic; never leave a surface half-migrated.-- Legacy pages under `public/*.html` not in the Vite graph: remember the raw-/src trap (an- unregistered page shipping `/src` imports breaks: CSS import kills the page); test each- touched public page actually renders.-- Light/dark: the platform is dark-first; if a light context exists (docs, embeds), tokens must- carry both or explicitly declare dark-only. Do not invent a light theme in this prompt.+- [ ] Token sheet canonical; a raw-hex grep over `src/` returns only the token sheet plus+ justified exceptions, each listed in the report.+- [ ] Per-surface state checklist complete, with the fixes shipped.+- [ ] `npm run audit:tokens`, `npm run audit:console`, `npm run audit:a11y` all better than the+ Step 0 baseline and none worse. Before and after numbers in the report.+- [ ] `npm run audit:web` shows no new errors; visual spot-check at 320, 768, 1440 px on the+ top 10 pages.+- [ ] One `data/changelog.json` entry summarizing the visible polish in holder language.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| Scale: too many surfaces for one session | Batch by surface, commit per surface with explicit paths, and list the remainder ordered by traffic. Never leave one half-migrated. |+| A legacy page under `public/*.html` is not in the Vite graph | Remember the raw-`/src` trap: an unregistered page shipping `/src` imports breaks (a CSS import kills the page). Test every touched public page actually renders. |+| Light vs dark | The platform is dark-first. If a light context exists (docs, embeds), tokens carry both or explicitly declare dark-only. Do not invent a light theme here. |+| A token change touches a file another agent is editing | Re-read the file immediately before each edit and stage only your own paths. |++## Report format++Before and after audit numbers, the per-surface checklist, the exceptions list, and the+remainder ordered by traffic. No recap of this file.diff --git a/prompts/quality-bar/08-mobile-performance.md b/prompts/quality-bar/08-mobile-performance.mdindex 65c3f36de..8e32f72a9 100644--- a/prompts/quality-bar/08-mobile-performance.md+++ b/prompts/quality-bar/08-mobile-performance.md@@ -1,6 +1,15 @@-# 08: Mobile experience and asset performance+# QB-08: Mobile experience and asset performance-Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/quality-bar/08-mobile-performance.md`".+It is complete on its own. Also read `prompts/quality-bar/_shared.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question or an unexecuted plan.+2. Blockers have pre-answered routes at the bottom.+3. CLAUDE.md hard rules: no mocks, no TODO comments, no em-dash or en-dash characters. Stage+ explicit paths only. Publish only real measured numbers, never estimates.## Mission@@ -8,45 +17,73 @@ A crypto-native audience lives on phones. Make the platform genuinely excellentphone: fast first paint, smooth 3D, no WebGL exhaustion, small GLB payloads, thumb-friendlycontrols.+## Step 0: re-derive current state (trust nothing below)++A measured baseline already exists. Read it, then re-measure, because production has moved:++```bash+sed -n '1,40p' prompts/quality-bar/_generated/08/baseline.md+sed -n '1,40p' prompts/quality-bar/_generated/08/touch-baseline.md+node scripts/mobile-perf.mjs # Playwright field-style metrics, NOT Lighthouse+npm run audit:mobile-touch # scripts/mobile-touch-audit.mjs+```++The 2026-07-29 baseline measured `/play` LCP 37.7 s, `/marketplace` 30.4 s, `/` 27.4 s,+`/forge` TBT 56 s on a throttled Pixel 5. Those are the pages that matter most; if your fresh+run disagrees, trust your run and say so.++Lighthouse is not installed and must not be added. `scripts/mobile-perf.mjs` measures LCP, CLS,+FCP and a long-task blocking-time proxy directly through `PerformanceObserver` under emulated+mobile hardware and network. Quote its numbers with that caveat attached, exactly as+`baseline.md` does.+## Tasks-1. **Baseline.** Lighthouse (mobile preset, throttled) on the top 15 pages: home, forge,- markets, news, agents/marketplace, a coin page, dashboard, walk, irl, ar, play, launches,- changelog, docs start, an agent profile. Record LCP/CLS/TBT/transfer size. These numbers- anchor the report.-2. **GLB delivery pipeline.** Add a compression pass where models are served: Draco or- meshopt mesh compression + KTX2 texture compression via `@gltf-transform` (dependency-check- first per open-source-first rule). Serve compressed by default with full-res on the- download action (pairs with prompt 04 tiering). Target: typical forge output under 8MB over- the wire without visible quality loss. Verify decode support on iOS Safari WebGL and- Android Chrome before defaulting on; feature-detect and fall back to uncompressed.-3. **WebGL context discipline.** Enforce the one-visible-viewer rule sitewide (prompt 05 task 4- ships the mechanism; you verify it on real mobile viewports and fix stragglers). Pages with- model grids use static thumbnails that upgrade to live 3D on tap.-4. **Input ergonomics.** Touch targets 44px minimum, viewer gestures (orbit/pinch) not- fighting page scroll (use proper touch-action CSS), bottom-reachable primary actions on- generation flows, safe-area insets respected.-5. **Network resilience.** Generations survive tab backgrounding and flaky mobile networks:- poll with backoff and resume, never lose a finished result because the socket dropped.- Test by throttling to Slow 3G mid-generation.-6. **Re-measure.** Same Lighthouse matrix after. Publish the wins honestly (only real numbers)- in the changelog entry.+1. **Fix the worst pages first, in baseline order.** For each of the top five worst LCP or TBT+ pages: find the actual cause (main-thread blocking module, unlazy 3D, oversized image,+ render-blocking fetch), fix it, re-measure the same page with the same harness, and record+ the delta. A fix that does not move the number is not a fix.+2. **GLB delivery.** `scripts/compress-glbs.mjs` already runs dedup, prune, resample, quantize,+ `EXT_meshopt_compression` and WebP textures. Make it the default on the serve path: models+ written through `api/_lib/r2.js` callers get compressed at upload or finalize time, with the+ full-res original still available on the download action. Target: a typical forge output+ under 8 MB over the wire with no visible quality loss. Feature-detect decoder support and+ fall back to uncompressed.+3. **WebGL context discipline.** No page may hold more than two live WebGL contexts. Verify on+ real mobile viewports; grid pages use static thumbnails that upgrade to live 3D on tap. The+ `GL made/live/visible` column in `mobile-perf` output is your evidence.+4. **Input ergonomics.** 44 px minimum touch targets, viewer gestures not fighting page scroll+ (correct `touch-action`), primary actions reachable at the bottom of generation flows,+ safe-area insets respected. `npm run audit:mobile-touch` must come back clean.+5. **Network resilience.** Generations survive tab backgrounding and flaky networks: poll with+ backoff and resume, never lose a finished result because a socket dropped. Test by+ throttling to slow 3G mid-generation and by backgrounding the tab.+6. **Re-measure everything and publish honestly.** Same harness, same pages, before and after+ table. Only real numbers go in the changelog.## Definition of done-- Before/after Lighthouse matrix in the report; every top-15 page improved or explained.-- Compressed GLB path proven on iOS Safari + Android Chrome (real device lab not available:- use Playwright WebKit + Chrome mobile emulation and note the caveat).-- No page can exceed 2 live WebGL contexts; grid pages tap-to-activate.-- Changelog entry; docs updated where the embed/SDK behavior changed.--## Anticipated blockers, pre-answered--- `@gltf-transform` version conflicts with the three.js in the tree: pin the CLI as a- devDependency and run it in scripts (build-time), keeping runtime untouched.-- KTX2 on old devices: the KTX2Loader transcoder needs its wasm assets served locally; copy- them into static assets (never CDN hotlink), and fall back to png/jpg textures on decode- failure.-- Where GLBs are stored on R2: the compression pass runs at upload/finalize time in the- worker/API path that writes R2 (`api/_lib/r2.js` callers), not as a bulk rewrite; optionally- add a lazy migrate-on-first-serve for old assets.+- [ ] Before and after table for every top-15 page, produced by the same harness, in the report+ and committed under `prompts/quality-bar/_generated/08/`.+- [ ] Compressed GLB path proven under Playwright WebKit and Android Chrome emulation, with the+ real-device caveat stated.+- [ ] No page exceeds two live WebGL contexts; grid pages tap-to-activate.+- [ ] `npm run audit:mobile-touch` clean; `npm test` green.+- [ ] `data/changelog.json` entry quoting only measured numbers; docs updated where embed or+ SDK behavior changed.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| Lighthouse is missing | Deliberate. Use `scripts/mobile-perf.mjs` and keep its caveat wording. Never add Lighthouse as a dependency. |+| `@gltf-transform` version conflicts with the tree's three.js | Pin the CLI as a devDependency and run it from scripts at build time; leave the runtime untouched. |+| KTX2 or WebP decode fails on an old device | Serve the transcoder assets locally (never hotlink a CDN) and fall back to png/jpg textures on decode failure. |+| Old GLBs already on R2 | Compress at write time for new assets and add a lazy migrate-on-first-serve for old ones. Never bulk-rewrite storage. |+| A page's slowness is caused by someone else's in-flight change | Re-measure after `git pull` is not an option here (shared worktree); measure against production instead and say which revision you measured. |++## Report format++The before and after table, the cause you found per page, the compression byte deltas, and any+single remaining owner action. No recap of this file.diff --git a/prompts/quality-bar/10-avatar-likeness-irl-people.md b/prompts/quality-bar/10-avatar-likeness-irl-people.mdindex 67c9d4827..457835d18 100644--- a/prompts/quality-bar/10-avatar-likeness-irl-people.md+++ b/prompts/quality-bar/10-avatar-likeness-irl-people.md@@ -1,113 +1,91 @@-# 10: Avatar likeness, IRL people quality+# QB-10: Avatar likeness, IRL people quality-Read `prompts/quality-bar/_shared.md` first. Its operating clause applies: finish 100%, never ask.+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/quality-bar/10-avatar-likeness-irl-people.md`".+It is complete on its own. Also read `prompts/quality-bar/_shared.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question or an unexecuted plan.+2. Blockers have pre-answered routes at the bottom.+3. CLAUDE.md hard rules: no mocks, no TODO comments, no em-dash or en-dash characters. Stage+ explicit paths only. Never add a rig allowlist; fixes go at the mapping layer.## Mission-Photo→avatar and text→avatar outputs should look like real people: correct proportions,-believable skin, hands with five fingers, clothes with fabric behavior, and a rig that-animates without breaking the illusion. This prompt owns the human-specific end of the-realism campaign.+Photo-to-avatar and text-to-avatar outputs should look like real people: correct proportions,+believable skin, hands with five fingers, clothes with fabric behavior, and a rig that animates+without breaking the illusion.++## Step 0: re-derive current state (trust nothing below)++```bash+node scripts/animation-dignity-sweep.mjs --verbose # ten bone-naming conventions, measured+ls prompts/quality-bar/_generated/10/ # committed evidence from the last pass+npx vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js+gcloud run services list --region us-central1 --project aerial-vehicle-466722-p5 \+ --format="value(metadata.name)" | grep -E "avatar-reconstruction|model-rig|hunyuan"+```-## Current state (verify)+**Already proven, do not redo:** task 5 (animation dignity) is measured and green. Ten rig+conventions animate both arms and both legs down both production paths; the fixes landed in+`src/glb-canonicalize.js` with regression cover in both test files, and the evidence is+committed at `prompts/quality-bar/_generated/10/animation-dignity-sweep.{txt,json}`.-- `avatar-reconstruction` service is LIVE on Cloud Run. `unirig` (skeleton/skinning/ARKit-52)- is LIVE. `text_to_avatar` and `forge_avatar` chain mesh+rig with a humanoid gate; degrade- paths shipped 07-16 (3e22c3e82). Portrait realism cues went into the hunyuan worker today- (f131e51b0). Animation retarget is universal (`src/glb-canonicalize.js`,- `src/animation-retarget.js`); never add a rig allowlist.+**One known open defect from that pass:** on the runtime-only lane a Rigify rig binds the+`LeftArm`/`RightArm` clip track to `shoulder.L`/`shoulder.R` (the clavicle), because+`shoulder.L` and `upper_arm.L` normalize onto the same canonical name and no name-only table+separates them. The ingest canonicalizer resolves it structurally+(`canonicalizeJointNodes` pass 1.5), so stored avatars are correct and only a third-party GLB+loaded straight into the viewer is affected. **Remedy, part of this work order:** port pass+1.5/1.6 into `canonicalNodeMapFromObject` in `src/animation-retarget.js` and cover it with a+case in `tests/animation-retarget.test.js`.## Tasks-1. **Audit the avatar path end to end** with 6 real test cases: text prompts (athlete,- grandmother, child-safe stylized kid, businessperson) and 2 reference photos (CC0 portrait- sets). Score against the IRL bar: proportions, face fidelity, hands, feet, clothing,- texture seams at the neck/hairline. Document per-case failures precisely.-2. **Route avatars through the strongest lane.** Once Hunyuan3D is live (prompt 02), the- avatar mesh stage should prefer it with the portrait realism cues; verify the humanoid gate- still passes its output to unirig cleanly, T/A-pose normalized (bind pose sanity: the- glb-canonicalize suite covers naming, `tests/glb-canonicalize.test.js`).-3. **Face fidelity pass for photo input.** For photo→avatar, the reference pipeline must- preserve identity: feed the actual user photo (multi-view if the user gave several) to the- image→3D lane rather than a re-generated lookalike, and keep the face region's texture- resolution highest (UV area weighting if the pipeline exposes it). Never generate an avatar- of a named third party from text alone; photo input implies consent by upload, text-only- real-person names get the generic treatment (existing director behavior; keep it).-4. **Skin/eye/hair materials** land here for avatars specifically (coordinate with prompt 04- task 4; if that prompt already shipped the material module, wire it, do not duplicate).-5. **Animation dignity check.** Idle/walk retargeted onto 10 differently-sourced rigs- (Mixamo-, VRM-, Avaturn-style naming per glb-canonicalize coverage) with no candy-wrapper- twists, foot sliding, or T-pose flashes at 320px mobile and desktop. Fix retarget bugs at- the mapping layer, add test cases for any new bone convention encountered.-6. **The /irl moment.** Place 3 finished avatars in AR (the USDZ animated-bake path from- 8b23b8d9e) and screenshot; the pin should read as a person standing there, not a figurine.- ACES lighting for pins is live (07-15); verify avatars specifically benefit.-7. **Prove and publish.** Before/after gallery of all 6 test cases through the whole chain- (mesh, materials, rig, animation, AR). Changelog entry in holder language. Update- `.agents/skills` create-3d-avatar guidance if defaults changed.+1. **Fix the Rigify runtime-lane defect above.** Structural resolution, not a name special-case.+2. **Audit the avatar path end to end** with 6 real cases: four text prompts (athlete,+ grandmother, stylized kid, businessperson) and two CC0 reference photos. Score each against+ the IRL bar: proportions, face fidelity, hands, feet, clothing, texture seams at the neck+ and hairline. Document per-case failures precisely, with screenshots.+3. **Route avatars through the strongest live lane.** Confirm which mesh lane is Ready, prefer+ the highest-quality one with portrait realism cues, and verify the humanoid gate still hands+ its output to the rig worker cleanly with a normalized bind pose.+4. **Face fidelity for photo input.** Feed the actual user photo (multi-view when several were+ given) to the image-to-3D lane rather than a regenerated lookalike, and keep the face+ region's texture resolution highest. Never generate an avatar of a named third party from+ text alone; photo input implies consent by upload, text-only real-person names keep the+ generic treatment.+5. **Skin, eye and hair materials for avatars.** If QB-04 already shipped the material module,+ wire it. Do not duplicate it.+6. **The `/irl` moment.** Place three finished avatars in AR through the animated USDZ bake+ path and screenshot each. The pin should read as a person standing there, not a figurine.+7. **Publish.** Before and after gallery for all six cases through the whole chain (mesh,+ materials, rig, animation, AR), `data/changelog.json` entry in holder language, and an+ update to the `create-3d-avatar` skill guidance if defaults changed.## Definition of done-- 6/6 test cases visibly improved with the gallery in the report; hands specifically called out- (count fingers in the screenshots).-- Retarget suite green plus any new bone-convention cases added.-- AR screenshots included; no regression in the humanoid-gate degrade paths (kill-test one- rig failure and confirm the mesh still ships with a working fallback).--## Verification status (2026-07-29)--Evidence lives in `prompts/quality-bar/_generated/10/`. Only what is listed as PROVEN below-has measured evidence behind it; everything else is still open.--### Task 5, animation dignity: PROVEN--- Tool: `scripts/animation-dignity-sweep.mjs` (run it with `--verbose` for per-limb numbers,- `--json` for machine-readable output). It builds ten minimal skinned GLBs, one per bone-naming- convention, drives the real `idle` and `walk` clips onto each, and MEASURES the outcome rather- than checking that nothing threw: retarget coverage, per-limb rotation swing in degrees, and- end-effector world travel in hip-heights for both hands and both feet, composed off real- three.js world matrices. Every rig runs down both production paths (ingest-canonicalized and- raw-runtime).-- Result: **10/10 conventions animate both arms and both legs on both lanes.** Committed evidence:- `_generated/10/animation-dignity-sweep.txt` (verbose report) and `.json` (full per-limb data).- Conventions covered: Mixamo, Avaturn/RPM, Unreal mannequin, VRM 0.x/VRoid, VRM 1.0,- Daz/Genesis 8, MakeHuman, Blender Rigify, a simple `shoulderL` hobby rig, and a novel- anatomical-Latin scan rig the canonicalizer had never seen.-- **Five of the ten were broken before this run, and nothing in the suite noticed.** 30 of the 53- tracks in every clip address a finger joint, so a rig whose hands do not name-map scores about- 40% coverage, falls under `MIN_COVERAGE` in `src/animation-retarget.js`, and gets NO action- built at all: the avatar stands frozen in its bind pose, arms and legs included. Measured- before/after coverage: Unreal 39.6% to 96%, VRM 1.0 43.4% to 100%, Daz 43.4% to 100%,- MakeHuman 41.5% to 98%, Rigify 41.5% to 98%. The novel anatomical rig went from 7.5% (3 of 52- joints mapped, nothing moved at all) to 100%.-- Fixes landed at the mapping layer only, in `src/glb-canonicalize.js`: Unreal finger chain- (`index_01_l`), VRM 1.0 phalanx naming (`leftIndexProximal`, `leftThumbMetacarpal`), Daz- numbered fingers (`lIndex1`, `lMid1`), Rigify fingers (`f_index.01.L`, `thumb.01.L`),- MakeHuman digit numbering (`finger2-1.L`), and the whole anatomical-Latin skeleton- (`lumbar`, `thoracic`, `cervical`, `cranium`, `humerus.L`, `ulna.L`, `femur.L`, `tibia.L`,- `talus.L`, `metatarsus.L`, `index_proximal.L`). No rig allowlist was added.-- Regression cover: `tests/glb-canonicalize.test.js` gained per-convention finger cases plus an- anatomical-skeleton block; `tests/animation-retarget.test.js` gained a coverage-floor suite that- asserts six conventions clear the PRODUCTION `MIN_COVERAGE` default against the real clips and- map all 30 finger joints.-- One open defect, reported not papered over: on the runtime-only lane a Rigify rig binds the- `LeftArm`/`RightArm` clip track to `shoulder.L`/`shoulder.R` (the clavicle) because- `shoulder.L` and `upper_arm.L` normalize onto the same canonical name and no name-only table can- separate them (the simple hobby rig spells its upper arm `shoulderL` too). The arm still- animates, but it swings from the shoulder blade. The ingest canonicalizer resolves this- structurally (`canonicalizeJointNodes` pass 1.5), and every avatar three.ws stores is- canonicalized at ingest, so production is correct; only a third-party GLB loaded straight into- the viewer is affected. Remedy: port pass 1.5/1.6 into `canonicalNodeMapFromObject` in- `src/animation-retarget.js`. The sweep prints this as a warning with the remedy attached.--## Anticipated blockers, pre-answered--- Hunyuan3D not Ready yet: run the full audit and material/rig/AR work on the TRELLIS lane- now; the lane swap is one env var and a re-run, note it as the follow-up command.-- Hands are the hardest failure: if mesh-level hands stay bad at max budgets, the honest- mitigations are pose choice (relaxed hands), higher reference-image hand visibility, and- the director explicitly requesting "hands visible, fingers separated" in reference views.- Document what moved the needle with screenshots.-- Child-safety: stylized kid case must stay clearly stylized; if any output drifts- photoreal-child, drop the case from public galleries and note it; never ship photoreal- minors' likenesses.+- [ ] Rigify runtime-lane defect fixed structurally, with a regression test.+- [ ] `node scripts/animation-dignity-sweep.mjs` still 10/10 on both lanes after your changes.+- [ ] 6 of 6 test cases visibly improved, gallery in the report, hands specifically called out+ (count the fingers in the screenshots).+- [ ] AR screenshots included; humanoid-gate degrade path kill-tested (force a rig failure and+ confirm the mesh still ships with a working fallback, never a T-pose).+- [ ] `npm test` green; `npm run audit:rig-coverage` clean.+- [ ] `data/changelog.json` entry; `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| The strongest mesh lane is not Ready | Run the full audit and material, rig and AR work on the lane that is. The swap is one env var and a re-run; note it as the follow-up command. |+| Hands stay bad at max budgets | The honest mitigations are pose choice (relaxed hands), higher hand visibility in the reference views, and the director explicitly requesting "hands visible, fingers separated". Document what moved the needle with screenshots. |+| A stylized kid case drifts photoreal | Drop the case from public galleries and say so. Never ship photoreal likenesses of minors. |+| A new bone-naming convention appears | Add its mapping to `src/glb-canonicalize.js` plus a case in `tests/glb-canonicalize.test.js`. Never add a curated rig allowlist. |+| A GPU lane is cold | Wait it out. Do not fall back to a weaker lane for the quality audit. |++## Report format++The per-case scoring table with before and after images, the sweep result, the AR screenshots,+and any single remaining owner action. No recap of this file.diff --git a/prompts/roadmap/creation-consolidation.md b/prompts/roadmap/creation-consolidation.mdindex db6e148f3..83173a90f 100644--- a/prompts/roadmap/creation-consolidation.md+++ b/prompts/roadmap/creation-consolidation.md@@ -1,383 +1,130 @@-# Creation Surface Consolidation — Audit & Plan--**Status:** Phase 1 (additive hub) shipped 2026-07-08. Phase 2 executed 2026-07-16 for everything that survived re-verification against the live tree; several table rows turned out stale or unsafe (see the 07-16 note). Phase 3 (§3.3 pipeline handoffs) executed 2026-07-16 (see the Phase 3 note). Phase 2 closed out 2026-07-29: the `/agent/new` and `/scan` 301s and the standalone `/avatar-edit` retirement shipped; the `/embed` -> `/studio` and `/avatar-edit` -> Avatar Studio redirects are recorded as deliberate no-ships with their blockers (see the 07-29 note).-**Audited:** 2026-06-12-------## Progress note — 2026-07-08--**Phase 1 (§4, step 1–3: rebuild `/create` as the intent hub) is shipped.** `pages/create.html`-now opens with a "What do you want to create?" section — four intent cards (Build an AI agent →-`/create-agent`, Make a 3D avatar → same-page anchor, Generate a 3D model → `/forge`, Launch a-token world → `/launchpad`, with a footnote pointing at `/play` for live worlds) — one question-deep, matching §3.1 exactly. The page's original content (hero "Customize a base avatar" editor-card + the full secondary grid: describe-to-3D, template picker, selfie scan, talking video,-Cosmos, GLB upload, Avatar Studio) is **untouched and still fully wired** — it now lives under the-"Make a 3D avatar" anchor as that intent's answer, exactly as §3.1 specifies ("The current-template-picker content of `/create` survives as the 'From scratch / templates' path"). No JS-handlers, IDs, or existing behavior were changed — only new markup/CSS was added above it.-`data/pages.json`'s `/create` entry and the page's meta/OG/JSON-LD were updated to describe the-hub instead of the stale "agent wizard" copy that predated this pass. A changelog entry was added-(`data/changelog.json`, tag `improvement`, dated 2026-07-08, title "/create is now the front door-for everything you can build").--**Phase 2 (§4 steps 4–10: kill duplicates per clusters C1–C6, plus all 301 redirects in the-redirect table) is deliberately NOT done.** Nothing was deleted, merged, or redirected — every-page named in §1/§2 (`/scan`, `/create/selfie`, `/agent/new`, `/create/character`,-`/create-character`, `/avatar-edit`, `/import/rpm`, `/embed.html`, `/create-prompt`,-`/create-review`, `/avatar-studio-demo`, `/avatar-embed`, `/bulk-launch`, etc.) is exactly as it-was before this pass, still live, still linked from wherever it was linked from. `vercel.json` was-not touched. This phase touches live production routes with real traffic and hard-to-reverse-redirects — it needs a dedicated pass with explicit owner review of the C1–C5 merge decisions-(especially the open decisions in §5: which photo→avatar implementation wins, what happens to-`/start`, where `/pose` lives) before any code changes. A future session should pick up Phase 2-here, not assume this consolidation is fully executed.-## Progress note: 2026-07-16 (Phase 2 pass)--Every §2/§4 cluster was re-verified against the tree before acting; the June audit had gone stale in several places. What was executed, and what was deliberately not:--**Executed:**-- **C3:** `/create/character` and `/create-character` had already been deleted (no pages, no routes; both hit the designed 404). The redirect-table 301s to `/play` now exist in `vercel.json`, so old links land on the character-capable worlds surface instead of a 404.-- **C2 (links, not the 301):** the table's `301 /agent/new -> /create-agent` is unsafe and was NOT added. The §1.1 claim "(routes to same flow)" is stale: `/agent/new` routes to `pages/agent-edit.html`, which immediately creates a draft agent, and it is the target of the marketplace "Start an agent with this avatar" handoff (`/agent/new?avatar_id=&avatar_glb=&avatar_name=`, `startAgentFromAvatar()` in `src/marketplace.js`). A 301 breaks that handoff. Instead every generic "create an agent" entry link now converges on the canonical wizard: the marketplace "+ Create Agent" / "+ New Agent" CTAs (`pages/marketplace.html`, three call sites in `src/marketplace.js`) and the search-page agent CTA (`src/search-page.js`) point at `/create-agent`; the avatar handoff keeps `/agent/new`. Bonus fix: the search-page avatar CTA pointed at `/create-avatar`, a route that has never existed (dead link); it now points at `/create#avatar-options`.-- **C1 (cross-link, not the merge):** both photo->avatar surfaces stay. Re-inspection shows they are distinct input methods, not duplicates: `/scan` is live-camera real-time reconstruction, `/create/selfie` is single-photo upload; the same "different input methods" logic §2 already applies to `/mocap-studio` vs `/pose`. Each hero now cross-links the other (`.alt-path` line under the subtitle), so they behave as one product with two input modes. Nav links `/create/selfie`; `/scan` stays reachable via `/features/scan`, search, tutorials, and the new cross-link. The §5.1 hard merge (one implementation at one URL) remains an owner decision.-- **Nav (finishes Phase 1 step 2):** the `/create` hub itself was missing from the nav. Build > Start here now opens with "Create anything" -> `/create`. The `/create-agent` item was also relabeled from "Create an avatar" (a mislabel that collided with the avatar column) to "Create an agent".-- **C6 (cross-link, not the merge):** the `/studio` "Your widget is live" modal now links `/playground` (§3.3 handoff). The `/embed` -> `/studio` 301 was NOT done: `/embed` is a live editor linked from 10+ surfaces (`features`, `create-next`, `marketplace`, `search`, `feature-discovery`, `getting-started`, `coincommunities-ui`) and `/studio` has no equivalent of its mode/size/position tuning, so the redirect would destroy working UX.--**Found already done or stale (no action):**-- **Step 10:** `/bulk-launch` is already admin-gated at `/admin/bulk-launch`; no public route exists.-- **C5:** `/create-prompt` is not stranded; it is the nav-linked "Describe it to 3D" surface served at `/create/prompt`. `/create-review` is the live review step of the create flow (`src/create.js` navigates to it). `/avatar-studio-demo` is already deleted (no page, no route). `/avatar-embed` is the iframe target behind `/embed/avatar` used by SDK embeds; it must not be retired.-- **C4:** `/avatar-edit` is orphaned but Avatar Studio has no edit mode (`avatar-studio.html` reads no URL params), so `301 /avatar-edit -> /avatar-studio?mode=edit&id=` has no working destination; redirecting would silently lose edit-by-id for bookmarked URLs. Left live. `/import/rpm` stays as a page: the hub links it as the import option and it supports URL import the hub's upload card does not.--**Still open for future passes:** the `/agent/new` 301 (blocked until `/create-agent` supports the avatar handoff params), the C1 single-URL merge (§5.1 owner decision), `/avatar-edit` retirement (needs an Avatar Studio edit mode), the `/embed` -> `/studio` merge (needs feature parity in `/studio`).--## Progress note: 2026-07-16 (Phase 3 pass — pipeline handoffs, §3.3)--Phase 3 wires the completion-state handoffs from §3.3 that were still missing, all additive (new CTAs on existing "done" states; no routes, redirects, or existing behavior changed):--**Executed:**-- **Row 1 (photo->avatar -> agent):** the `/create/selfie` done state gains a "Turn this into an agent" button that PATCHes the avatar name (when set) then navigates to `/agent/new?avatar_id=&avatar_name=&avatar_glb=` with the just-built body pre-selected, reusing the exact hand-off the marketplace's `startAgentFromAvatar()` already uses (agent-edit.js consumes those params). `/scan` inherits this automatically since it now `location.replace()`s to `/create/selfie`.-- **Row 2 (agent -> deploy):** the `/create-agent` wizard success screen gains a "Take it further" row with four next-stage links: "Give it a voice" -> `/voice`, "Embed it anywhere" -> `/studio` (pre-loaded with the agent's 3D body via `?model=` when publicly readable), "Put it in a world" -> `/play`, "Launch its token" -> `/launchpad`.-- **Row 3 (voice -> agent):** the `/voice` clone-done state gains an "Add to an agent" link to `/dashboard`, where any agent's editor voice tab picks up the new clone.--**Found already done (no action):**-- **Row 4 (studio snippet -> playground + agent detail):** `/studio` already links `/playground` (shipped in the 07-16 Phase 2 commit).-- **Row 5 (avatar detail -> edit):** `avatar-page.js` already offers an owner "Edit avatar" button to `/create/studio?edit=ID` (Avatar Studio's edit mode), plus Voice Lab and "Open in Studio" CTAs.--**Still open:** the same route-level items listed in the Phase 2 note (the `/agent/new` 301, the C1 single-URL merge, `/avatar-edit` retirement, and the `/embed` -> `/studio` merge) all remain owner/parity-gated and were not touched.--## Progress note: 2026-07-29 (Phase 2 close-out pass)--Picks up the four items the 07-16 pass left open. Three of the four shipped; the fourth is-recorded below as a deliberate no-ship with the reason and the remaining work, because the-redirect it calls for would have removed working functionality.--The redirect mechanics matter here, so they are written down once: `server/index.mjs` matches-`vercel.json` `routes` against the **pathname only** and emits `Location` verbatim, so a-status-only route **drops the query string**. Any retired route that carries meaningful params-therefore uses a `has`-gated rewrite for the param-carrying form and the 301 only for the bare-form. That pattern is used twice below.--**Executed:**--- **C2 — `/agent/new` -> `/create-agent` (301), shipped.** The 07-16 blocker was real: `/agent/new`- serves `pages/agent-edit.html`, which POSTs a draft agent on page load, and it was the target of- the avatar handoff (`?avatar_id=&avatar_glb=&avatar_name=`). Both are now resolved.- `src/create-agent.js` gained `applyAvatarHandoff()`: it reads those three params, seeds- `state.model` in `library` mode (or `starter` mode when only a GLB URL arrives, which imports the- model at ship time), opens the matching pane, prefills the name as `"<avatar> Agent"`, and- `history.replaceState`s the URL back to `/create-agent`. Note this is strictly more than- `/agent/new` ever did: `agent-edit.js` read `avatar_glb` but never used it. The two producers now- link the canonical wizard directly (`startAgentFromAvatar()` in `src/marketplace.js`, the- "Turn this into an agent" button in `pages/create-selfie.html`). `vercel.json` keeps- `/agent/new` alive for old links: two `has`-gated rewrites (`avatar_id`, `avatar_glb`) serve- `create-agent.html` with the params intact, and the bare path 301s. `/agent/:id/edit` is- untouched: `agent-edit.html` is still the editor for an existing agent, it is only the- create-a-blank-agent entry that is retired. `data/pages.json` entry removed.--- **C1 — `/scan` merged into `/create/selfie` (301), shipped.** Re-inspection overturned the 07-16- "two distinct input methods" reading. `pages/scan.html` had already been reduced to a stub that- `location.replace()`d to `/create/selfie` on load, and `/create/selfie` owns *both* inputs: the- "Use camera" button opens the live camera, "Upload" takes a file. So there was no capability left- to port and no second implementation to choose between: §5.1's open decision resolves to- `/create/selfie` by what the code already does. `/scan` now 301s server-side (no more- render-then-bounce), `pages/scan.html` and its Vite entry are deleted, and the entry is gone from- `data/pages.json`. Inbound links repointed: `pages/features/scan.html` (both CTAs),- `pages/what-is.html`, and the `/studio` empty state. The now-circular "Prefer to use your camera- live? The 3D Scanner…" cross-link on `/create/selfie` is replaced by copy pointing at the- page's own camera button (under a new i18n key, so stale translations fall back to English- instead of rendering a self-link). `/features/scan` stays as the marketing page.--- **C4 — the standalone `/avatar-edit` landing retired, shipped (partial).** §2 C4 asks for two- things: kill the standalone URL, and make Avatar Studio the editor. The first shipped: the bare- `/avatar-edit` path (which rendered an error, since it has no avatar to edit) now 301s to- `/avatars`, while a `has`-gated rewrite keeps the legacy `?id=` form rendering, and- `src/avatar-edit.js` rewrites that URL in place to the canonical `/avatars/:id/edit` with- `replaceState` (no reload, so the `?equip-*` gallery handoff survives). The last producer of the- query form, `src/a-me.js`, now links the canonical path; every other caller already did.- The second half did **not** ship, deliberately: see below.--- **C6 — `/embed` parity work in `/studio`, shipped; the 301 did not.** Four options the- `/walk-embed` runtime has always honoured were unreachable from Widget Studio, so any- Studio-built avatar snippet silently shipped the defaults. `public/studio/studio.js` now exposes- them on the `walking-avatar` type: **ground** disc/shadow (`?ground=false`), visitor- **gesture** buttons (`?gestures=true`), the attribution **badge** (`?badge=false`), and a- **responsive** snippet that emits an `aspect-ratio` wrapper instead of fixed pixels. Defaults- mirror `src/walk-embed.js`, and only non-default values are written into the URL. The two- surfaces now cross-link and each states what it is for.--**Deliberately NOT shipped, with the reason:**--- **The `/embed` -> `/studio` 301.** After the parity work above, `/studio` still cannot do- `/embed`'s job, and the gaps are structural rather than missing checkboxes:- 1. **No-account snippet generation.** `/embed` is fully client-side: configure, copy, leave.- `/studio` must persist a widget row before `openEmbedModal` can emit anything, so the redirect- would put a sign-in wall in front of a flow that has none today.- 2. **Chat mode.** `/embed`'s `chat` mode emits `<iframe src="/a/<agentId>?embed=1">`. Studio's- `talking-agent` is a different runtime (`/widget#widget=<id>&kiosk=true`) and cannot produce- that URL. `src/dashboard-next/pages/agents.js` links `/embed?avatar=…&mode=chat` today.- 3. **Deep-linkable config.** `/embed` reflects every control into `location.search` and rehydrates- from it, so a configured editor URL is itself a shareable artifact. `/studio` reads only- `edit`/`template`/`type`/`model`/`avatar`. A query-dropping 301 (see the mechanics note above)- would break every saved `/embed?…` URL, and a `has`-gated rewrite cannot translate the params- because Studio does not read them.- 4. **Raw GLB/VRM URL as the avatar**, and the **platform paste instructions**- (HTML / React / WordPress / Webflow / Shopify), have no Studio equivalent.- Also mechanical: `walk-sdk/src/config.js` suppresses the corner companion on paths prefixed- `/embed`; moving the editor under `/studio` needs that list updated in the same change.- The honest state is that these are two products sharing a category, not a duplicate: a fast- stateless snippet maker and a saved, brandable widget builder. Closing 1-3 means building a- guest mode, a chat widget type, and a config-URL layer inside `/studio` (a project, not a- redirect). Until then the two are cross-linked and the 301 stays unshipped.--- **`/avatar-edit` -> Avatar Studio edit mode.** The redirect in the §4 table is still unsafe, and- the 07-16 note understated why: Avatar Studio's edit mode is not merely missing features, it- **loses data**. `collapseAppearance`/`hydrateAppearance` in `src/avatar-studio-utils.js` know only- `accessories/morphs/colors/hidden`, so opening a garment-wearing avatar in- `/create/studio?edit=ID` and saving drops `appearance.garments` and `appearance.outfit`; and its- save is a client-side `GLTFExporter` re-export of `base_model_url` that overwrites the canonical- GLB, where `avatar-edit` PATCHes appearance only and lets the server bake rebuild the dressed- model. On top of that, Studio has no wardrobe/closet (8 garment slots with occlusion masking), no- auto-rig tab, no walk preview or "Play as this" handoff, no `?equip-*` support, and its- recolour/hide targets are hardcoded Wolf3D material names where `src/avatar-wardrobe.js` resolves- layers on arbitrary GLBs. Redirecting now would silently undress people's avatars. **Prerequisite- for the merge:** appearance round-trip fidelity (garments + outfit) and non-destructive save in- `src/avatar-studio.js` first; then the wardrobe/closet, rig, and walk panels; then the redirect.--**Phase 2 status after this pass:** steps 4 (C2), 5 (C1), 6 (C3), 8 (C5) and 10 are complete.-Step 7 (C4) is half complete: the standalone route is retired, the editor merge is blocked on the-data-loss prerequisites above. Step 9 (C6) has its parity work done and its redirect deliberately-unshipped. The remaining `/start` question in §5.2 was not in scope for this pass.-------**Problem:** 28 creation-related surfaces (18 nav-linked, 10 orphaned) presented as a flat menu of peer options. Users can't tell which tools are products, which are steps, and which are duplicates. The platform has no creation funnel — it has a pile of doors.--**Goal:** One front door (`/create` hub organized by user intent), one canonical surface per capability, every tool's "done" state handing off to the next stage of the pipeline: **avatar → agent → deploy (embed / world / token)**.-------## 1. Full inventory--Every user-facing surface where something gets created. "Nav" reflects `public/nav-data.js` as of audit date.--### 1.1 AI agent creation--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Create an Agent | `/create-agent` | `pages/create-agent.html` | 5-step wizard: name, 3D body, skills, personality, voice, on-chain identity | `POST /api/agents` | Build ▸ |-| New Agent | `/agent/new` | (routes to same flow) | Appears to duplicate `/create-agent` | `POST /api/agents` | — |-| Get Started | `/start` | — | 5-step onboarding: avatar → name → skills → embed → monetization | multiple | — (hidden onboarding) |--### 1.2 3D avatar building--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Create avatar | `/create` | `pages/create.html` | Pick template avatar or upload GLB; feeds agent workflow | `/api/avatars/*` | Build ▸ |-| Avatar Studio | `/avatar-studio` | `pages/avatar-studio.html` | Full character creator (M3-org/CharacterStudio fork): sculpt, outfits, export GLB | internal Three.js | Build ▸ |-| Customize avatar | `/avatar-edit` | `pages/avatar-edit.html` | Edit existing avatar attributes/accessories | `/api/avatars/{id}` | — (orphaned) |-| Import avatar | `/import/rpm` | — | Import GLB/glTF from URL or file upload | `/api/avatars` | Build ▸ |-| Avatar Studio demo | `/avatar-studio-demo` | `pages/avatar-studio-demo.html` | Demo variant of Avatar Studio | internal | — (orphaned) |--### 1.3 Photo/selfie → 3D avatar--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Selfie to avatar | `/create/selfie` | `pages/create-selfie.html` | One photo → rigged 3D avatar (~60s) | `/api/avatars/{id}` | Build ▸ |-| Scan | `/scan` | `pages/scan.html` | Real-time camera reconstruction → rigged avatar (~60s) | `/api/config`, `/api/avatars/{id}` | — (only via `/features/scan`) |-| Scan feature page | `/features/scan` | — | Marketing/feature overview of Scan | read-only | Discover ▸ |--### 1.4 Prompt → 3D model generation--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Forge | `/forge` | `pages/forge.html` | Text prompt → textured GLB (Flux + TRELLIS); viewer, AR preview, download | `/api/forge*` (13 endpoints) | Build ▸ "Text to 3D" |-| Forge feature page | `/features/forge` | — | Marketing/feature overview of Forge | read-only | Discover ▸ |--### 1.5 Character creation (worlds)--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Play (coin worlds) | `/play` | — | 3D worlds per token; character creation is an integrated subflow | multiplayer backend | Build ▸ "Worlds" |-| Character creator | `/create/character` | `pages/create/` | Standalone character builder referencing `/play` worlds | internal | — (orphaned; linked from `/play`) |-| Create character | `/create-character` | `pages/create-character.html` | Lightweight character creation variant | unknown | — (orphaned) |--### 1.6 Motion & pose--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Mocap Studio | `/mocap-studio` | `pages/mocap-studio.html` | Webcam face/body capture → save clip → replay on any avatar | internal media capture | Labs ▸ |-| Pose Studio | `/pose` | — | Click-to-pose mannequin, presets, props, export PNG/animation | internal Three.js | Build ▸ + Labs ▸ |--### 1.7 Voice--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Voice Lab | `/voice` | — | Record → voice clone; compare models; use in agents/TTS | TTS/cloning APIs | Build ▸ |--### 1.8 Embed / widget creation--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Widget Studio | `/studio` | — | Pick avatar, configure voice/knowledge, copy embed snippet | config generation | Embed ▸ |-| Embed editor | `/embed.html` | — | Tune embed mode, size, position | config UI | Embed ▸ |-| Avatar SDK | `/avatar-sdk` | `pages/avatar-sdk.html` | Reference/demo for `@three-ws/avatar` + `<agent-3d>` component | docs | Embed ▸ |-| Playground | `/playground` | — | Viewer + environment + embed code | — | Build ▸ |--### 1.9 Token / launchpad--| Surface | Path | File | What it does | Backend | Nav |-|---|---|---|---|---|---|-| Launchpad Studio | `/launchpad` | `pages/launchpad.html` | Build hosted white-label 3D token launchpad (Pump.fun-powered) | `/api/launchpad/*` | Labs ▸ |-| Bulk Launch | `/bulk-launch` | `pages/bulk-launch.html` | Admin batch launcher for agent tokens | internal/admin | — (orphaned, admin-only) |--### 1.10 Stranded internal steps & demo variants (orphaned pages)--| Path | File | Likely purpose | Disposition needed |-|---|---|---|---|-| `/create-prompt` | `pages/create-prompt.html` | Internal prompt-input step | Fold into parent flow or delete |-| `/create-review` | `pages/create-review.html` | Review step of a creation flow | Fold into parent flow or delete |-| `/avatar-studio-demo` | `pages/avatar-studio-demo.html` | Demo variant | Delete or gate behind docs |-| `/avatar-embed` | `pages/avatar-embed.html` | Embed demo variant | Fold into `/studio` or docs |-| `/avatar-page` | `pages/avatar-page.html` | Avatar detail (read-only, not creation) | Keep; add "Edit" link → canonical editor |-| `/avatar-wallet-chat` | `pages/avatar-wallet-chat.html` | Feature demo | Keep as demo, out of creation scope |-| `/avatar-artifact` | `pages/avatar-artifact.html` | Standalone artifact viewer | Keep (Labs), out of creation scope |--**Totals: 18 nav-discoverable + 10 orphaned = 28 surfaces.**-------## 2. Duplication clusters & canonical decisions--For each cluster: the surfaces involved, the chosen canonical, and what happens to the rest.--| # | Cluster | Surfaces | Canonical | Action for the rest |-|---|---|---|---|---|-| C1 | Photo→avatar | `/scan`, `/create/selfie` | **Merge into one** (decision needed: which UX wins — `/scan`'s real-time tracking appears more sophisticated; `/create/selfie`'s URL fits the hub) | 301 the loser → winner; `/features/scan` links to winner |-| C2 | Agent creation | `/create-agent`, `/agent/new`, `/start` | **`/create-agent`** | 301 `/agent/new`; keep `/start` as guided onboarding that *wraps* the canonical wizard (no parallel implementation) |-| C3 | Character creation | in-`/play` flow, `/create/character`, `/create-character` | **`/play` integrated flow** | Fold `/create/character` into `/play` (modal or subroute); delete `/create-character`; 301 both |-| C4 | Avatar building | `/create`, `/avatar-studio`, `/avatar-edit`, `/import/rpm` | **`/create` as router → `/avatar-studio` as editor** | `/avatar-edit` becomes the edit mode of Avatar Studio (reachable from avatar detail pages, not standalone); `/import/rpm` becomes an upload option inside `/create` |-| C5 | Stranded steps | `/create-prompt`, `/create-review`, `/avatar-studio-demo`, `/avatar-embed` | n/a | Fold into parent flows or delete; 301 or 410 |-| C6 | Embed | `/studio`, `/embed.html`, `/avatar-sdk`, `/playground` | **`/studio`** for building; `/avatar-sdk` stays as docs | Merge `/embed.html` tuning options into `/studio`; clarify `/playground` as preview, link it from `/studio` |--Not duplicates — keep as-is (complementary, single-purpose):-- `/forge` (prompt→3D) — most mature tool on the platform (13 API endpoints)-- `/mocap-studio` vs `/pose` — different input methods (capture vs manual)-- `/voice` — single surface-- `/launchpad` (public) vs `/bulk-launch` (admin; remove from public routing)-------## 3. Target information architecture--### 3.1 The `/create` hub (new front door)+# RM-CONSOL: Creation surface consolidation, the remaining three++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/roadmap/creation-consolidation.md`".+It is complete on its own. Also read `prompts/roadmap/00-README.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100%. Never end with a question, a plan you did not execute, or "should I proceed?".+2. These are live production routes with real traffic. Additive first, redirect last, and never+ ship a redirect whose destination loses a capability the old route had. Two redirects were+ deliberately NOT shipped for exactly that reason; the reasons are recorded below and they+ are the work, not an excuse.+3. CLAUDE.md hard rules: no mocks, no TODO comments, no commented-out code, no em-dash or+ en-dash characters. Stage explicit paths only.++## Where this stands (verified through 2026-07-29, re-verify before acting)++Shipped: `/create` is the intent hub, nav restructured, `/agent/new` 301s to `/create-agent`+(with `has`-gated rewrites preserving the `avatar_id` / `avatar_glb` handoff), `/scan` 301s to+`/create/selfie`, `/create/character` and `/create-character` 301 to `/play`, the standalone+`/avatar-edit` landing 301s to `/avatars`, `/bulk-launch` is admin-only, and every pipeline+handoff in the target IA is wired (photo to avatar to agent to voice, embed, world, token).++One mechanical fact that governs every remaining redirect: `server/index.mjs` matches+`vercel.json` `routes` against the pathname only and emits `Location` verbatim, so a+status-only route **drops the query string**. Any retired route carrying meaningful params+needs a `has`-gated rewrite for the param form plus a 301 for the bare form.++## Task 1: Avatar Studio edit-mode parity, then retire `/avatar-edit` for real++The redirect is currently unsafe because Avatar Studio's edit mode **loses data**, not merely+features. `collapseAppearance` / `hydrateAppearance` in `src/avatar-studio-utils.js` know only+`accessories`, `morphs`, `colors` and `hidden`, so opening a garment-wearing avatar at+`/create/studio?edit=ID` and saving drops `appearance.garments` and `appearance.outfit`. Its+save is a client-side `GLTFExporter` re-export of `base_model_url` that overwrites the canonical+GLB, where `src/avatar-edit.js` PATCHes appearance only and lets the server bake rebuild the+dressed model.++Ship, in this order:++1. Appearance round-trip fidelity: `collapseAppearance` / `hydrateAppearance` preserve garments+ and outfit losslessly. Prove it with a unit test that round-trips a real dressed avatar's+ appearance object and asserts deep equality.+2. Non-destructive save: Avatar Studio PATCHes appearance and lets the server bake rebuild,+ exactly like `avatar-edit`. Never overwrite the canonical GLB from the client.+3. Port the missing panels: the wardrobe and closet (8 garment slots with occlusion masking,+ resolved on arbitrary GLBs by `src/avatar-wardrobe.js`, not hardcoded material names), the+ auto-rig tab, the walk preview and the "Play as this" handoff, and `?equip-*` support.+4. Only then: 301 the bare `/avatar-edit` path to the studio and keep a `has`-gated rewrite for+ the legacy `?id=` form. Verify with `curl -I` and by opening a real dressed avatar, saving,+ and confirming the garments survive.++## Task 2: `/embed` to `/studio`, the four structural gaps++The parity work already shipped (ground disc, gesture buttons, badge, responsive snippet on the+`walking-avatar` type), but `/studio` still cannot do `/embed`'s job. Close these, then redirect:++1. **No-account snippet generation.** `/embed` is fully client-side: configure, copy, leave.+ `/studio` must persist a widget row before `openEmbedModal` can emit anything. Build a guest+ mode so the snippet works with no sign-in.+2. **Chat mode.** `/embed`'s `chat` mode emits `<iframe src="/a/<agentId>?embed=1">`. Studio's+ `talking-agent` is a different runtime and cannot produce that URL. Add a chat widget type.+ `src/dashboard-next/pages/agents.js` links `/embed?avatar=...&mode=chat` today.+3. **Deep-linkable config.** `/embed` reflects every control into `location.search` and+ rehydrates from it, so a configured editor URL is itself a shareable artifact. `/studio`+ reads only `edit`, `template`, `type`, `model`, `avatar`. Add a config-URL layer that reads+ and writes the same params `/embed` uses, so the `has`-gated rewrite can carry them.+4. **Raw GLB or VRM URL as the avatar**, plus the platform paste instructions (HTML, React,+ WordPress, Webflow, Shopify), have no Studio equivalent. Port them.+5. Mechanical detail that must land in the same change: `walk-sdk/src/config.js` suppresses the+ corner companion on paths prefixed `/embed`; moving the editor under `/studio` needs that+ list updated or the companion appears inside the editor.++Only after all five: 301 the bare path, `has`-gated rewrite for the param-carrying form, and+verify every saved `/embed?...` URL shape still lands somewhere that reproduces its config.++## Task 3: the two open placement decisions++Decide both yourself using the most reversible option, implement it, and record the decision+plus the alternative in the report. Do not ask.++1. **`/start`**: keep it as guided onboarding that wraps the canonical `/create-agent` wizard+ (never a parallel implementation), or retire it now that the hub exists. Check its real+ traffic and inbound links first.+2. **`/pose`**: it currently appears in both Build and Labs in `public/nav-data.js`. It is a+ tool, not an intent, so it belongs in Labs only unless the data says otherwise.++## Definition of done++- [ ] Every redirect you ship returns 301 to a live page (`curl -I`), and every param-carrying+ form still works through its rewrite.+- [ ] A real dressed avatar survives an Avatar Studio edit and save with garments and outfit+ intact, proven in a browser and by test.+- [ ] `/studio` produces a working snippet with no account, in chat mode, from a raw GLB URL,+ and from a deep-linked config URL.+- [ ] `public/nav-data.js` has no link to a retired URL, and+ `grep -rn "<retired-path>" pages/ public/ docs/ src/` finds nothing.+- [ ] `data/pages.json` updated; `npm run build:pages` green; `npm run audit:web` green on every+ touched page; `npm run audit:links` clean.+- [ ] `data/changelog.json` entry for each user-visible merge.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| A redirect would lose a capability | Then it is not ready. Build the capability first, in the same session, and ship the redirect after. That is this whole work order. |+| Uncertain which surface wins a merge | Pick the one the code already favors (what users actually reach today), implement it, and record the alternative. |+| A page under `public/*.html` is not in the Vite graph | Test that it still renders after any change; the raw-`/src` import trap silently kills such pages. |+| Traffic data is unavailable | Use inbound-link count from `grep -rn` across `pages/`, `public/`, `docs/`, `src/` as the proxy and say so. |+| Another agent is editing a page you need | Re-read the file immediately before each edit; stage only your own paths. |-`/create` stops being "avatar template picker" and becomes the intent router. Four intents, each one question deep:+## Appendix: the target information architecture (unchanged)```/create-├── Build an AI agent → /create-agent (wizard; avatar step links to avatar intents below)+├── Build an AI agent -> /create-agent├── Make a 3D avatar-│ ├── From a photo → canonical photo→avatar surface (C1 winner)-│ ├── From scratch → /avatar-studio-│ ├── From a text prompt → /forge (avatar preset)-│ └── From a file/URL → upload option (absorbs /import/rpm)-├── Generate a 3D model → /forge-└── Launch a token world → /launchpad (and /play for worlds)+│ ├── From a photo -> /create/selfie (camera + upload, canonical)+│ ├── From scratch -> Avatar Studio+│ ├── From a text prompt -> /forge (avatar preset)+│ └── From a file or URL -> upload (absorbs /import/rpm)+├── Generate a 3D model -> /forge+└── Launch a token world -> /launchpad (and /play for worlds)```-The current template-picker content of `/create` survives as the "From scratch / templates" path.--### 3.2 Nav after consolidation--**Build dropdown** shrinks from 8+ tool links to ~4 intent links (mirroring the hub) plus Worlds. **Embed dropdown** keeps `/studio` + `/avatar-sdk` docs. **Labs** keeps genuinely experimental: Mocap, Pose, Launchpad live feeds. All menus live in `public/nav-data.js` (single source of truth — never hand-edit nav markup).--### 3.3 The pipeline (cross-links that turn tools into a product)--Every tool's completion state hands off to the next stage:--| When user finishes… | Offer… |-|---|---|-| Photo→avatar, Avatar Studio, Forge (avatar output), import | "Turn this into an agent" → `/create-agent` with avatar pre-selected |-| `/create-agent` wizard | "Give it a voice" → `/voice` · "Embed it" → `/studio` · "Put it in a world" → `/play` · "Launch its token" → `/launchpad` |-| `/voice` clone | "Attach to an agent" → agent picker |-| `/studio` snippet | Link to `/playground` preview + agent detail |-| Avatar detail page | "Edit" → Avatar Studio edit mode (replaces orphaned `/avatar-edit`) |-------## 4. Migration plan--### Phase 1 — Front door & nav (fixes the overwhelm; no tool internals touched)-1. Rebuild `/create` as the intent hub (3.1). Existing template picker becomes a sub-path of the avatar intent.-2. Restructure `public/nav-data.js` per 3.2.-3. Update `data/pages.json`; add changelog entry (user-visible).--### Phase 2 — Kill duplicates (one cluster per task; each independently shippable)-4. **C2:** 301 `/agent/new` → `/create-agent`; rewire `/start` to wrap the canonical wizard.-5. **C1:** pick the photo→avatar winner, merge the better pieces of both implementations, 301 the loser, add winner to nav.-6. **C3:** fold character creation into `/play`; delete/301 the two orphans.-7. **C4:** retire standalone `/avatar-edit` (edit mode lives in Avatar Studio, linked from avatar detail); absorb `/import/rpm` into the hub.-8. **C5:** fold or delete stranded steps and demo variants.-9. **C6:** merge `/embed.html` into `/studio`; cross-link `/playground`.-10. Remove `/bulk-launch` from public routing (admin-only access).--### Phase 3 — Pipeline handoffs (turns breadth into a journey)-11. Implement every completion-state handoff in 3.3.-12. End-to-end walkthrough: photo → avatar → agent → voice → embed → world → token, with no dead ends.--### Redirect table (cumulative)--| Old URL | New URL | Type |-|---|---|---|-| `/agent/new` | `/create-agent` | 301 |-| `/scan` *or* `/create/selfie` (loser of C1) | C1 winner | 301 |-| `/create/character` | `/play` (character subflow) | 301 |-| `/create-character` | `/play` (character subflow) | 301 |-| `/avatar-edit` | `/avatar-studio?mode=edit&id=…` | 301 |-| `/import/rpm` | `/create` (upload intent) | 301 |-| `/embed.html` | `/studio` | 301 |-| `/create-prompt`, `/create-review` | parent flow or 410 | per-case |-| `/avatar-studio-demo` | `/avatar-studio` | 301 |-| `/bulk-launch` | admin-gated, removed from public routes | — |--Redirects live in `vercel.json` routes. Also update `data/pages.json` (feeds sitemap + changelog) and any internal links found via grep before removing a page.--### Per-phase definition of done-- All redirects return 301 to a live page (verify with `curl -I`).-- `public/nav-data.js` has no link to a retired URL; `grep -r` across `pages/`, `public/`, `docs/` finds no internal links to retired URLs.-- `data/pages.json` updated; `npm run build:pages` green.-- Changelog entries for user-visible changes (Phase 1 hub + nav; each cluster merge that users would notice).-- Page audit (`scripts/page-audit.mjs`) green on touched pages.-------## 5. Open decisions--1. **C1 winner:** `/scan` (real-time tracking UX) vs `/create/selfie` (URL fits the hub). Recommendation: keep `/scan`'s implementation at `/create/selfie`'s URL — best UX, best IA.-2. **`/start` scope:** keep as marketing onboarding wrapping the wizard, or retire entirely once the hub exists?-3. **`/pose` placement:** currently in both Build and Labs; after consolidation it should live in Labs only (it's a tool, not an intent).-------*Related: [generation-suite.md](generation-suite.md) (prompt/image→3D roadmap — Forge is the canonical surface for that work; nothing in this consolidation conflicts with it).*+Completion states hand off to the next stage: avatar to agent, agent to voice, embed, world and+token, voice to agent, studio snippet to playground, avatar detail to editor. All of those are+shipped; keep them working.diff --git a/prompts/roadmap/developer-resources-repos.md b/prompts/roadmap/developer-resources-repos.mdindex 62178b492..b3c520f2e 100644--- a/prompts/roadmap/developer-resources-repos.md+++ b/prompts/roadmap/developer-resources-repos.md@@ -1,150 +1,104 @@-# Developer Resources & Satellite Repos — Plan--**Status:** Proposed, not started-**Drafted:** 2026-06-13-**Problem:** All developer-facing material (examples, SDK quickstarts, guides) lives inside the monorepo, invisible to developers browsing GitHub. Platforms at the bar we're aiming for (Vercel, Stripe, Anthropic) present curated satellite repos — `vercel/examples`, `stripe-samples`, `anthropic-cookbook` — that act as the discovery and onboarding front door.-**Goal:** A public `examples` repo (under a `three-ws` GitHub org) seeded from the monorepo and kept in sync by a one-way export script, with npm packages publishable so the examples actually install.-------## 1. What we already have (the raw material)--No new content needs writing. The job is re-presenting what exists.--### 1.1 Runnable examples (`examples/`)--| Example | What it shows |-|---|---|-| `coach-leo/` | Full agent build |-| `pump-fun-agent/` | Agent wired to the pump.fun feed |-| `three-concierge/` (+ `.html`) | Embedded concierge agent |-| `metamask-agent-wallet/` | Wallet-connected agent |-| `agenc-task-roundtrip/` | Agent task round-trip |-| `minimal.html`, `two-agents.html`, `web-component.html`, `widget-rpc.html`, `embed-test.html` | Single-file embed patterns |-| `skills/` | Skill examples |--### 1.2 SDKs--| SDK | Location |-|---|---|-| Core SDK | `sdk/` (includes `sdk/example/`) |-| Solana agent SDK | `solana-agent-sdk/` |-| Agent payments SDK | `agent-payments-sdk/` |-| Agent protocol SDK | `agent-protocol-sdk/` |-| Agent UI SDK | `agent-ui-sdk/` |-| Avatar SDK | `avatar-sdk/` |--### 1.3 MCP packages (`packages/`)--`avatar-agent-mcp`, `avatar-cli`, `avatar-schema`, `ibm-watsonx-mcp`, `ibm-x402-mcp`, `pumpfun-mcp`, `three-token-mcp`, `threews-avatar-mcp`.--### 1.4 Docs--60+ guides in `docs/` (architecture, authentication, embedding, MCP, multi-agent, on-chain agents, …), already wired into the site build and sitemap.-------## 2. Constraints that shape the plan--These are why the obvious approach ("just push copies to new repos") fails here.--1. **No CI on this account.** GitHub Actions are unavailable (all workflows deleted 2026-06-11). The standard satellite-sync pattern — a workflow pushing subtrees on every merge — cannot run. Sync must be a local script invoked from the existing push routine, or satellites rot.-2. **Mirror maintenance already bites.** We maintain one mirror (`nirholas/3D-Agent`, push-only) and it has caused destructive history merges. Every additional repo multiplies that class of risk. Satellites must be strictly one-way exports, never pulled from.-3. **~~npm packages 404.~~ RESOLVED (2026-06-13).** All public packages are now published on npm under the single `@three-ws/*` scope, and all 20 MCP servers (14 stdio + 6 remote) are registered in the official MCP registry. `npm install @three-ws/sdk` and `npx -y @three-ws/mcp-server` now work, so an examples repo no longer fails on its first instruction.-4. **A stale satellite is worse than none.** Broken examples in a standalone repo are anti-marketing. Anything we publish must be smoke-tested by the export script before it pushes.-------## 3. The plan--### Phase 0 — Prerequisite: publish to npm--- Obtain `NPM_TOKEN` (user-provided; not recoverable from `vercel env pull`).-- Run the existing publish pipeline for the MCP servers and SDKs.-- Until this lands, any satellite example must target the **hosted MCP/API endpoints** (which work today) rather than npm installs.--### Phase 1 — GitHub org--- Create the `three-ws` org. An org page with pinned repos signals project maturity in a way more repos under a personal account cannot.-- Transfer nothing initially; `nirholas/three.ws` stays the canonical monorepo. (Moving the canonical repo is a separate decision with deploy-pipeline implications — Vercel is linked to it.)--### Phase 2 — `three-ws/examples` repo--One satellite, not three. Tutorials are examples with longer READMEs; they live here. A separate docs repo is explicitly out of scope (§5).--Proposed layout:--```-examples/-├── README.md # index table: example → what it shows → run command-├── LICENSE-├── quickstarts/ # one folder per SDK, copy-paste minimal-│ ├── sdk/-│ ├── solana-agent-sdk/-│ ├── agent-payments-sdk/-│ └── mcp-server/-├── agents/ # full agent builds-│ ├── coach-leo/-│ ├── pump-fun-agent/-│ ├── three-concierge/-│ └── metamask-agent-wallet/-├── embeds/ # single-file HTML patterns-│ ├── minimal.html-│ ├── two-agents.html-│ ├── web-component.html-│ └── widget-rpc.html-└── tutorials/ # long-form walkthroughs+# RM-DEV: Developer resources and the examples satellite repo++**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/roadmap/developer-resources-repos.md`".+It is complete on its own. Also read `prompts/roadmap/00-README.md` and `CLAUDE.md`.++## Binding operating clause++1. Finish 100% of what can be done from this machine. Never end with a question about scope.+2. Two things genuinely need the owner and nothing else does: creating the GitHub org, and+ pushing to any repo. Prepare both so each is one command, batch them into one closing note,+ and do everything else first.+3. CLAUDE.md hard rules: no mocks, no placeholder code, no TODO comments, no em-dash or en-dash+ characters. Stage explicit paths only. Never create `.github/workflows/`; this project does+ not use GitHub Actions.+4. Satellites are strictly one-way exports. Never pull, fetch or merge from one.++## Problem++Every developer-facing artifact (examples, SDK quickstarts, guides) lives inside the monorepo,+invisible to a developer browsing GitHub. The platforms we benchmark against (Vercel, Stripe,+Anthropic) all present a curated satellite examples repo as the onboarding front door.++## Step 0: re-derive current state (trust nothing below)++```bash+ls examples/+ls sdk solana-agent-sdk agent-payments-sdk agent-protocol-sdk agent-ui-sdk avatar-sdk+npm view @three-ws/sdk version && npm view @three-ws/mcp-server version+ls scripts/export-examples.mjs scripts/export-satellites.mjs 2>&1+gh api user --jq .login 2>&1 | head -2+gh api /orgs/three-ws --jq .login 2>&1 | head -2```-Repo-level requirements:--- Root README states: **source of truth is the monorepo; PRs and issues belong there** (with links). Satellite accepts no direct contributions.-- Every example folder has its own README: what it does, prerequisites, exact run commands, link to relevant docs page on three.ws.-- Every example pins to working surfaces — published npm packages (post Phase 0) or hosted endpoints — never relative monorepo paths.--### Phase 3 — One-way export script--`scripts/export-satellites.mjs`, run locally as part of the push routine (no CI available):--1. Copy curated paths (`examples/` subset, SDK quickstarts) into a staging dir, rewriting any monorepo-relative imports to published package names.-2. Smoke-test: `npm install` + run each example's check command in staging. Abort export on any failure — never push broken examples.-3. Force-push staging to `three-ws/examples` as a single-parent history (satellite history is disposable; monorepo is truth).-4. Wire as `npm run export:satellites`; document in CLAUDE.md push routine. **Never pull/fetch from satellites** — same rule as the 3D-Agent mirror.--### Phase 4 — Cross-linking (what makes it pay off)--- three.ws docs pages link to the matching example folder; examples README links back to docs and the live platform.-- `llms.txt` / `llms-full.txt` reference the examples repo.-- Org profile README pins `examples` + monorepo.-- Changelog entry + Telegram push announcing the developer resources (this is user-visible — gets a `data/changelog.json` entry when shipped).-------## 4. Sequencing & effort--| Phase | Depends on | Effort |-|---|---|---|-| 0. npm publish | `NPM_TOKEN` from user | Small (pipeline exists) |-| 1. Org creation | User action (GitHub UI) | Minutes |-| 2. Examples repo seed | Phases 0–1 | ~1 day: curate, write READMEs, pin versions |-| 3. Export script | Phase 2 | ~half day incl. smoke-test harness |-| 4. Cross-linking | Phase 2 | Small, rolling |--If `NPM_TOKEN` is delayed: ship Phase 2 against hosted endpoints only, add npm-install quickstarts when Phase 0 lands.-------## 5. Explicitly not doing (and why)--- **Separate documentation repo.** Docs are wired into the site build (SEO injectors, `pages.json` as sitemap source of truth). Extracting them creates a second source of truth that drifts. Discovery is served by linking docs prominently from the examples README.-- **Separate tutorials repo.** Fragments attention; tutorials are `examples/tutorials/`.-- **Two-way sync or accepting PRs on satellites.** Sync conflicts without CI are unmanageable; the 3D-Agent mirror already demonstrated the failure mode.-- **Moving the canonical repo to the org (for now).** Vercel deploys hang off `nirholas/three.ws`; relinking was fixed 2026-06-11 and shouldn't be churned without a deliberate migration plan.-------## 6. Open decisions--1. **Org name** — `three-ws` proposed (`three.ws` isn't a valid org slug). Alternative: keep everything under `nirholas`.-2. ~~**npm scope**~~ — RESOLVED: consolidated to a single `@three-ws/*` scope; the former `@3d-agent/*` packages were repointed before publish.-3. **Announce timing** — changelog + Telegram on examples-repo launch, or wait until npm installs work end-to-end.+Known as of 2026-08-01: the `@three-ws/*` packages are published on npm (so an examples repo no+longer fails on its first instruction), `scripts/export-examples.mjs` exists,+`scripts/export-satellites.mjs` does not, and the `three-ws` org may not exist yet.++## Tasks++1. **Curate the export set.** Decide, file by file, what belongs in a public examples repo:+ quickstarts (one per SDK, copy-paste minimal), full agent builds from `examples/`,+ single-file embed patterns, and long-form tutorials. Anything referencing a crypto project+ other than $THREE is subject to the CLAUDE.md commit gate: keep it out of the export set+ unless the owner has approved that specific content.+2. **Write `scripts/export-satellites.mjs`.** It must:+ - copy the curated paths into a staging directory, rewriting monorepo-relative imports to+ published package names;+ - smoke-test every example in staging (`npm install` plus the example's own check command)+ and abort the whole export on any failure, because a broken public example is+ anti-marketing;+ - produce a single-parent history in staging and print the exact push command rather than+ pushing (pushing is owner-gated);+ - expose itself as `npm run export:satellites`.+3. **Author the repo content in staging**: root README stating that the monorepo is the source+ of truth and that issues and PRs belong there, a per-example README (what it does,+ prerequisites, exact run commands, link to the matching page on three.ws), MIT LICENSE, and+ version pins to published packages, never relative paths.+4. **Prove it works before anyone sees it.** Run the smoke stage against the real npm packages+ in a clean directory outside the workspace, so hoisted `node_modules` cannot mask a broken+ install. Record every command and its output.+5. **Cross-linking (the part that makes it pay off).** three.ws docs pages link to the matching+ example folder; `llms.txt` and `llms-full.txt` reference the examples repo; the examples+ README links back to the docs and the live platform.+6. **Documentation and changelog.** `STRUCTURE.md` row for the export script, a `docs/` section+ describing the satellite policy (one-way, no PRs, how to refresh), and a+ `data/changelog.json` entry when the repo goes live.++## Definition of done++- [ ] `npm run export:satellites` runs end to end into staging, smoke-tests every example, and+ aborts on failure. Show a deliberate failure being caught.+- [ ] Staging tree complete: root README, per-example READMEs, LICENSE, published-package pins.+- [ ] Clean-room install proven outside the workspace with the output pasted in the report.+- [ ] Cross-links added in docs, `llms.txt` and the examples README.+- [ ] `STRUCTURE.md` and `docs/` updated; `npm run audit:docs` clean.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.+- [ ] The two owner actions (create the `three-ws` org, run the printed push command) stated in+ one closing note, with the exact commands.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| The `three-ws` org does not exist | Build everything against a placeholder remote name, print the org-creation and push commands, and continue. Do not stall. |+| No push credentials for a new repo | Never push; that is gate 2 in CLAUDE.md anyway. Stage and print. |+| An example fails its smoke test | That is the point of the gate. Fix the example in the monorepo (it is broken for real users too), then re-export. |+| An example references another crypto project | Keep it out of the export set and list it in the report as owner-gated content. |+| `npx` resolves to hoisted workspace modules | Run the clean-room test outside `/workspaces/three.ws`; in-workspace `npx` breaks ESM resolution and produces false failures. |+| CI is wanted for the sync | There is no CI on this account and GitHub Actions are prohibited here. The export is a local script invoked from the push routine. |++## Deliberately out of scope (do not build)++- A separate documentation repo. Docs are wired into the site build and `data/pages.json`;+ extracting them creates a second source of truth that drifts.+- A separate tutorials repo. Tutorials live in `tutorials/` inside the examples satellite.+- Two-way sync or accepting PRs on satellites. The retired 3D-Agent mirror already proved that+ failure mode with a destructive history merge.+- Moving the canonical repo to the org. That is a separate decision with deploy implications.++## Report format++What the export produces, the clean-room install output, the caught-failure demonstration, and+the two owner commands. No recap of this file.diff --git a/prompts/roadmap/generation-suite.md b/prompts/roadmap/generation-suite.mdindex 1a850a7a2..3aaaf819c 100644--- a/prompts/roadmap/generation-suite.md+++ b/prompts/roadmap/generation-suite.md@@ -1,135 +1,109 @@-# three.ws — AI Generation Suite Roadmap (prompt→3D, image→3D, full Meshy/Tripo class)+# RM-GEN: Generation suite parity and production truth-**This is the platform's current top priority.** The goal is a generation suite that matches-Meshy and Tripo feature-for-feature on quality and beats them on agent-nativeness — and,-above all, that **actually works in production**. The repo already contains most of the-surface area; the gap is between "code exists" and "a user can run it on three.ws today."+**How to run this:** paste this whole file into a fresh Claude Code chat opened in+`/workspaces/three.ws`, or say "execute `prompts/roadmap/generation-suite.md`".+It is complete on its own. Also read `prompts/roadmap/00-README.md` (safety doctrine and the+regression gate) and `CLAUDE.md`.-Status below is from a **live production audit on 2026-06-11** — every row was probed-against the deployed endpoints, not inferred from code.+## Binding operating clause----+1. Finish 100%. Never end with a question, a plan you did not execute, or "should I proceed?".+2. "Works" means verified in production by running it, after deploy. Tests passing is not the+ bar; a stranger getting a GLB is the bar.+3. Fix the smallest broken thing that unblocks a whole flow before building anything new.+4. CLAUDE.md hard rules: no mocks, no stubs, no TODO comments, no em-dash or en-dash+ characters. Stage explicit paths only. Deploys are owner-gated: prepare them so the ship is+ one command.-## Verified current state+## Mission-| Feature | Code | Production reality (verified) |+A generation suite that matches Meshy and Tripo on quality and beats them on agent-nativeness,+and that actually works in production. The repo has the surface area; the gap has historically+been between "code exists" and "a user can run it on three.ws today".++## Step 0: rebuild the truth table (mandatory, replaces every claim below)++The June 2026 audit that this file used to carry is stale: several workers that it listed as+undeployed are Ready now. Do not read old status from anywhere. Probe production yourself and+write the table into your report:++```bash+gcloud run services list --region us-central1 --project aerial-vehicle-466722-p5 \+ --format="table(metadata.name,status.conditions[0].status)"+gcloud run services describe three-ws-api --region us-central1 \+ --project aerial-vehicle-466722-p5 --format=yaml | grep -E "^ *- name: (GCP_|MODEL_|LONGCAT_|REPLICATE_)" -A1+curl -s "https://three.ws/api/forge?catalog" | python3 -m json.tool | head -60+curl -s "https://three.ws/api/forge?health" | python3 -m json.tool | head -60+```++Then, for each row, run the real flow end to end against production and record the outcome:++| Feature | Endpoint | Probe ||---|---|---|-| Text→3D (`/forge`, FLUX/Imagen → TRELLIS) | ✅ complete | ❌ **was broken** — Vertex path crashed on malformed `GCP_SERVICE_ACCOUNT_JSON` with no Replicate fallback. Fixed in code 2026-06-11; needs deploy. |-| Image→3D (`/forge`, 1–4 views → TRELLIS) | ✅ complete | ❌ **was broken** — Replicate 404s unversioned community-model submits (`firtoz/trellis`). Fixed in code 2026-06-11 (version-resolve retry); needs deploy. |-| Image upload (R2 presign) | ✅ complete | ✅ works (verified live) |-| Tier/backend catalog + gallery | ✅ complete | ✅ works (verified live) |-| Meshy / Tripo geometry path (BYOK) | ✅ complete | ⚠️ reports `configured: true`; untested without a BYOK key — needs a live key test |-| x402 paid generation (`/api/x402/forge`) | ✅ complete | ⚠️ untested live; shares the (broken→fixed) submit path, so re-verify after deploy |-| Auto-rig (`?action=rig`) | ✅ complete | ❌ 501 — `REPLICATE_RERIG_MODEL` unset, `workers/unirig` not deployed |-| Remesh / retopo / lowpoly (`/api/forge-remesh`) | ✅ complete | ❌ 503 — `workers/remesh` not deployed, `GCP_REMESH_URL` unset |-| Stylize (`/api/forge-stylize`) | ✅ complete | ❌ 503 — `workers/stylize` not deployed |-| Part segmentation (`/api/forge-segment`) | ✅ complete | ❌ 503 — `workers/segment` not deployed |-| Background removal (`/api/forge-rembg`) | ✅ complete | ❌ 503 — `workers/rembg` not deployed |-| Text→animation (`/api/forge-motion`) | ✅ complete | ❌ 503 — `workers/model-text2motion` not deployed |-| Retexture full/region (`/api/studio/retexture-*`) | ✅ complete | ❌ dead — `GCP_TEXTURE_URL` unset; also MCP/API-only, no `/forge` UI |-| Talking-avatar video | ✅ complete | ❌ dead — `LONGCAT_WORKER_URL` unset |-| MCP 3D Studio tools (15 tools) | ✅ complete | ⚠️ tools resolve but inherit every breakage above |--Root cause in one sentence: **the API layer shipped, the compute layer behind it never got-deployed, and the two flows that don't need GCP workers died on two provider regressions-nobody noticed because nothing smoke-tests production.**-------## Phase 0 — Restore the core (now)--The two flows everything else builds on.--1. **Ship the 2026-06-11 fixes** (done in repo, needs deploy):- - `api/_providers/replicate.js` — on 404 from the unversioned model endpoint, resolve- `latest_version` and retry version-pinned. Unbreaks image→3D and text→3D's mesh step.- - `api/_mcp3d/text-to-image.js` — Vertex failure now falls back to Replicate FLUX;- Vertex's inline data-URI PNG is persisted to R2 and submitted as an https URL.- - `api/_mcp3d/vertex-imagen.js` — tolerant service-account JSON parsing (quoted /- escaped / base64 manglings), designed `unconfigured` error instead of a parse crash.- - Regression tests: `tests/api/providers-replicate.test.js`, `tests/api/text-to-image.test.js`.-2. **Fix `GCP_SERVICE_ACCOUNT_JSON` in Vercel prod** — re-paste the raw key-file JSON- (current value is mangled; the fallback masks it, but Imagen is the better/cheaper path).-3. **Verify `VERTEX_IMAGEN_MODEL`** — default `imagen-3.0-generate-001` may be retired on- Vertex; pin a current Imagen model explicitly.-4. **Post-deploy smoke test, both flows, in prod**: submit text→3D draft → poll → GLB loads;- submit image→3D → poll → GLB loads. No green checkmark without a real GLB.--**Done when:** a first-time visitor on three.ws/forge gets a model from a prompt and from a-photo, draft tier, under 2 minutes, zero console errors.--## Phase 1 — Light up the built-but-dark compute (next)--Everything here is written and containerized; it needs deployment + env wiring.--1. **Deploy automation for the editing workers.** ✅ Built 2026-06-12:- `workers/deploy/deploy-editing.sh` provisions + deploys `stylize`, `remesh`, `segment`,- `rembg` (CPU-only, default set) and optionally `texture` / `model-text2motion` (GPU),- prints the URL + key pairs, and with `VERCEL_TOKEN` upserts them into Vercel production- via REST. ❌ Not yet run — needs a privileged GCP identity (Cloud Shell):- `PROJECT_ID=… ./workers/deploy/deploy-editing.sh`.-2. **Set the env vars** (names): `GCP_REMESH_URL`, `GCP_STYLIZE_URL`, `GCP_SEGMENT_URL`,- `GCP_REMBG_URL`, `GCP_TEXTURE_URL`, `GCP_TEXT2MOTION_URL`, `GCP_TRIPOSG_URL`- (+ shared `GCP_RECONSTRUCTION_KEY`), `LONGCAT_WORKER_URL`/`LONGCAT_WORKER_KEY`.-3. **Auto-rig**: deploy `workers/unirig` (or pin a Replicate UniRig build) and set- `REPLICATE_RERIG_MODEL` / route through the GCP pipeline. Rig is the gateway to the- avatar/animation economy — it unlocks `/forge-motion` clips on generated meshes.-4. **Per-feature prod verification**, same bar as Phase 0: real mesh in, real result out.-5. **Production health surface.** `?catalog` says `configured: true` when an env var exists —- that's how two dead flows looked green. Add a `/api/forge?health` that live-probes each- provider (cheap HEAD/auth checks) + a scheduled smoke test that runs a draft generation- daily and alerts on failure.--**Done when:** every row in the table above reads ✅, verified in prod, and a daily smoke-test guards regressions.--## Phase 2 — Parity gaps vs Meshy / Tripo--What they have that we don't (or that we hide). Ordered by user impact.--1. **Surface the hidden tools in `/forge`.** Retexture (full + region/magic-brush) and- text→animation exist as APIs/MCP tools with no UI. The result panel should offer:- Retexture · Remesh · Stylize · Segment · Rig · Animate · Export — one pipeline, one page.-2. **Preview → refine flow.** Meshy's signature UX: cheap fast preview, then one-click refine- of the chosen result (re-run at high tier conditioned on the same seed/reference). We have- the tier system; add "Refine this" on every draft result.-3. **Export formats.** The remesh worker already converts glb/obj/stl/ply/usdz/3mf/fbx —- expose a format picker on download instead of GLB-only.-4. **PBR material controls.** High tier claims PBR; expose map outputs (albedo/normal/- roughness/metallic) and a re-bake option in the result panel.-5. **Sketch→3D.** ✅ Built 2026-06-12 on TripoSG-scribble (VAST AI, MIT) — a native- sketch+prompt→geometry model, not a controlnet preprocessing hack. New- `workers/model-triposg` GPU worker (also added to the avatar pipeline's mesh pool as- the TripoSR quality successor), `sketch` path through forge-tiers / gcp provider /- `/api/forge`, and a "From a sketch" mode on `/forge` that only appears when the- engine is live. ❌ Not deployed: stage weights (`stage-weights.sh`, key `triposg`),- deploy the worker (`deploy-all.sh`), set `GCP_TRIPOSG_URL` in Vercel. Output is- untextured geometry — pairs with retexture/stylize (item 1).-6. **Job webhooks + public API docs.** Replicate webhook plumbing exists for avatars; extend- to forge jobs and publish the endpoint contract (we already sell it via x402 — document it- like a product, with examples).-7. **Community gallery.** The private per-client gallery exists; add opt-in public showcase- with remix ("generate a variation of this").--## Phase 3 — Where we beat them--1. **Agent-native generation.** Meshy/Tripo sell to humans with credit cards; we sell to- agents with wallets. x402 pricing + MCP tools are live differentiators — market them,- benchmark them, keep them first-class in every new feature.-2. **Text→animation on generated meshes.** Neither Meshy nor Tripo generates animation.- Generate → rig → animate from one prompt chain is a demo nobody else can run.-3. **Generate → place.** One-click "drop into world": a generated asset becomes a networked- object in `/play` (Wave 0 object sync from the 3D-world roadmap). The generation suite- feeds the sandbox economy; assets become $three-priced cosmetics and props.-4. **Holder perks.** Generation tiers/quotas for $three holders (the only coin:- `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).-------## Operating rules for this roadmap--- **"Works" means verified in production**, by running it, after deploy. The 2026-06 audit- found two fully-tested, fully-wired flows that were 100% dead in prod. Tests passing is- not the bar; a stranger getting a GLB is the bar.-- Fix the smallest broken thing that unblocks a whole flow before building anything new.-- Every phase ends with the daily smoke test extended to cover what it shipped.+| Text to 3D | `POST /api/forge` | submit, poll to `done`, download the GLB, assert it parses with geometry |+| Image to 3D | `POST /api/forge` | presign, upload, submit, poll, download |+| Auto-rig | `POST /api/forge?action=rig` | rig a real mesh, assert bones and skin weights exist |+| Remesh / retopo | `POST /api/forge-remesh` | real mesh in, real mesh out |+| Stylize | `POST /api/forge-stylize` | same |+| Segment | `POST /api/forge-segment` | same |+| Background removal | `POST /api/forge-rembg` | real image in, alpha out |+| Text to motion | `POST /api/forge-motion` | clip out, plays on the default rig |+| Retexture | `POST /api/studio/retexture-*` | textures actually change |+| Talking avatar | the longcat worker route | real video out |+| x402 paid generation | `POST /api/x402/forge` | 402, pay, artifact |+| MCP 3D Studio tools | `POST /api/mcp-studio`, `/api/mcp-3d` | `tools/list` then a real `tools/call` |++A `configured: true` in the catalog means an env var exists, nothing more. That is exactly how+dead flows once looked green. Only a real artifact counts.++## Tasks++1. **Close every red row from Step 0.** Root-cause each (missing env var, worker not Ready,+ provider regression, schema drift), fix it, and re-run the same probe. If the fix needs a+ deploy, stage everything and name the one command.+2. **Health that tells the truth.** `GET /api/forge?health` must live-probe each provider+ (cheap authenticated HEAD or equivalent) rather than reporting on env-var presence. Add or+ extend the scheduled smoke test so a draft generation runs daily and alerts on failure.+3. **Surface the hidden tools in `/forge`.** Retexture (full and region), remesh, stylize,+ segment, rig, animate and export exist as APIs or MCP tools; the result panel should offer+ them as one pipeline on one page. Every button wired to the real endpoint.+4. **Preview then refine.** Cheap fast preview, then a one-click refine of the chosen result at+ a higher tier conditioned on the same seed and reference. The tier system already exists.+5. **Export formats.** The remesh worker already converts glb, obj, stl, ply, usdz, 3mf and fbx.+ Expose a format picker on download instead of GLB-only.+6. **PBR material controls.** Expose the map outputs (albedo, normal, roughness, metallic) and+ a re-bake option in the result panel. Coordinate with `prompts/quality-bar/04-...` rather+ than duplicating it.+7. **Job webhooks and public API docs.** Extend the existing Replicate webhook plumbing to+ forge jobs and publish the endpoint contract in `docs/` with runnable examples, since we+ sell it through x402.+8. **Community gallery.** Add an opt-in public showcase over the existing private gallery, with+ a remix action that generates a variation.++## Definition of done++- [ ] Step 0 table filled in from real production probes, every row green or explained with a+ named blocker and a one-command fix.+- [ ] `/api/forge?health` live-probes providers; the daily smoke test covers what you shipped.+- [ ] Every newly surfaced tool clicked through in a real browser at 320, 768 and 1440 px, with+ loading, empty, error and success states designed.+- [ ] `npm run gate` no worse than the baseline you captured at the start; `npm test` green.+- [ ] `data/changelog.json` entries for the user-visible additions; docs updated for the API+ contract.+- [ ] `npm run check:rules -- --paths <files you touched>` clean.++## Never blocked (pre-answered)++| Blocker | Do this |+|---|---|+| A worker is not deployed | Deploy it from `workers/<name>/cloudbuild.yaml` with the pinned build and runtime service accounts. Staging weights from `gs://three-ws-model-weights` is part of the task. |+| An env var is missing | Look in `.env`, then the Cloud Run service, then Secret Manager. Update single vars with `--update-env-vars`; `--set-env-vars` replaces the entire set. |+| A third-party provider 404s or throttles | Use the failover chain in `api/forge.js`; if a rung is missing, adding it is part of the task. |+| `gcloud` auth dead | Do everything else, then put the exact commands in the report; one `gcloud auth login` clears it. |+| A deploy is required | Owner-gated. Prepare it, name the single command, and finish everything else. |+| Production is behind `main` | Check `curl -s https://three.ws/api/version` against `git log` before debugging a "broken" feature. A stale revision explains most phantom failures. |++## Report format++The Step 0 truth table (before and after), the root cause per red row, what you shipped, and+the single owner action if one remains. No recap of this file.diff --git a/prompts/robinhood-chain/14-wallet-connect-kit.md b/prompts/robinhood-chain/14-wallet-connect-kit.mddeleted file mode 100644index 74edb8289..000000000--- a/prompts/robinhood-chain/14-wallet-connect-kit.md+++ /dev/null@@ -1,53 +0,0 @@-# 14 — Wallet & onboarding kit: `hood-connect`--Read `prompts/robinhood-chain/_shared.md` first. Wave 2: requires core SDK-(`file:../robinhood-chain-sdk`).--## Mission-Build `robinhood/hood-connect/` — the wallet + onboarding kit for Robinhood Chain dApps.-Chain 4663 is NOT a default network in any wallet; every dApp there needs "add network →-fund via bridge → connect" and today each developer hand-rolls it. This kit makes it one-component. Confirmed ecosystem gap (no wagmi connector kit / wallet UI kit exists). npm-`hood-connect` (fallbacks: `hoodconnect`, `@hoodkit/connect`).--## Deliverables--1. **`hood-connect/core`** (framework-free) —- - `addNetwork(provider)` — EIP-3085 `wallet_addEthereumChain` for 4663/46630 with the- official params (from viem chain defs), plus EIP-6963 multi-wallet discovery.- - `ensureChain(provider)` — connect → add-if-missing → switch, one call, typed states.- - Balance bootstrap check: detects an empty wallet on 4663 and returns funding options.-2. **`hood-connect/react`** — `<HoodConnectButton />` (the whole flow in one component:- discover wallets → connect → switch/add chain → show address + ETH/USDG balances),- `useHoodAccount()`, `useEnsureChain()`. Headless hooks + a styled default skin matching the- `_shared.md` design bar; every visual state designed (disconnected, wrong-chain, adding,- connected, error, no-wallet-installed with install links).-3. **Funding funnel** — `<FundWallet />`: live bridge routing via the LI.FI SDK/API (Robinhood- Chain is supported — verify current route support against their API during the build, fall- back to Relay if LI.FI lacks a route) so users move ETH/USDC from any chain to 4663 without- leaving the dApp; plus a "from Robinhood app" path documenting Robinhood Wallet withdrawal.- Real quotes, real route execution (test on a small real transfer if funds are available;- otherwise verify to the quote/route step and say so).-4. **"Add Robinhood Chain" button-as-a-service** — a tiny embeddable snippet (`docs/add.html`,- linkable on Pages) any site can iframe/link so "Add to wallet" works from README badges.- Include the markdown badge snippet in the README.-5. **Demo app** — `examples/demo/` (Vite): connect, fund, read balance, swap 1 USDG via the- core SDK — the full onboarding journey, exercised in a real browser during the build.--## Requirements-- Wagmi optionality: ship a wagmi v2 config export (`hood-connect/wagmi`) for teams already on- wagmi, but core must not require wagmi or React.-- Vitest: chain-param correctness (assert against viem defs, not copies), state machines for- ensureChain (each wallet-rejection path), EIP-6963 discovery with a scripted mock provider- (test-only harness, clearly not shipped code).-- Real-browser verification of the demo app with at least one real wallet extension (document- which; headless + extension via Playwright is acceptable).-- `docs/` static site per `_shared.md`: landing = the live connect button working on Pages- (connectable by any visitor with a wallet), integration guide (vanilla/React/wagmi), funding- funnel docs, the add-network badge gallery.--## Done checklist-- [ ] Demo journey completed in a real browser (evidence in report; tx hash if funding/swap ran).-- [ ] Connect button works ON the Pages docs site itself.-- [ ] Chain params provably derived from viem (test), never duplicated by hand.-- [ ] `npm pack` clean for all entry points; README badge snippet renders.diff --git a/public/changelog.json b/public/changelog.jsonindex cf72ce3fb..2bd0f3f78 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-01T20:23:20.633Z",+ "generated_at": "2026-08-01T21:10:27.953Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex ca86a36bb..77e38eb4c 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-01T20:09:05.322Z",+ "generated_at": "2026-08-01T21:10:27.933Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/verify-sign-avatar.mjs b/scripts/verify-sign-avatar.mjsnew file mode 100644index 000000000..1e4c39d1d--- /dev/null+++ b/scripts/verify-sign-avatar.mjs@@ -0,0 +1,128 @@+#!/usr/bin/env node+// Prove, in a real browser, the two things the Avatar control on the signing+// pages has to do: put an avatar the visitor chose from the gallery on stage,+// and let them move the camera around it.+//+// Usage: node scripts/verify-sign-avatar.mjs [baseUrl]+// defaults to http://localhost:3000 (npm run dev)++import { chromium } from 'playwright';++const BASE = process.argv[2] || 'http://localhost:3000';+let failures = 0;++function check(label, ok, detail = '') {+ if (ok) console.log(` ok ${label}`);+ else {+ failures++;+ console.error(` FAIL ${label}${detail ? ` :: ${detail}` : ''}`);+ }+}++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] });+const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });++// The dev server's HMR socket cannot reach a forwarded Codespace port. That is+// the tunnel, not the page, and it never exists in a built deployment.+const isDevNoise = (text) => /\[vite\]|WebSocket (connection|closed)/i.test(text);++const consoleErrors = [];+page.on('console', (m) => {+ if (m.type() === 'error' && !isDevNoise(m.text())) consoleErrors.push(m.text());+});+page.on('pageerror', (e) => {+ if (!isDevNoise(String(e))) consoleErrors.push(String(e));+});++let lastPicked = '';++for (const route of ['/sign-language', '/asl-alphabet']) {+ const rigSel = route === '/sign-language' ? '#sl-rig' : '#aa-rig';+ const stageSel = route === '/sign-language' ? '#sl-stage' : '#aa-stage';+ console.log(`\nAvatar control, ${BASE}${route}`);++ // Each route is judged from a first visit: the cross-page carry-over is+ // checked on its own at the end, where it cannot mask a broken default.+ await page.goto(`${BASE}${route}`, { waitUntil: 'domcontentloaded' });+ await page.evaluate(() => localStorage.clear());+ await page.reload({ waitUntil: 'domcontentloaded' });+ await page.waitForSelector(`${rigSel} button`, { timeout: 15000 });+ await page.waitForTimeout(2500);++ const labels = await page.$$eval(`${rigSel} button`, (els) => els.map((e) => e.textContent));+ check('three rigs offered, the last one the visitor own avatar', labels.length === 3 && labels[2] === 'Your avatar…', labels.join(' | '));+ check('the stage rendered a canvas', await page.$(`${stageSel} canvas`) !== null);++ // The gallery: open it, take the first public avatar, and require the stage+ // to come back up on that GLB.+ await page.click(`${rigSel} button:nth-child(3)`);+ await page.waitForSelector('.agp-overlay.agp-open', { timeout: 12000 });+ check('the avatar gallery opened', true);+ await page.waitForSelector('.agp-card', { timeout: 15000 });+ const pickedName = await page.$eval('.agp-card', (el) => el.querySelector('.agp-card-name')?.textContent?.trim() || '');+ await page.click('.agp-card');+ await page.click('.agp-cta');+ await page.waitForTimeout(6000);++ const prefs = await page.evaluate(() => JSON.parse(localStorage.getItem('threews:sign-prefs') || '{}'));+ check('the pick was stored as a custom rig', String(prefs.customRig?.url || '').length > 0, JSON.stringify(prefs.customRig || null));+ const pillLabel = await page.$eval(`${rigSel} button:nth-child(3)`, (el) => el.textContent);+ check('the pill now carries the avatar name', pillLabel.length > 0 && pillLabel !== 'Your avatar…', `${pillLabel} vs ${pickedName}`);+ const activePill = await page.$eval(`${rigSel}`, (el) => el.querySelector('button[aria-pressed="true"]')?.textContent || '');+ check('the custom avatar is the one on stage', activePill === pillLabel, activePill);+ check('the stage remounted on the custom GLB', await page.$(`${stageSel} canvas`) !== null);++ // Mounting is not the feature: the custom rig has to actually form the+ // letters. Spell a word on it and require the page to report what it signed.+ if (route === '/sign-language') {+ await page.fill('#sl-spell-input', 'hi there');+ await page.click('#sl-spell-btn');+ await page.waitForTimeout(4000);+ const said = await page.$eval('#sl-status', (el) => el.textContent || '');+ check('the custom avatar signs what you type', /signed|spelled/i.test(said), said);+ } else {+ await page.click('.aa-key[data-char="F"]');+ await page.waitForTimeout(2500);+ const played = await page.evaluate(() => document.querySelector('.aa-key[aria-pressed="true"]')?.dataset.char || '');+ check('the custom avatar forms a chosen letter', played === 'F', played);+ }++ // The camera: a drag has to move the view and surface the reset affordance.+ const box = await page.$eval(`${stageSel} canvas`, (el) => {+ const r = el.getBoundingClientRect();+ return { x: r.x, y: r.y, w: r.width, h: r.height };+ });+ await page.mouse.move(box.x + box.w / 2, box.y + box.h / 2);+ await page.mouse.down();+ await page.mouse.move(box.x + box.w / 2 + 140, box.y + box.h / 2 + 40, { steps: 12 });+ await page.mouse.up();+ await page.waitForTimeout(600);+ const resetVisible = () => page.$eval(`${stageSel} .av-pose-reset`, (el) => getComputedStyle(el).opacity === '1');+ check('dragging the avatar reveals the Reset view control', await resetVisible());+ await page.click(`${stageSel} .av-pose-reset`);+ await page.waitForTimeout(900);+ check('resetting the view hides the control again', !(await resetVisible()));++ // The choice has to survive a reload, and across the sibling page.+ await page.reload({ waitUntil: 'domcontentloaded' });+ await page.waitForSelector(`${rigSel} button`, { timeout: 15000 });+ await page.waitForTimeout(2500);+ const afterReload = await page.$eval(`${rigSel}`, (el) => el.querySelector('button[aria-pressed="true"]')?.textContent || '');+ check('the custom avatar survives a reload', afterReload === pillLabel, afterReload);+ lastPicked = pillLabel;+}++// One avatar, every signing surface: the pick made on /asl-alphabet is already+// on stage when the visitor walks back to /sign-language.+console.log('\nCarry-over between the signing pages');+await page.goto(`${BASE}/sign-language`, { waitUntil: 'domcontentloaded' });+await page.waitForSelector('#sl-rig button', { timeout: 15000 });+await page.waitForTimeout(2500);+const carried = await page.$eval('#sl-rig', (el) => el.querySelector('button[aria-pressed="true"]')?.textContent || '');+check('the avatar chosen on the alphabet page is signing here too', carried === lastPicked, `${carried} vs ${lastPicked}`);++check('no console errors', consoleErrors.length === 0, consoleErrors.slice(0, 4).join(' :: '));++await browser.close();+console.log(failures ? `\n${failures} check(s) failed\n` : '\nall checks passed\n');+process.exit(failures ? 1 : 0);diff --git a/src/asl-alphabet-page.js b/src/asl-alphabet-page.jsindex c01dca04b..825b232c2 100644--- a/src/asl-alphabet-page.js+++ b/src/asl-alphabet-page.js@@ -12,36 +12,18 @@import { PoseStage } from './avatar-pose.js';import { buildFingerspellingClip, normalizeWord } from './fingerspelling.js';import { DIGITS, LETTERS, LETTER_NOTES, PRACTICE_WORDS } from './asl-alphabet-data.js';+import { buildRigPicker, loadSignPrefs, resolveRig, saveSignPrefs } from './sign-avatars.js';import { log } from './shared/log.js';-// The same two rigs, and the same stored preferences, as /sign-language: a-// left-handed signer who set that once should never set it again.-const AVATARS = [- { id: 'classic', label: 'Classic', url: '/avatars/cz.glb' },- { id: 'expressive', label: 'Expressive face', url: '/avatars/default.glb' },-];-const PREFS_KEY = 'threews:sign-prefs';+// The rigs and the stored preferences are shared with /sign-language, including+// a custom avatar: a left-handed signer who set that once, on either page,+// should never set it again.const SPEEDS = [{ label: '0.5×', rate: 0.5 },{ label: '0.75×', rate: 0.75 },{ label: '1×', rate: 1 },];-function loadPrefs() {- try {- return JSON.parse(localStorage.getItem(PREFS_KEY)) || {};- } catch {- return {};- }-}-function savePrefs(prefs) {- try {- localStorage.setItem(PREFS_KEY, JSON.stringify(prefs));- } catch {- /* private mode: settings just don't persist */- }-}-const $ = (sel, root = document) => root.querySelector(sel);const CHARS = [...LETTERS, ...DIGITS];@@ -60,8 +42,8 @@ async function boot() {const stageHost = $('#aa-stage');if (!stageHost) return;- const prefs = loadPrefs();- let avatar = AVATARS.find((a) => a.id === prefs.avatar) || AVATARS[0];+ const prefs = loadSignPrefs();+ let avatar = resolveRig(prefs);let rate = SPEEDS.some((s) => s.rate === prefs.rate) ? prefs.rate : 1;let dominant = prefs.dominant === 'Left' ? 'Left' : 'Right';@@ -273,7 +255,7 @@ async function boot() {const practice = {answer: '',streak: 0,- best: Number(loadPrefs().aslBest || 0),+ best: Number(loadSignPrefs().aslBest || 0),active: false,};const practiceEl = $('#aa-practice');@@ -328,7 +310,7 @@ async function boot() {practice.streak = right ? practice.streak + 1 : 0;if (practice.streak > practice.best) {practice.best = practice.streak;- savePrefs({ ...loadPrefs(), aslBest: practice.best });+ saveSignPrefs({ aslBest: practice.best });}renderScore();if (practiceFeedback) {@@ -378,7 +360,7 @@ async function boot() {}};- const persist = () => savePrefs({ ...loadPrefs(), rate, dominant, avatar: avatar.id });+ const persist = () => saveSignPrefs({ rate, dominant, avatar: avatar.id });buildOptions('#aa-speed', SPEEDS, (s) => s.rate === rate, (s) => {rate = s.rate;@@ -398,16 +380,33 @@ async function boot() {if (current) play(current, { describe: false });},);- let switchingRig = false;- buildOptions('#aa-rig', AVATARS, (a) => a.id === avatar.id, async (picked) => {- if (switchingRig || picked.id === avatar.id) return;- switchingRig = true;- avatar = picked;- persist();- setStatus('Loading avatar…');- const ok = await mountStage();- switchingRig = false;- if (ok && current) play(current, { describe: false });+ // Any avatar on three.ws can form the letters, not only the two rigs that+ // ship with the platform: the handshapes are solved against whatever+ // skeleton is attached, so they land on your own avatar's fingers.+ buildRigPicker({+ host: '#aa-rig',+ optionClass: 'aa-opt',+ active: avatar,+ onStatus: setStatus,+ apply: async (picked) => {+ const previous = avatar;+ avatar = picked;+ persist();+ setStatus('Loading avatar…');+ if (await mountStage()) {+ if (current) play(current, { describe: false });+ else if (picked.custom) setStatus(`${picked.label} is forming the letters now.`);+ return true;+ }+ // No finger bones means no handshapes, and a hand that cannot move is+ // worse than the rig the visitor already had. Put that one back.+ avatar = previous;+ persist();+ const restored = await mountStage();+ setStatus(`${picked.label} has no finger bones, so it cannot form handshapes. ${previous.label} is back on stage.`);+ if (restored && current) play(current, { describe: false });+ return false;+ },});// ── Deep links ───────────────────────────────────────────────────────────diff --git a/src/avatar-pose.js b/src/avatar-pose.jsindex f6812c233..b0488a762 100644--- a/src/avatar-pose.js+++ b/src/avatar-pose.js@@ -255,6 +255,7 @@ export class PoseStage {if (getComputedStyle(this.host).position === 'static') this.host.style.position = 'relative';const btn = document.createElement('button');btn.type = 'button';+ btn.className = 'av-pose-reset';btn.textContent = 'Reset view';btn.setAttribute('aria-label', 'Reset the camera to the default view');btn.title = 'Drag to rotate, right-drag to move, pinch or ctrl+scroll to zoom. Double-click also resets.';diff --git a/src/glb-canonicalize.js b/src/glb-canonicalize.jsindex bba2beb64..83156a320 100644--- a/src/glb-canonicalize.js+++ b/src/glb-canonicalize.js@@ -465,54 +465,11 @@ export function canonicalizeJointNodes(json) {targetCount.set(canonical, (targetCount.get(canonical) || 0) + 1);}- // Pass 1.5: collision-aware shoulder/upper-arm split. Rigify and other- // anatomical rigs name the clavicle `shoulder.L` and the upper arm- // `upper_arm.L`; both normalise onto `LeftArm`, so two joints would take the- // same name and the clip's arm rotation would bind to the clavicle instead of- // the upper arm (arm swings from the shoulder blade). When an Arm target is- // contested and one contender is clavicle-spelled, demote it to the Shoulder- // bone (which the clip library also drives) — but only if Shoulder is free, so- // this can never fire on a rig that doesn't actually have the collision.- const isClavicle = (raw) => /shoulder|clavicle|collar/i.test(raw);- const isUpperArm = (raw) => /upper.?arm|upperarm/i.test(raw);- for (const side of ['Left', 'Right']) {- const arm = `${side}Arm`;- const shoulder = `${side}Shoulder`;- if ((targetCount.get(arm) || 0) < 2 || (targetCount.get(shoulder) || 0) > 0) continue;- const contenders = plan.filter((p) => p.canonical === arm);- const hasUpperArm = contenders.some((p) => isUpperArm(p.raw));- if (!hasUpperArm) continue;- for (const p of contenders) {- if (isClavicle(p.raw) && !isUpperArm(p.raw)) {- p.canonical = shoulder;- targetCount.set(arm, targetCount.get(arm) - 1);- targetCount.set(shoulder, 1);- break;- }- }- }-- // Pass 1.6: the mirror-image collision. SMPL-style rigs name the clavicle- // `left_collar` and the upper arm `left_shoulder`; both normalise onto- // `LeftShoulder`, leaving `LeftArm` vacant and the arm clip unbound. When a- // Shoulder target is contested between a collar/clavicle-spelled joint and a- // shoulder-spelled one, and Arm is free, the shoulder-spelled joint is the- // upper arm — promote it to the Arm bone.- for (const side of ['Left', 'Right']) {- const arm = `${side}Arm`;- const shoulder = `${side}Shoulder`;- if ((targetCount.get(shoulder) || 0) < 2 || (targetCount.get(arm) || 0) > 0) continue;- const contenders = plan.filter((p) => p.canonical === shoulder);- if (!contenders.some((p) => /clavicle|collar/i.test(p.raw))) continue;- for (const p of contenders) {- if (/shoulder/i.test(p.raw) && !/clavicle|collar/i.test(p.raw)) {- p.canonical = arm;- targetCount.set(shoulder, targetCount.get(shoulder) - 1);- targetCount.set(arm, 1);- break;- }- }- }+ // Pass 1.5/1.6: the clavicle/upper-arm collision, resolved for both lanes by+ // the shared resolver below.+ resolveArmShoulderCollisions(plan, {+ isAncestor: (a, b) => isAncestorNode(json, a.index, b.index),+ });// Pass 2: apply. A canonical name is assigned at most once — when two joints// still resolve to the same target after collision resolution (SMPL'sdiff --git a/src/monitor.js b/src/monitor.jsindex 8f190ed65..13932ba9e 100644--- a/src/monitor.js+++ b/src/monitor.js@@ -93,6 +93,15 @@ function mountSpotlight(agent) {el.setAttribute('api-base', 'https://three.ws');el.setAttribute('responsive', '');el.setAttribute('background', 'transparent');+ // Binding by agent-id opts into the full conversational chrome by default,+ // whose name plate and action chips sit exactly where this panel prints the+ // agent's name and links. A monitor tile wants the bare avatar: the footer+ // below already names it and links to the chat.+ el.setAttribute('chat', 'off');+ el.setAttribute('name-plate', 'off');+ // Head-to-mid-thigh crop: a tile is wider than it is tall, and full-body+ // framing spends most of that height on empty room above the avatar.+ el.setAttribute('framing', 'portrait');stage.appendChild(el);spotlightMounted = true;$('spot-name').textContent = agent.name || 'Unnamed agent';diff --git a/src/sign-avatars.js b/src/sign-avatars.jsnew file mode 100644index 000000000..d0c307f64--- /dev/null+++ b/src/sign-avatars.js@@ -0,0 +1,171 @@+// Which avatar does the signing, shared by every sign-language surface.+//+// /sign-language, /asl-alphabet and the mirror drill all put a rig on a+// PoseStage and drive it with the same clips, and they all read one stored+// preference block: a left-handed signer who set that once should never set it+// again, and an avatar chosen on one page is already on stage on the next.+//+// Two rigs ship with the platform, and any avatar on three.ws (yours or a+// public one) can take their place. The clips are rig-independent: they+// retarget onto whatever skeleton is attached, so a custom avatar signs with+// the same vocabulary, speed and dominant hand as the built-ins.++const PREFS_KEY = 'threews:sign-prefs';++// The classic rig is light enough to animate smoothly everywhere, including on+// software renderers, but carries no face blendshapes. The expressive rig ships+// the full ARKit shape set, so the non-manual markers a signed question needs+// (raised brows, furrowed brows, a headshake's set jaw) are actually visible.+// See docs/sign-language.md.+export const BUILT_IN_RIGS = [+ { id: 'classic', label: 'Classic', url: '/avatars/cz.glb' },+ { id: 'expressive', label: 'Expressive face', url: '/avatars/default.glb' },+];++const CUSTOM_PREFIX = 'custom:';++export function loadSignPrefs() {+ try {+ const parsed = JSON.parse(localStorage.getItem(PREFS_KEY));+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+}++/** Merge `patch` into the stored preferences. Private mode just doesn't persist. */+export function saveSignPrefs(patch) {+ try {+ localStorage.setItem(PREFS_KEY, JSON.stringify({ ...loadSignPrefs(), ...patch }));+ } catch {+ /* storage denied: settings live for this page view only */+ }+}++/** A stored custom rig is only usable if it still carries a loadable GLB URL. */+function validCustomRig(rig) {+ if (!rig || typeof rig !== 'object') return null;+ const { id, label, url } = rig;+ if (typeof id !== 'string' || !id.startsWith(CUSTOM_PREFIX)) return null;+ if (typeof url !== 'string' || !/^(https?:\/\/|\/)/.test(url)) return null;+ return { id, label: typeof label === 'string' && label.trim() ? label.trim() : 'Your avatar', url, custom: true };+}++/** The custom avatar the visitor last picked, or null. */+export function customRig(prefs = loadSignPrefs()) {+ return validCustomRig(prefs.customRig);+}++/** The rig to put on stage: the stored pick, falling back to the classic rig. */+export function resolveRig(prefs = loadSignPrefs()) {+ const custom = customRig(prefs);+ if (custom && prefs.avatar === custom.id) return custom;+ return BUILT_IN_RIGS.find((r) => r.id === prefs.avatar) || BUILT_IN_RIGS[0];+}++/** Turn a picked avatar record from the gallery into a rig the stages can mount. */+export function rigFromAvatar(avatar) {+ const url = avatar?.model_url || avatar?.modelUrl || '';+ if (!url) return null;+ const id = `${CUSTOM_PREFIX}${avatar.id || url}`;+ return validCustomRig({ id, label: avatar.name || 'Your avatar', url });+}++/**+ * Render the Avatar pill group: the built-in rigs, then one pill for a custom+ * avatar. The custom pill opens the avatar gallery when it is already active+ * (or when nothing has been picked yet), and simply switches back to the stored+ * pick otherwise, so swapping between a built-in and your own avatar never+ * costs a trip through the gallery.+ *+ * @param {Object} opts+ * @param {Element|string} opts.host Container for the pills.+ * @param {string} opts.optionClass Page's pill class (`sl-opt` / `aa-opt`).+ * @param {Object} opts.active Rig currently on stage.+ * @param {(rig: Object) => Promise<boolean>} opts.apply Mounts the rig; resolves+ * false when the rig could not be used, which restores the previous pill.+ * @param {(msg: string) => void} [opts.onStatus]+ */+export function buildRigPicker({ host, optionClass, active, apply, onStatus }) {+ const root = typeof host === 'string' ? document.querySelector(host) : host;+ if (!root) return;++ let current = active;+ let busy = false;+ const buttons = new Map();++ const press = (rig) => {+ for (const [id, btn] of buttons) btn.setAttribute('aria-pressed', String(id === rig?.id));+ };+ const setBusy = (value) => {+ busy = value;+ for (const btn of buttons.values()) btn.disabled = value;+ };++ const choose = async (rig) => {+ if (busy || !rig || rig.id === current.id) return;+ const previous = current;+ setBusy(true);+ press(rig);+ const ok = await apply(rig);+ if (ok) current = rig;+ else press(previous);+ setBusy(false);+ };++ const addPill = (label, onClick) => {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = optionClass;+ btn.textContent = label;+ btn.setAttribute('aria-pressed', 'false');+ btn.addEventListener('click', onClick);+ root.appendChild(btn);+ return btn;+ };++ for (const rig of BUILT_IN_RIGS) {+ buttons.set(rig.id, addPill(rig.label, () => choose(rig)));+ }++ // The custom pill carries the picked avatar's name once there is one, and+ // keeps its own key in the map so pressed state tracks the avatar behind it.+ let stored = customRig();+ const customBtn = addPill(stored ? stored.label : 'Your avatar…', async () => {+ if (busy) return;+ if (stored && stored.id !== current.id) {+ await choose(stored);+ return;+ }+ setBusy(true);+ let picked = null;+ try {+ const { openAvatarPicker } = await import('./avatar-gallery-picker.js');+ picked = await openAvatarPicker({+ source: 'both',+ title: 'Choose an avatar to sign with',+ selectedId: stored ? stored.id.slice(CUSTOM_PREFIX.length) : '',+ showModes: false,+ ctaLabel: 'Sign with this avatar',+ });+ } catch {+ onStatus?.('The avatar gallery could not open. The built-in rigs still sign everything.');+ }+ setBusy(false);+ const rig = picked ? rigFromAvatar(picked) : null;+ if (!rig) {+ if (picked) onStatus?.('That avatar has no 3D model to load. Pick another.');+ return;+ }+ const previousKey = stored?.id;+ stored = rig;+ saveSignPrefs({ customRig: rig });+ customBtn.textContent = rig.label;+ if (previousKey) buttons.delete(previousKey);+ buttons.set(rig.id, customBtn);+ await choose(rig);+ });+ if (stored) buttons.set(stored.id, customBtn);++ press(current);+}diff --git a/src/sign-language-page.js b/src/sign-language-page.jsindex ad801cb75..5fe5b51cd 100644--- a/src/sign-language-page.js+++ b/src/sign-language-page.js@@ -13,37 +13,9 @@ import { SignSpeaker, scaledTiming } from './sign-speech.js';import { normalizeWord } from './fingerspelling.js';import { SIGNS, signGloss, signLookup } from './sign-dictionary.js';import { initSignApiConsole } from './sign-api-console.js';+import { buildRigPicker, loadSignPrefs, resolveRig, saveSignPrefs } from './sign-avatars.js';import { log } from './shared/log.js';-// Two hero rigs, because signing has two halves and no one avatar shows both-// best. The classic rig is light enough to animate smoothly everywhere,-// including on software renderers, but carries no face blendshapes. The-// expressive rig ships the full ARKit shape set, so the non-manual markers a-// signed question needs (raised brows, furrowed brows, a headshake's set jaw)-// are actually visible on it. See docs/sign-language.md.-const AVATARS = [- { id: 'classic', label: 'Classic', url: '/avatars/cz.glb' },- { id: 'expressive', label: 'Expressive face', url: '/avatars/default.glb' },-];--// Speed, hand, and rig survive a reload: a left-handed signer should not have-// to re-declare themselves on every visit.-const PREFS_KEY = 'threews:sign-prefs';-function loadPrefs() {- try {- return JSON.parse(localStorage.getItem(PREFS_KEY)) || {};- } catch {- return {};- }-}-function savePrefs(prefs) {- try {- localStorage.setItem(PREFS_KEY, JSON.stringify(prefs));- } catch {- /* private mode: settings just don't persist */- }-}-// Signing speed. Learners and many Deaf viewers want it slower, and signing is// content, so it cannot simply be reduced away like decorative motion.const SPEEDS = [@@ -63,8 +35,10 @@ async function boot() {const stageHost = $('#sl-stage');if (!stageHost) return;- const prefs = loadPrefs();- let avatar = AVATARS.find((a) => a.id === prefs.avatar) || AVATARS[0];+ // Speed, hand, and rig survive a reload and carry across every sign surface:+ // a left-handed signer should not have to re-declare themselves per page.+ const prefs = loadSignPrefs();+ let avatar = resolveRig(prefs);let stage = null;let speaker = null;let heroTimer = 0;@@ -104,7 +78,7 @@ async function boot() {};const applySetting = (fn) => {fn();- savePrefs({ rate, dominant, avatar: avatar.id });+ saveSignPrefs({ rate, dominant, avatar: avatar.id });rebuildSpeaker();replay();};@@ -283,22 +257,39 @@ async function boot() {);// Switching rigs replaces the whole stage: the clips are rig-independent// (they retarget on attach), so the speaker just rebuilds against the new- // skeleton and whatever was signing resumes on the new avatar.- let switchingRig = false;- buildOptions('#sl-rig', AVATARS, (a) => a.id === avatar.id, async (picked) => {- if (switchingRig || picked.id === avatar.id) return;- switchingRig = true;- avatar = picked;- savePrefs({ rate, dominant, avatar: avatar.id });- setStatus('Loading avatar…');- const ok = await mountStage();- switchingRig = false;- if (!ok) return;- if (picked.id === 'expressive') {- setStatus('This avatar has a face: questions raise the brows, negation furrows them.');- }- if (heroActive && !reducedMotion) heroTick();- else replay();+ // skeleton and whatever was signing resumes on the new avatar. That is why+ // any avatar on three.ws can take the hero's place, not only the two rigs+ // that ship with it.+ buildRigPicker({+ host: '#sl-rig',+ optionClass: 'sl-opt',+ active: avatar,+ onStatus: setStatus,+ apply: async (picked) => {+ const previous = avatar;+ avatar = picked;+ saveSignPrefs({ rate, dominant, avatar: avatar.id });+ setStatus('Loading avatar…');+ if (!(await mountStage())) {+ // A rig with no usable skeleton cannot sign, and leaving a mute+ // avatar on stage would read as the feature being broken. Put the+ // working one back and say which one is signing.+ avatar = previous;+ saveSignPrefs({ avatar: avatar.id });+ const restored = await mountStage();+ setStatus(`${picked.label} can’t sign: it has no usable skeleton. ${previous.label} is back on stage.`);+ if (restored && heroActive && !reducedMotion) heroTick();+ return false;+ }+ if (picked.id === 'expressive') {+ setStatus('This avatar has a face: questions raise the brows, negation furrows them.');+ } else if (picked.custom) {+ setStatus(`${picked.label} is signing. Speed and signing hand carry over.`);+ }+ if (heroActive && !reducedMotion) heroTick();+ else replay();+ return true;+ },});// ── Vocabulary: every word with a real sign, playable ─────────────────────@@ -357,7 +348,7 @@ async function boot() {if (wanted !== dominant || speed !== rate) {dominant = wanted;rate = speed;- savePrefs({ rate, dominant, avatar: avatar.id });+ saveSignPrefs({ rate, dominant, avatar: avatar.id });syncPills('#sl-hand', (btn) => btn.textContent.toLowerCase().startsWith(hand));syncPills('#sl-speed', (btn) => btn.textContent === `${speed}×`);rebuildSpeaker();diff --git a/src/sign-mirror-page.js b/src/sign-mirror-page.jsindex 62696e371..29192ed81 100644--- a/src/sign-mirror-page.js+++ b/src/sign-mirror-page.js@@ -15,13 +15,9 @@ import { buildFingerspellingClip, normalizeWord } from './fingerspelling.js';import { LETTERS, LETTER_NOTES } from './asl-alphabet-data.js';import { GradeSmoother, gradeHandshape, rankHandshapes } from './sign-grader.js';import { HAND_CONNECTIONS, handshapeLandmarks, projectHand } from './sign-hand-model.js';+import { loadSignPrefs, resolveRig, saveSignPrefs } from './sign-avatars.js';import { log } from './shared/log.js';-const AVATARS = [- { id: 'classic', label: 'Classic', url: '/avatars/cz.glb' },- { id: 'expressive', label: 'Expressive face', url: '/avatars/default.glb' },-];-const PREFS_KEY = 'threews:sign-prefs';const PROGRESS_KEY = 'threews:sign-mirror-progress';// Letters whose handshape is identical to another letter's: in ASL they differ@@ -86,9 +82,11 @@ async function boot() {const stageHost = $('#sm-stage');if (!stageHost) return;- const prefs = readJSON(PREFS_KEY, {});+ const prefs = loadSignPrefs();const progress = readJSON(PROGRESS_KEY, { passed: {}, best: {} });- let avatar = AVATARS.find((a) => a.id === prefs.avatar) || AVATARS[0];+ // The rig, the signing hand and any custom avatar come from the same stored+ // block /sign-language and /asl-alphabet write.+ let avatar = resolveRig(prefs);let dominant = prefs.dominant === 'Left' ? 'Left' : 'Right';let stage = null;@@ -442,7 +440,7 @@ async function boot() {btn.addEventListener('click', () => {dominant = btn.dataset.hand === 'Left' ? 'Left' : 'Right';handBtns.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.hand === dominant)));- writeJSON(PREFS_KEY, { ...readJSON(PREFS_KEY, {}), dominant });+ saveSignPrefs({ dominant });drawTarget(current);showOnAvatar(current);});diff --git a/tests/api/avatar-render-expression-report.test.js b/tests/api/avatar-render-expression-report.test.jsindex 6ce8b6621..f8befa3bc 100644--- a/tests/api/avatar-render-expression-report.test.js+++ b/tests/api/avatar-render-expression-report.test.js@@ -1,5 +1,5 @@// Regression lock for the silent-expression defect on /api/avatar/render-// (ISSUES.md item 9, second defect): a model with zero morph targets, or with+// (filed with the Draco transcode item, since closed): a model with zero morph targets, or with// morphs named differently from the request, rendered a clean 200 with none of// the requested expression applied and gave the caller no way to tell.// applyExpression now returns { requested, missing }, the page publishes it asdiff --git a/tests/sign-avatars.test.js b/tests/sign-avatars.test.jsnew file mode 100644index 000000000..681f80597--- /dev/null+++ b/tests/sign-avatars.test.js@@ -0,0 +1,133 @@+// @vitest-environment jsdom+//+// The Avatar control shared by /sign-language, /asl-alphabet and the mirror+// drill. Before this module those pages each hardcoded the same two rigs, so a+// visitor could watch the platform's avatars sign but never their own.+//+// The rules that matter to a person using it: a custom avatar persists across+// pages, a rig that cannot sign never gets to stay on stage (the pill snaps+// back to the one that was working), and nothing in localStorage can put a+// junk URL in front of the GLB loader.++import { beforeEach, describe, expect, it, vi } from 'vitest';+import {+ BUILT_IN_RIGS,+ buildRigPicker,+ customRig,+ loadSignPrefs,+ resolveRig,+ rigFromAvatar,+ saveSignPrefs,+} from '../src/sign-avatars.js';++const CUSTOM = { id: 'custom:av_9', label: 'Nova', url: 'https://three.ws/cdn/u/av_9/model.glb' };++beforeEach(() => {+ localStorage.clear();+ document.body.innerHTML = '<div id="rig"></div>';+});++const host = () => document.getElementById('rig');+const pills = () => [...host().querySelectorAll('button')];+const pressed = () => pills().find((b) => b.getAttribute('aria-pressed') === 'true')?.textContent;++describe('preferences', () => {+ it('merges rather than replacing, so one page cannot drop another page setting', () => {+ saveSignPrefs({ dominant: 'Left' });+ saveSignPrefs({ rate: 0.5 });+ expect(loadSignPrefs()).toMatchObject({ dominant: 'Left', rate: 0.5 });+ });++ it('survives unreadable storage', () => {+ localStorage.setItem('threews:sign-prefs', '{not json');+ expect(loadSignPrefs()).toEqual({});+ expect(resolveRig()).toEqual(BUILT_IN_RIGS[0]);+ });+});++describe('resolveRig', () => {+ it('defaults to the classic rig', () => {+ expect(resolveRig({})).toEqual(BUILT_IN_RIGS[0]);+ });++ it('returns the stored custom avatar when it is the active pick', () => {+ expect(resolveRig({ avatar: CUSTOM.id, customRig: CUSTOM })).toMatchObject({ url: CUSTOM.url, custom: true });+ });++ it('keeps a stored custom avatar available while a built-in is on stage', () => {+ const prefs = { avatar: 'expressive', customRig: CUSTOM };+ expect(resolveRig(prefs)).toEqual(BUILT_IN_RIGS[1]);+ expect(customRig(prefs)).toMatchObject({ label: 'Nova' });+ });++ it('rejects a stored rig with a non-http URL', () => {+ const poisoned = { avatar: 'custom:x', customRig: { id: 'custom:x', label: 'x', url: 'javascript:alert(1)' } };+ expect(customRig(poisoned)).toBeNull();+ expect(resolveRig(poisoned)).toEqual(BUILT_IN_RIGS[0]);+ });+});++describe('rigFromAvatar', () => {+ it('reads the gallery record', () => {+ expect(rigFromAvatar({ id: 'av_9', name: 'Nova', model_url: CUSTOM.url })).toEqual({+ id: 'custom:av_9',+ label: 'Nova',+ url: CUSTOM.url,+ custom: true,+ });+ });++ it('refuses an avatar with no model', () => {+ expect(rigFromAvatar({ id: 'av_9', name: 'Nova' })).toBeNull();+ });+});++describe('buildRigPicker', () => {+ it('renders the built-ins plus one custom pill, pressing the active rig', () => {+ buildRigPicker({ host: '#rig', optionClass: 'sl-opt', active: BUILT_IN_RIGS[1], apply: async () => true });+ expect(pills().map((b) => b.textContent)).toEqual(['Classic', 'Expressive face', 'Your avatar…']);+ expect(pressed()).toBe('Expressive face');+ });++ it('names the custom pill after the stored avatar and switches to it without reopening the gallery', async () => {+ saveSignPrefs({ customRig: CUSTOM });+ const apply = vi.fn().mockResolvedValue(true);+ buildRigPicker({ host: '#rig', optionClass: 'sl-opt', active: BUILT_IN_RIGS[0], apply });++ const custom = pills()[2];+ expect(custom.textContent).toBe('Nova');+ custom.click();+ await vi.waitFor(() => expect(apply).toHaveBeenCalled());+ expect(apply.mock.calls[0][0]).toMatchObject({ url: CUSTOM.url, custom: true });+ expect(pressed()).toBe('Nova');+ });++ it('restores the previous pill when a rig cannot sign', async () => {+ saveSignPrefs({ customRig: CUSTOM });+ buildRigPicker({ host: '#rig', optionClass: 'sl-opt', active: BUILT_IN_RIGS[0], apply: async () => false });++ pills()[2].click();+ await vi.waitFor(() => expect(pressed()).toBe('Classic'));+ });++ it('ignores a click on the rig already on stage', async () => {+ const apply = vi.fn().mockResolvedValue(true);+ buildRigPicker({ host: '#rig', optionClass: 'sl-opt', active: BUILT_IN_RIGS[0], apply });+ pills()[0].click();+ await Promise.resolve();+ expect(apply).not.toHaveBeenCalled();+ });++ it('locks every pill while a rig is loading, so a double-click cannot race two mounts', async () => {+ let release;+ const apply = vi.fn(() => new Promise((resolve) => { release = resolve; }));+ buildRigPicker({ host: '#rig', optionClass: 'sl-opt', active: BUILT_IN_RIGS[0], apply });++ pills()[1].click();+ await vi.waitFor(() => expect(pills()[0].disabled).toBe(true));+ pills()[2].click();+ release(true);+ await vi.waitFor(() => expect(pills()[0].disabled).toBe(false));+ expect(apply).toHaveBeenCalledTimes(1);+ });+});