Skip to content

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

chore: sync working tree

nirholas8aec631ac3d0
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index b9a25d2fb..b7dd783dd 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -199,6 +199,11 @@ const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000; // 10m — transient 429
const AUTH_COOLDOWN_MS = 30 * 60_000; // 30m — bad/expired key on this provider only
const SERVER_COOLDOWN_MS = 2 * 60_000; // 2m — provider 5xx
const NETWORK_COOLDOWN_MS = 30_000; // 30s — fetch threw (DNS/connection blip)
+// A lane refusing ONE call shape is demoted for that method alone, never for the
+// lane. Short, because a policy block is a provider setting that can change and
+// re-probing costs exactly one request that transparently fails over — unlike a
+// quota probe, which burns the very budget it is testing.
+const METHOD_DEMOTION_MS = 15 * 60_000; // 15m — this lane refuses this method
const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';
const PUBLIC_DEVNET = 'https://api.devnet.solana.com';
@@ -343,14 +348,34 @@ function publishCooldowns(now) {
.catch(() => {});
}
-// A provider refusing one call shape (a blocked method, an unsupported filter, an
-// unindexed account key) rather than the caller. Endpoint-scoped credentials are
-// not the problem, so the lane must survive the refusal; only this request fails
-// over. Kept separate from isProviderTierError, which matches paid-plan gating.
-function isBlockedCallShape(bodyText) {
- return /request blocked|blocked parameter|excluded from account secondary indexes|method .*(not supported|is not available|disabled)/i.test(
- bodyText || '',
- );
+// Every way a provider says "not THIS call" while staying perfectly healthy for
+// every other call. Three distinct phrasings live here because three distinct
+// mechanisms produce them, and all three were previously scattered across two
+// near-duplicate matchers that disagreed about which strings counted:
+//
+// • POLICY BLOCK — the node is configured to refuse a shape.
+// PublicNode getTokenAccountsByOwner → `Request blocked. Details: blocked
+// parameter: params.1.programId`; PublicNode getProgramAccounts → `… excluded
+// from account secondary indexes; this RPC method unavailable for key`;
+// MagicBlock getProgramAccounts → `Your IP or provider is blocked from this
+// endpoint`.
+// • TIER GATE — the method exists but the keyless/free plan may not call it.
+// Tatum getBalance / getSignaturesForAddress → `available for paid plans only`.
+// • METHOD DISABLED — an operator switched the shape off on that node.
+//
+// All three are lane-and-method specific: the next lane serves the same call
+// normally, and this lane serves every other call normally. That is precisely the
+// signature of a METHOD demotion, never of a lane bench, and never of an auth
+// fault. Matching on wording (not on the JSON-RPC code) is deliberate: PublicNode
+// returns -32602 for a policy block, the same code a genuine invalid-params error
+// uses, and a genuine invalid-params error must NOT demote anything because every
+// lane would reject it identically.
+const METHOD_REFUSAL =
+ /request blocked|blocked parameter|excluded from account secondary indexes|this rpc method unavailable|blocked from this endpoint|method .*(?:not supported|is not available|disabled)|not available for anonymous access|available for paid plans only|upgrade your subscription|please register at/i;
+
+/** True when `text` is a provider refusing one call shape rather than the caller. */
+export function isMethodRefusal(text) {
+ return METHOD_REFUSAL.test(text || '');
}
function cooldownMsFor(status, bodyText) {
@@ -381,7 +406,13 @@ function cooldownMsFor(status, bodyText) {
// primary was evicted by its own routine traffic and the rotation cascaded onto
// the exhausted paid lanes. The endpoint is fine, this one request is not: fail
// over for the call, keep the lane.
- if (status === 403 && isBlockedCallShape(bodyText)) return NETWORK_COOLDOWN_MS;
+ //
+ // The rotating fetch no longer reaches this branch — it recognises the refusal
+ // first and demotes the METHOD instead of the lane (see markMethodDemotion), so
+ // the lane keeps serving every other call shape with no cooldown at all. The
+ // branch stays because markEndpointCooldown is exported and must still classify
+ // a blocked call shape as the cheapest window rather than a 30m auth bench.
+ if (status === 403 && isMethodRefusal(bodyText)) return NETWORK_COOLDOWN_MS;
if (status === 401 || status === 403) return AUTH_COOLDOWN_MS;
// 404/410: the endpoint URL is dead or misrouted (expired Quicknode/Alchemy
// app, wrong path) — a persistent misconfiguration, so park it like an auth
@@ -396,6 +427,99 @@ export function isEndpointCooling(url) {
return (_endpointCooldown.get(url) || 0) > Date.now();
}
+// ---------------------------------------------------------------------------
+// Per-method lane capability
+// ---------------------------------------------------------------------------
+// The lane cooldown above is the right tool for a provider that cannot serve
+// ANY call — quota spent, key rejected, node down. It is the wrong tool for the
+// far more common free-lane failure: a provider that serves most of the chain
+// happily and refuses exactly one call shape. PublicNode answers getBalance,
+// getLatestBlockhash and getSignatureStatuses perfectly while refusing
+// getTokenAccountsByOwner with a programId filter and getProgramAccounts
+// outright; MagicBlock serves the token filters and IP-blocks
+// getProgramAccounts. Parking the whole lane on those refusals meant a lane's
+// own routine traffic evicted it, and the rotation cascaded down onto the
+// exhausted paid lanes that the free chain exists to protect.
+//
+// So a method-level refusal demotes (url, method) and nothing else: the lane
+// stays in rotation for every other shape, and only this shape skips it. It is
+// never an auth fault, so it never earns the 30m auth bench and is never
+// published as a fleet-wide bench.
+//
+// Deliberately process-local, unlike the quota breaker. Re-discovering a method
+// block on a cold instance costs ONE request that transparently fails over.
+// Re-discovering a quota block costs a request against a plan that is already
+// over its cap, which is what keeps a daily cap pinned — that asymmetry is the
+// whole reason the quota verdict is shared and this one is not.
+const _methodDemotion = new Map(); // `${url}${method}` → expiry ms
+
+const methodKey = (url, method) => `${url}${method}`;
+
+/**
+ * The JSON-RPC method names carried by a request body, deduped. Handles the
+ * single-call and batch forms web3.js emits. Returns [] for an unreadable body,
+ * which makes every capability check a no-op — an unparseable request must never
+ * silently skip a healthy lane.
+ */
+export function rpcMethodsFromBody(body) {
+ if (typeof body !== 'string' || !body) return [];
+ let parsed;
+ try {
+ parsed = JSON.parse(body);
+ } catch {
+ return [];
+ }
+ const items = Array.isArray(parsed) ? parsed : [parsed];
+ const out = [];
+ for (const item of items) {
+ const m = item && typeof item === 'object' ? item.method : null;
+ if (typeof m === 'string' && m && !out.includes(m)) out.push(m);
+ }
+ return out;
+}
+
+/** True when `url` is currently demoted for `method`. */
+export function isMethodDemoted(url, method) {
+ return (_methodDemotion.get(methodKey(url, method)) || 0) > Date.now();
+}
+
+/**
+ * True when `url` is demoted for ANY method in `methods`. A JSON-RPC batch is
+ * atomic from the caller's side: if one member would be refused, the whole batch
+ * comes back partially broken, so the lane is skipped for the batch.
+ */
+export function isAnyMethodDemoted(url, methods) {
+ return methods.some((m) => isMethodDemoted(url, m));
+}
+
+/**
+ * Demote `url` for each of `methods` for METHOD_DEMOTION_MS. Returns the window
+ * so the caller can log it. Never touches the lane cooldown.
+ */
+export function markMethodDemotion(url, methods, now = Date.now()) {
+ const until = now + METHOD_DEMOTION_MS;
+ for (const m of methods) _methodDemotion.set(methodKey(url, m), until);
+ return METHOD_DEMOTION_MS;
+}
+
+/**
+ * Every live (url, method) demotion, for the ops surface. Expired entries are
+ * dropped as they are read, which is the only reaping this map needs: the key
+ * space is bounded by lanes × methods.
+ */
+export function rpcMethodDemotions(now = Date.now()) {
+ const out = [];
+ for (const [key, until] of _methodDemotion) {
+ if (until <= now) {
+ _methodDemotion.delete(key);
+ continue;
+ }
+ const [url, method] = key.split('');
+ out.push({ url, method, remainingMs: until - now });
+ }
+ return out;
+}
+
/**
* Park `url` in cooldown for a window sized to the failure class. Returns the
* chosen cooldown in ms so callers can log it. `bodyText` (a 429 body or error
@@ -635,17 +759,8 @@ const PROVIDER_CAPACITY_CODES = new Set([
429, // Alchemy: monthly capacity exceeded, reported as a JSON-RPC code
]);
-// A provider that gates a method behind its paid/registered tier answers with a
-// method-shaped JSON-RPC error (Tatum returns -32601-class codes for
-// `getBalance` / `getSignaturesForAddress` on the keyless lane). The code alone
-// is indistinguishable from a genuinely absent method — which is deterministic
-// and must NOT rotate — so this matches the plan-gate phrasing instead. Unlike a
-// missing method, a tier gate is provider-specific: the next lane serves the call
-// normally, so failing over is the correct disposition. Left unclassified these
-// surfaced straight to the caller and blinded every getSignaturesForAddress
-// consumer (the ring leak scanner) and every getBalance consumer the moment the
-// rotation cascaded past the keyed lanes onto Tatum.
-// A keyless lane can also refuse a method by POLICY rather than by tier, and the
+// A provider that refuses one call shape — by paid-tier gate, by policy, or by
+// switching the method off — answers with a method-shaped JSON-RPC error, and the
// dangerous variant answers HTTP 200 so no status-driven rotation fires. Measured
// on the live free lanes 2026-07-30:
// • PublicNode getProgramAccounts → 200 + {code:-32010, "… excluded from account
@@ -655,19 +770,19 @@ const PROVIDER_CAPACITY_CODES = new Set([
// invalid params, so the code alone would wrongly read as deterministic
// • MagicBlock getProgramAccounts → {code:403, "Your IP or provider is blocked
// from this endpoint"}
-// All three are provider-specific: another lane serves the same call normally, so
-// rotating is correct. Unclassified, the 200-status one surfaced straight to the
-// caller and hard-failed the $THREE holder-gating and token-balance readers
-// (api/_lib/balances.js, api/_lib/coin/holders.js, api/_lib/embed-gate.js,
-// api/scene/gate-check.js) whenever the rotation was sitting on that lane.
-const PROVIDER_POLICY_BLOCK = /excluded from account secondary indexes|this rpc method unavailable|request blocked|blocked parameter|blocked from this endpoint/i;
-
+// • Tatum getBalance / getSignaturesForAddress → -16401 "available for paid
+// plans only", a code otherwise indistinguishable from a genuinely absent
+// method (which IS deterministic and must never rotate)
+// Every one is lane-and-method specific, so the disposition is: fail this request
+// over to the next lane, and demote THIS method on THIS lane — never the lane.
+// Unclassified, the 200-status ones surfaced straight to the caller and hard-failed
+// the $THREE holder-gating and token-balance readers (api/_lib/balances.js,
+// api/_lib/coin/holders.js, api/_lib/embed-gate.js, api/scene/gate-check.js)
+// whenever the rotation was sitting on that lane; classified as a LANE fault, they
+// benched a healthy free primary on its own routine traffic. isMethodRefusal (the
+// single matcher, defined near the cooldown table) decides the class.
function isProviderTierError(rpcError) {
- const message = String(rpcError?.message || '');
- if (PROVIDER_POLICY_BLOCK.test(message)) return true;
- return /not available for anonymous access|available for paid plans only|upgrade your subscription|please register at/i.test(
- message,
- );
+ return isMethodRefusal(String(rpcError?.message || ''));
}
function isProviderCapacityError(rpcError) {
diff --git a/api/_lib/x402/wallet-balance-monitor.js b/api/_lib/x402/wallet-balance-monitor.js
index 6324e36dc..2a6d18ccf 100644
--- a/api/_lib/x402/wallet-balance-monitor.js
+++ b/api/_lib/x402/wallet-balance-monitor.js
@@ -74,6 +74,10 @@ const log = logger('x402-wallet-balance-monitor');
// • treasury — UNBOUNDED. It only receives ring payments and gets swept back
// to the payer by the rebalancer, so a low balance is its healthy resting
// state, not an alert condition.
+// The sponsor also gets a RUNWAY check (sponsor-runway.js): a floor breach says
+// the rail is already dead, and by then the Solana accept has been withdrawn from
+// every 402 challenge. The runway alert fires days earlier, off a burn rate
+// measured from the settle ledger on every run.
const RING_SOL_FLOOR_LAMPORTS = Math.round(SPONSOR_SOL_FLOOR_LAMPORTS * 1.5);
const RING_PAYER_USDC_FLOOR_ATOMIC = Number(
env.X402_RING_PAYER_USDC_FLOOR_ATOMIC || process.env.X402_RING_PAYER_USDC_FLOOR_ATOMIC || 5_000_000,
@@ -485,11 +489,16 @@ export async function run(ctx = {}) {
threshold_usdc: ALERT_THRESHOLD_USDC,
usdc_delta: usdcDelta,
spend_rate_usdc_hr: spendRateUsdcHr,
- ring: ring.configured ? { wallets: ring.wallets, breaches: ring.breaches } : null,
+ ring: ring.configured
+ ? { wallets: ring.wallets, breaches: ring.breaches, sponsor_runway: ring.sponsorRunway }
+ : null,
};
+ const runwayNote = ring.sponsorRunway && ring.sponsorRunway.runway_days_to_floor != null
+ ? ` runway:${ring.sponsorRunway.runway_days_to_floor}d/${ring.sponsorRunway.status}`
+ : '';
const ringNote = ring.configured
- ? ` ring:${ring.breaches.length ? `BREACH(${ring.breaches.length})` : 'ok'}`
+ ? ` ring:${ring.breaches.length ? `BREACH(${ring.breaches.length})` : 'ok'}${runwayNote}`
: '';
return {
@@ -520,5 +529,9 @@ export const WALLET_BALANCE = Object.freeze({
solFloorLamports: RING_SOL_FLOOR_LAMPORTS,
payerUsdcFloorAtomic: RING_PAYER_USDC_FLOOR_ATOMIC,
sponsorHardFloorLamports: SPONSOR_SOL_FLOOR_LAMPORTS,
+ // Runway watch on the same wallet: measured burn window, and the days-left
+ // threshold that pages. Both env-overridable without a redeploy.
+ sponsorBurnWindowDays: SPONSOR_BURN_WINDOW_DAYS,
+ sponsorRunwayAlertDays: SPONSOR_RUNWAY_ALERT_DAYS,
},
});
diff --git a/api/ops/payment-outcomes.js b/api/ops/payment-outcomes.js
index a5561a2f6..e6349b664 100644
--- a/api/ops/payment-outcomes.js
+++ b/api/ops/payment-outcomes.js
@@ -11,8 +11,9 @@
// split, top failure reasons, settled volume.
// ring_settle : gatherX402SettleHealth(), the outbound settle-success-rate
// sensor (3h window, rail-fault allowlist).
-// sponsor : fee-wallet SOL vs its floor plus measured burn (7d of
-// fee_lamports) and the runway in days that implies.
+// sponsor : fee-wallet SOL vs its floor plus measured burn (fee_lamports
+// over a stated window) and the runway in days that implies,
+// including the threshold the scheduled monitor alerts on.
//
// Auth: authorizeOps (admin session, or x-ops-secret / OPS_SECRET): the same
// gate as /api/ops/health, so the /admin/ops dashboard reuses its stored
@@ -125,34 +126,36 @@ async function inboundBoard() {
}
async function sponsorBoard() {
- // Balances via the ring monitor with alerting disabled: a dashboard READ
- // must never page anyone; the scheduled monitor owns alerting.
+ // Balances AND runway via the ring monitor with alerting disabled: a dashboard
+ // READ must never page anyone; the scheduled monitor owns alerting. The burn
+ // and runway are computed there (api/_lib/x402/sponsor-runway.js) so the number
+ // this board renders and the number the alert fires on are the same number,
+ // measured the same way, over the same window.
const ring = await checkRingWallets({ sendAlert: async () => {} });
const sponsor = ring.wallets.find((w) => w.role === 'sponsor') || null;
+ const runway = ring.sponsorRunway || null;
- // Measured burn, not a remembered constant: fee_lamports over settled
- // settles for 7 days (ISSUES.md item 6 records the folklore number being
- // wrong by roughly 10x, so derive it every time).
- const [burn] = await sql`
- SELECT count(*)::int AS settles,
- coalesce(sum(fee_lamports), 0)::bigint AS lamports
- FROM x402_self_facilitator_log
- WHERE ts >= now() - interval '7 days'
- AND action = 'settle' AND ok = true
- `;
- const burnSolPerDay = Number(burn?.lamports || 0) / 7 / 1e9;
- const sol = sponsor?.sol ?? null;
return {
configured: Boolean(sponsor?.address),
address: sponsor?.address || null,
- sol,
+ sol: sponsor?.sol ?? null,
+ // The ring's 1.5x watch floor (what `below_floor` compares against) and the
+ // facilitator's hard floor (where settling actually stops) are different
+ // numbers, and conflating them is how a "safe" reading precedes an outage.
sol_floor: sponsor?.sol_floor ?? null,
+ settle_floor_sol: runway?.floor_sol ?? null,
below_floor: Boolean(sponsor?.sol_low),
- settles_7d: burn?.settles ?? 0,
- burn_sol_per_day_7d: Math.round(burnSolPerDay * 1e6) / 1e6,
- runway_days: sol != null && burnSolPerDay > 0
- ? Math.round((sol / burnSolPerDay) * 10) / 10
- : null,
+ // Measured burn, never a remembered constant: fee_lamports over successful
+ // settles in the stated window (ISSUES.md item 6 records the folklore number
+ // being wrong by roughly 10x, so it is derived on every read).
+ burn_window_days: runway?.burn_window_days ?? null,
+ settles_in_window: runway?.settles_in_window ?? 0,
+ burn_sol_per_day: runway?.burn_sol_per_day ?? null,
+ runway_days: runway?.runway_days ?? null,
+ runway_days_to_floor: runway?.runway_days_to_floor ?? null,
+ runway_alert_days: runway?.alert_days ?? null,
+ runway_status: runway?.status ?? 'unknown',
+ runway_reason: runway?.reason ?? null,
};
}
diff --git a/pages/tour-atlas.html b/pages/tour-atlas.html
index dd53e135b..f2c314fe9 100644
--- a/pages/tour-atlas.html
+++ b/pages/tour-atlas.html
@@ -24,39 +24,26 @@
<meta name="twitter:description" content="185 stops of the three.ws guided tour, each one a real screenshot with the feature circled." />
<meta name="twitter:image" content="https://three.ws/api/page-og?s=main&amp;t=Tour+Atlas&amp;d=Every+feature+on+three.ws%2C+photographed+on+the+live+site+with+the+feature+circled.&amp;p=%2Ftour%2Fatlas" />
<style>
+ /* Thin alias layer over the canonical vocabulary in public/tokens.css —
+ the sanctioned pattern (same as --nxt-* / --nv-*): every value resolves
+ to a primitive via var(), so nothing here forks the palette and the whole
+ page flips under [data-theme='light'] with no second block to maintain. */
:root {
- --ta-bg: #07080c;
- --ta-panel: rgba(17, 19, 27, 0.86);
- --ta-panel-2: rgba(255, 255, 255, 0.028);
- --ta-border: rgba(255, 255, 255, 0.09);
- --ta-border-2: rgba(255, 255, 255, 0.17);
- --ta-text: #e9ebf2;
- --ta-muted: #8b91a3;
- --ta-faint: #5d6374;
- --ta-accent: #7aa2ff;
- --ta-accent-soft: rgba(122, 162, 255, 0.14);
- --ta-good: #34d399;
- --ta-warn: #fbbf24;
- --ta-bad: #f87171;
- --ta-shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 12px 34px rgba(0, 0, 0, 0.34);
- --ta-radius: 14px;
- }
-
- html[data-theme='light'] {
- --ta-bg: #f7f8fb;
- --ta-panel: #ffffff;
- --ta-panel-2: rgba(15, 18, 30, 0.026);
- --ta-border: rgba(15, 18, 30, 0.1);
- --ta-border-2: rgba(15, 18, 30, 0.2);
- --ta-text: #131722;
- --ta-muted: #5b6274;
- --ta-faint: #838a9c;
- --ta-accent: #3b62d0;
- --ta-accent-soft: rgba(59, 98, 208, 0.1);
- --ta-good: #0f9d66;
- --ta-warn: #b45309;
- --ta-bad: #b91c1c;
- --ta-shadow: 0 1px 2px rgba(15, 18, 30, 0.06), 0 10px 30px rgba(15, 18, 30, 0.07);
+ --ta-bg: var(--bg-0);
+ --ta-panel: var(--surface-glass);
+ --ta-panel-2: var(--surface-1);
+ --ta-border: var(--stroke);
+ --ta-border-2: var(--stroke-strong);
+ --ta-text: var(--ink);
+ --ta-muted: var(--ink-dim);
+ --ta-faint: var(--ink-faint);
+ --ta-accent: var(--accent);
+ --ta-accent-soft: var(--accent-soft);
+ --ta-good: var(--success);
+ --ta-warn: var(--warn);
+ --ta-bad: var(--danger);
+ --ta-shadow: var(--shadow-2);
+ --ta-radius: var(--radius-lg);
}
.ta-wrap {
@@ -70,7 +57,7 @@
.ta-head { margin-bottom: 28px; }
.ta-eyebrow {
display: inline-flex; align-items: center; gap: 8px;
- font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 600 11px/1 var(--font-mono);
letter-spacing: 0.1em; text-transform: uppercase;
color: var(--ta-accent); margin-bottom: 14px;
}
@@ -79,12 +66,12 @@
background: var(--ta-accent); box-shadow: 0 0 0 4px var(--ta-accent-soft);
}
.ta-h1 {
- font: 700 clamp(30px, 5vw, 46px)/1.08 Inter, system-ui, sans-serif;
+ font: 700 clamp(30px, 5vw, 46px)/1.08 var(--font-body);
letter-spacing: -0.03em; margin: 0 0 14px;
}
.ta-lede {
max-width: 68ch; margin: 0 0 4px;
- font: 400 16px/1.65 Inter, system-ui, sans-serif; color: var(--ta-muted);
+ font: 400 16px/1.65 var(--font-body); color: var(--ta-muted);
}
.ta-lede a { color: var(--ta-accent); text-decoration: none; border-bottom: 1px solid var(--ta-accent-soft); }
.ta-lede a:hover { border-bottom-color: currentColor; }
@@ -99,11 +86,11 @@
border-radius: var(--ta-radius); padding: 14px 16px;
}
.ta-stat-n {
- font: 700 24px/1 Inter, system-ui, sans-serif; letter-spacing: -0.02em;
+ font: 700 24px/1 var(--font-body); letter-spacing: -0.02em;
display: block; margin-bottom: 6px;
}
.ta-stat-l {
- font: 500 11px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 500 11px/1.3 var(--font-mono);
letter-spacing: 0.06em; text-transform: uppercase; color: var(--ta-faint);
}
.ta-stat[data-tone='good'] .ta-stat-n { color: var(--ta-good); }
@@ -111,12 +98,12 @@
.ta-stat[data-tone='bad'] .ta-stat-n { color: var(--ta-bad); }
.ta-provenance {
- margin: 14px 0 0; font: 400 13px/1.6 Inter, system-ui, sans-serif; color: var(--ta-faint);
+ margin: 14px 0 0; font: 400 13px/1.6 var(--font-body); color: var(--ta-faint);
}
.ta-provenance code {
- font: 500 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 500 12px/1 var(--font-mono);
background: var(--ta-panel-2); border: 1px solid var(--ta-border);
- border-radius: 5px; padding: 2px 6px;
+ border-radius: var(--radius-sm); padding: 2px 6px;
}
/* ── Toolbar ──────────────────────────────────────────────────────── */
@@ -129,9 +116,9 @@
.ta-search {
flex: 1 1 260px; min-width: 0;
background: var(--ta-panel); color: var(--ta-text);
- border: 1px solid var(--ta-border); border-radius: 10px;
- padding: 11px 14px; font: 400 14px/1.2 Inter, system-ui, sans-serif;
- transition: border-color 0.16s ease, box-shadow 0.16s ease;
+ border: 1px solid var(--ta-border); border-radius: var(--radius-md);
+ padding: 11px 14px; font: 400 14px/1.2 var(--font-body);
+ transition: border-color var(--duration-fast) var(--ease-standard), box-shadow var(--duration-fast) var(--ease-standard);
}
.ta-search::placeholder { color: var(--ta-faint); }
.ta-search:focus-visible {
@@ -140,13 +127,13 @@
}
.ta-seg {
display: inline-flex; background: var(--ta-panel); border: 1px solid var(--ta-border);
- border-radius: 10px; padding: 3px; gap: 2px;
+ border-radius: var(--radius-md); padding: 3px; gap: 2px;
}
.ta-seg button {
appearance: none; background: transparent; border: 0; cursor: pointer;
- color: var(--ta-muted); border-radius: 7px; padding: 7px 12px;
- font: 600 12px/1 Inter, system-ui, sans-serif;
- transition: background 0.16s ease, color 0.16s ease;
+ color: var(--ta-muted); border-radius: var(--radius-sm); padding: 7px 12px;
+ font: 600 12px/1 var(--font-body);
+ transition: background var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);
}
.ta-seg button:hover { color: var(--ta-text); background: var(--ta-panel-2); }
.ta-seg button[aria-pressed='true'] { background: var(--ta-accent-soft); color: var(--ta-accent); }
@@ -156,9 +143,9 @@
.ta-chip {
appearance: none; cursor: pointer;
background: var(--ta-panel); border: 1px solid var(--ta-border); color: var(--ta-muted);
- border-radius: 999px; padding: 6px 13px;
- font: 500 12.5px/1 Inter, system-ui, sans-serif;
- transition: border-color 0.16s ease, color 0.16s ease, background 0.16s ease;
+ border-radius: var(--radius-pill); padding: 6px 13px;
+ font: 500 12.5px/1 var(--font-body);
+ transition: border-color var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
}
.ta-chip:hover { border-color: var(--ta-border-2); color: var(--ta-text); }
.ta-chip[aria-pressed='true'] {
@@ -169,15 +156,15 @@
.ta-chip[aria-pressed='true'] .ta-chip-n { color: inherit; opacity: 0.7; }
.ta-count {
- margin: 16px 0 0; font: 500 13px/1 Inter, system-ui, sans-serif; color: var(--ta-faint);
+ margin: 16px 0 0; font: 500 13px/1 var(--font-body); color: var(--ta-faint);
display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
}
.ta-reset {
appearance: none; background: none; border: 0; padding: 0; cursor: pointer;
- color: var(--ta-accent); font: 500 13px/1 Inter, system-ui, sans-serif;
+ color: var(--ta-accent); font: 500 13px/1 var(--font-body);
text-decoration: underline; text-underline-offset: 3px;
}
- .ta-reset:focus-visible { outline: 2px solid var(--ta-accent); outline-offset: 3px; border-radius: 3px; }
+ .ta-reset:focus-visible { outline: 2px solid var(--ta-accent); outline-offset: 3px; border-radius: var(--radius-sm); }
/* ── Grid ─────────────────────────────────────────────────────────── */
.ta-grid {
@@ -189,7 +176,7 @@
appearance: none; cursor: pointer; padding: 0; color: inherit;
background: var(--ta-panel); border: 1px solid var(--ta-border);
border-radius: var(--ta-radius); overflow: hidden;
- transition: transform 0.18s cubic-bezier(0.2, 0, 0.2, 1), border-color 0.18s ease, box-shadow 0.18s ease;
+ transition: transform var(--duration-base) var(--ease-standard), border-color var(--duration-base) var(--ease-standard), box-shadow var(--duration-base) var(--ease-standard);
}
.ta-card:hover { transform: translateY(-3px); border-color: var(--ta-border-2); box-shadow: var(--ta-shadow); }
.ta-card:focus-visible { outline: 2px solid var(--ta-accent); outline-offset: 2px; }
@@ -201,38 +188,38 @@
}
.ta-shot img {
width: 100%; height: 100%; object-fit: cover; object-position: top center;
- display: block; transition: transform 0.4s cubic-bezier(0.2, 0, 0.2, 1);
+ display: block; transition: transform var(--duration-slow) var(--ease-standard);
}
.ta-card:hover .ta-shot img { transform: scale(1.035); }
.ta-shot-none {
position: absolute; inset: 0; display: grid; place-items: center; text-align: center;
- padding: 18px; font: 500 12.5px/1.5 Inter, system-ui, sans-serif; color: var(--ta-faint);
+ padding: 18px; font: 500 12.5px/1.5 var(--font-body); color: var(--ta-faint);
}
.ta-idx {
position: absolute; top: 9px; left: 9px; z-index: 2;
- padding: 3px 8px; border-radius: 999px;
+ padding: 3px 8px; border-radius: var(--radius-pill);
background: rgba(8, 10, 16, 0.76); color: rgba(255, 255, 255, 0.82);
border: 1px solid rgba(255, 255, 255, 0.14);
- font: 600 10.5px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 600 10.5px/1 var(--font-mono);
font-variant-numeric: tabular-nums;
}
.ta-body { padding: 14px 16px 16px; display: flex; flex-direction: column; gap: 8px; flex: 1; }
- .ta-title { font: 650 15px/1.3 Inter, system-ui, sans-serif; letter-spacing: -0.01em; }
+ .ta-title { font: 650 15px/1.3 var(--font-body); letter-spacing: -0.01em; }
.ta-path {
- font: 500 11.5px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 500 11.5px/1 var(--font-mono);
color: var(--ta-faint); word-break: break-all;
}
.ta-say {
- font: 400 13px/1.55 Inter, system-ui, sans-serif; color: var(--ta-muted);
+ font: 400 13px/1.55 var(--font-body); color: var(--ta-muted);
display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical;
line-clamp: 3; overflow: hidden;
}
.ta-badges { display: flex; flex-wrap: wrap; gap: 6px; margin-top: auto; padding-top: 4px; }
.ta-badge {
display: inline-flex; align-items: center; gap: 5px;
- padding: 3.5px 8px; border-radius: 6px;
- font: 600 10.5px/1.25 ui-monospace, SFMono-Regular, Menlo, monospace;
+ padding: 3.5px 8px; border-radius: var(--radius-sm);
+ font: 600 10.5px/1.25 var(--font-mono);
letter-spacing: 0.03em; text-transform: uppercase;
border: 1px solid var(--ta-border); color: var(--ta-faint); background: var(--ta-panel-2);
}
@@ -247,7 +234,7 @@
border-radius: var(--ta-radius); overflow: hidden;
}
.ta-skel-shot { aspect-ratio: 16 / 10; background: var(--ta-panel-2); }
- .ta-skel-line { height: 11px; border-radius: 5px; background: var(--ta-panel-2); margin: 12px 16px; }
+ .ta-skel-line { height: 11px; border-radius: var(--radius-sm); background: var(--ta-panel-2); margin: 12px 16px; }
.ta-skel-line:last-child { width: 55%; margin-bottom: 20px; }
@keyframes ta-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.45; } }
.ta-skel { animation: ta-pulse 1.5s ease-in-out infinite; }
@@ -263,15 +250,15 @@
border: 1px dashed var(--ta-border-2); border-radius: var(--ta-radius);
background: var(--ta-panel-2);
}
- .ta-empty h2 { font: 650 18px/1.3 Inter, system-ui, sans-serif; margin: 0 0 8px; }
- .ta-empty p { font: 400 14px/1.6 Inter, system-ui, sans-serif; color: var(--ta-muted); margin: 0 auto 18px; max-width: 44ch; }
+ .ta-empty h2 { font: 650 18px/1.3 var(--font-body); margin: 0 0 8px; }
+ .ta-empty p { font: 400 14px/1.6 var(--font-body); color: var(--ta-muted); margin: 0 auto 18px; max-width: 44ch; }
.ta-btn {
display: inline-flex; align-items: center; gap: 8px; cursor: pointer;
- appearance: none; border-radius: 9px; padding: 10px 16px;
- font: 600 13.5px/1 Inter, system-ui, sans-serif; text-decoration: none;
+ appearance: none; border-radius: var(--radius-md); padding: 10px 16px;
+ font: 600 13.5px/1 var(--font-body); text-decoration: none;
border: 1px solid var(--ta-border-2); background: var(--ta-panel); color: var(--ta-text);
- transition: border-color 0.16s ease, background 0.16s ease, transform 0.12s ease;
+ transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-instant) var(--ease-standard);
}
.ta-btn:hover { border-color: var(--ta-accent); }
.ta-btn:active { transform: translateY(1px); }
@@ -293,22 +280,22 @@
width: min(1080px, 100%); max-height: calc(100vh - 48px);
display: flex; flex-direction: column; overflow: hidden;
background: var(--ta-panel); border: 1px solid var(--ta-border-2);
- border-radius: 16px; box-shadow: 0 30px 90px rgba(0, 0, 0, 0.6);
+ border-radius: var(--radius-lg); box-shadow: 0 30px 90px rgba(0, 0, 0, 0.6);
}
.ta-lb-figure { position: relative; background: #05060a; flex-shrink: 0; }
.ta-lb-figure img { display: block; width: 100%; height: auto; max-height: 58vh; object-fit: contain; }
.ta-lb-x {
position: absolute; top: 10px; right: 10px; z-index: 3;
- width: 34px; height: 34px; border-radius: 9px; cursor: pointer;
- display: grid; place-items: center; font: 600 15px/1 Inter, system-ui, sans-serif;
+ width: 34px; height: 34px; border-radius: var(--radius-md); cursor: pointer;
+ display: grid; place-items: center; font: 600 15px/1 var(--font-body);
background: rgba(8, 10, 16, 0.78); color: #fff; border: 1px solid rgba(255, 255, 255, 0.16);
}
.ta-lb-x:hover { background: rgba(8, 10, 16, 0.95); }
.ta-lb-x:focus-visible { outline: 2px solid var(--ta-accent); outline-offset: 2px; }
.ta-lb-nav {
position: absolute; top: 50%; transform: translateY(-50%); z-index: 3;
- width: 40px; height: 56px; border-radius: 10px; cursor: pointer;
- display: grid; place-items: center; font: 600 18px/1 Inter, system-ui, sans-serif;
+ width: 40px; height: 56px; border-radius: var(--radius-md); cursor: pointer;
+ display: grid; place-items: center; font: 600 18px/1 var(--font-body);
background: rgba(8, 10, 16, 0.7); color: #fff; border: 1px solid rgba(255, 255, 255, 0.14);
}
.ta-lb-nav:hover { background: rgba(8, 10, 16, 0.92); }
@@ -318,22 +305,22 @@
.ta-lb-nav[disabled] { opacity: 0.3; cursor: default; }
.ta-lb-body { padding: 20px 24px 24px; overflow-y: auto; }
.ta-lb-kicker {
- font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 600 11px/1 var(--font-mono);
letter-spacing: 0.08em; text-transform: uppercase; color: var(--ta-accent); margin-bottom: 10px;
}
- .ta-lb-h { font: 700 22px/1.25 Inter, system-ui, sans-serif; letter-spacing: -0.02em; margin: 0 0 10px; }
- .ta-lb-say { font: 400 15px/1.65 Inter, system-ui, sans-serif; color: var(--ta-muted); margin: 0 0 18px; max-width: 72ch; }
+ .ta-lb-h { font: 700 22px/1.25 var(--font-body); letter-spacing: -0.02em; margin: 0 0 10px; }
+ .ta-lb-say { font: 400 15px/1.65 var(--font-body); color: var(--ta-muted); margin: 0 0 18px; max-width: 72ch; }
.ta-lb-meta {
display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 12px; margin: 0 0 20px; padding: 16px 0 0; border-top: 1px solid var(--ta-border);
}
.ta-lb-meta div { min-width: 0; }
.ta-lb-meta dt {
- font: 600 10.5px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font: 600 10.5px/1 var(--font-mono);
letter-spacing: 0.06em; text-transform: uppercase; color: var(--ta-faint); margin-bottom: 6px;
}
.ta-lb-meta dd {
- margin: 0; font: 500 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
+ margin: 0; font: 500 13px/1.5 var(--font-mono);
color: var(--ta-text); word-break: break-word;
}
.ta-lb-actions { display: flex; flex-wrap: wrap; gap: 10px; }
diff --git a/prompts/roadmap/avatar-parametric-editor.md b/prompts/roadmap/avatar-parametric-editor.md
index e957a9efa..4d33bbde0 100644
--- a/prompts/roadmap/avatar-parametric-editor.md
+++ b/prompts/roadmap/avatar-parametric-editor.md
@@ -1,113 +1,126 @@
-# Parametric Avatar Editor: the Avaturn-and-beyond plan
+# RM-PARAM: Parametric avatar editor, phase 2 onward
-Goal: an avatar editor where **every parameter of the character is editable**, minor and major: face regions (nose, ears, mouth, eyes, jaw, brow, cheeks), body shape (weight, muscle, proportions), individual limbs, hair, clothing, skin, and animation. Avaturn exposes a fixed template with a curated slider set and a paid catalog. We go past it on three axes: parameter depth (hundreds of sliders plus free sculpt), an AI-generated infinite asset catalog, and identity lanes (selfie and text prompt) that resolve into the same parameter space instead of a black-box mesh.
+**How to run this:** paste this whole file into a fresh Claude Code chat opened in
+`/workspaces/three.ws`, or say "execute `prompts/roadmap/avatar-parametric-editor.md`".
+It is complete on its own. Also read `prompts/roadmap/00-README.md` and `CLAUDE.md`.
-## The one architectural decision everything hangs on
+## Binding operating clause
-**One canonical parametric body. Everything else is a parameter over it.**
+1. Finish 100%. Never end with a question, a plan you did not execute, or "should I proceed?".
+2. Additive only. `src/glb-canonicalize.js`, `src/animation-retarget.js` and the export bake are
+ shared cores: preserve 100% backward compatibility and prove it with tests.
+3. CLAUDE.md hard rules: no mocks, no TODO comments, no em-dash or en-dash characters. Stage
+ explicit paths only.
-Avaturn, MetaHuman, MakeHuman, and Daz all converge on this: a single fixed-topology base mesh where
+## The architectural decision everything hangs on
-- shape = morph targets (vertex deltas),
-- proportions = skeleton parameters (per-bone scale/offset),
-- hair/clothes = conforming attachments that inherit the body's skinning and morphs,
-- skin = layered textures over a fixed UV layout,
-- identity capture (selfie, text) = a solver that outputs a parameter vector, not a mesh.
+**One canonical parametric body. Everything else is a parameter over it.** Shape is morph
+targets, proportions are skeleton parameters, hair and clothes are conforming attachments that
+inherit skinning and morphs, skin is layered textures over fixed UVs, and identity capture
+(selfie, text) is a solver that outputs a parameter vector rather than a mesh. Fixed topology
+is what makes "change everything" tractable.
-Fixed topology is what makes "change everything" tractable: every asset, morph, texture layer, and identity solver targets the same vertex ordering and UV space, so they all compose. Our current composer mixes baked parts across 4 RPM bodies; that gives variety but can never give sliders, because the bases have no morph library. The parametric backbone is the missing piece the composer README and `docs/avatar-reconstruction.md` v3 both already name.
+## Step 0: re-derive current state (trust nothing below)
-## What we already have (do not rebuild)
-
-| Layer | Exists today | Where |
-|---|---|---|
-| Slider UI | Morph slider panel, grouped, renders ANY morphs a GLB exposes; MetaHuman-style 2D face blend wheel | `src/avatar-sculpt.js` |
-| Studio shell | Create/edit modes, live scene, export | `src/avatar-studio.js`, `/avatar-studio` |
-| Part composition | Cross-base skinned-part grafting on a shared 67-joint skeleton, recolor, scale | `api/_lib/avatar-composer/` |
-| Wardrobe UI | Layered garment recolor + hide/show | `src/avatar-wardrobe.js`, `src/avatar-edit.js` |
-| Accessories | Bone-attached GLB merge bake | `api/_lib/bake.js`, `public/accessories/` |
-| Animation | 111 baked clips, universal retarget, additive overlays, ARKit-52 runtime, lipsync, face mocap | `src/animation-manager.js`, `src/animation-retarget.js`, `src/glb-canonicalize.js` |
-| Rigging | Auto-rig worker (Mixamo skeleton + skinning + ARKit-52) | `workers/rig/` |
-| Selfie face | MediaPipe 468-landmark shape morph onto template, `register_head_to_target` dense-registration primitive validated | `workers/avatar-reconstruction/` |
-| Export/bake | Morph bake, accessory merge, weld/quantize/meshopt, GLB/VRM/USDZ | `api/_lib/bake.js`, `src/avatar-export.js` |
-| Economy | Cosmetics shop, ownership, x402 settlement | `api/_lib/cosmetics*.js` |
-
-Key leverage: `avatar-sculpt.js` renders sliders for whatever morphs the loaded GLB carries. Ship a base with 300 morphs and the editor lights up with 300 sliders with zero UI work.
-
-## The build, in phases
-
-### Phase 1: the parametric backbone (unlocks everything): SHIPPED v1, 2026-07-22
+```bash
+ls public/avatars/parametric-base.glb avatar-sources/anny scripts/build-parametric-base.mjs
+npx vitest run tests/parametric-base.test.js
+node -e "1" && grep -c "" avatar-sources/anny/*/*.target 2>/dev/null | tail -3
+npm run dev # open /create/studio?base=parametric and count the sliders that render
+```
-Shipped by adopting [naver/anny](https://github.com/naver/anny)'s CC0 repackaging of the MakeHuman/MPFB2 data instead of hand-porting targets: `avatar-sources/anny/` (vendored data + provenance), `scripts/build-parametric-base.mjs` (baker), `public/avatars/parametric-base.glb` (52-bone mixamorig skeleton, 4 submeshes, 122 sparse morph sliders), Base switcher in Avatar Studio (`?base=parametric`), Ears/Head Shape sculpt groups, `tests/parametric-base.test.js`. 472 target files are vendored; ~350 remain uncurated (asym, per-segment scale axes, navel, valgus, hands, feet), so growing 122 sliders toward 400+ is a MORPHS-table edit plus rebake, no new engineering. Original plan for reference:
+**Phase 1 is shipped (2026-07-22):** `avatar-sources/anny/` (vendored CC0 MakeHuman/MPFB2 data
+with provenance), `scripts/build-parametric-base.mjs` (the baker),
+`public/avatars/parametric-base.glb` (52-bone `mixamorig:*` skeleton, 4 submeshes, 122 sparse
+morph sliders), the Base switcher in Avatar Studio (`?base=parametric`), the Ears and Head Shape
+sculpt groups, and `tests/parametric-base.test.js`. 472 target files are vendored and roughly
+350 remain uncurated, so growing 122 sliders toward 400+ is a MORPHS-table edit plus a rebake,
+not new engineering.
-Adopt a commercially-clean parametric base and port a large morph library onto it.
+`src/avatar-sculpt.js` renders sliders for whatever morphs the loaded GLB carries, so every
+morph you bake lights up in the UI with zero UI work.
-- **Base mesh + rig: Anny** (Apache-2.0 code, CC0 assets). Humanoid, game-ready topology, designed for morph-based customization.
-- **Face topology + ARKit: ICT-FaceKit** (MIT). Gives ARKit-52 + identity basis on a clean license; deformation-transfer its expression set onto the Anny head so lipsync/mocap keep working.
-- **Body morph library: MakeHuman targets** (CC0 output). Hundreds of body/face targets (per-region nose, ears, jaw, lips, eyes, torso, limbs, age, weight, muscle, gender spectrum). Port via one offline Blender/gltf-transform script that maps targets onto the Anny topology (nearest-surface + RBF, same math as `register_head_to_target`).
-- **Statistical prior: GHUM** (Apache-2.0) later, for realistic covariance ("heavier build also thickens wrists") behind a "realism lock" toggle. Not needed for v1.
-- Bake the result to `public/avatars/parametric-base.glb` (or one per build preset) with the full morph set. Three.js handles hundreds of morphs via texture-based morph targets; only nonzero influences cost anything at runtime.
+## Task 1: grow the slider set (cheapest large win)
-Output: the studio loads the parametric base and every slider is real. This single phase beats Avaturn's slider depth.
+Curate the remaining vendored targets into the MORPHS table (asymmetric variants, per-segment
+scale axes, navel, valgus, hands, feet), rebake, and confirm the studio renders them grouped
+sensibly. Keep the GLB sane: sparse accessors only, and measure the file size before and after.
+Extend `tests/parametric-base.test.js` with the new group assertions.
-### Phase 2: skeleton-space proportions (limbs, height, frame)
+## Task 2: skeleton-space proportions (phase 2)
Morphs cannot lengthen an arm without breaking skinning; bone parameters can.
-- Parameter set: height, leg/arm length, shoulder width, neck length, head size, hand/foot scale, hip width. Implemented as per-bone scale + rest-pose offsets on the canonical skeleton, applied at load and baked at export.
-- Verify against the retarget stack: clips play through `animation-retarget.js` hip-translation rescale already; extend its hip rescale to honor per-bone leg scale so walks don't foot-slide.
-- UI: a "Proportions" group in the sculpt panel (sliders already generic).
-
-### Phase 3: conforming assets + the AI catalog flywheel (the moat)
-
-Hair, clothes, shoes, facial hair as **conforming attachments**: assets authored (or generated) once against the canonical body, auto-fitted forever after.
-
-- **Auto-fit tool** (offline + on-upload): bind garment vertices to nearest body surface, transfer skin weights and all morph deltas (deformation transfer). A garment then follows every slider automatically: widen the hips, the pants widen.
-- **Layering**: slot taxonomy (hair, headwear, top, outerwear, bottom, footwear, gloves, facial-hair, accessories xN) with per-slot body-hide masks (vertex groups) so layered clothing never clips.
-- **The flywheel**: wire the forge text-to-3D lane to generate garments/hair against the canonical body ("generate a cyberpunk jacket"), pipe results through auto-fit, land them in the catalog and cosmetics shop. Avaturn has a fixed paid catalog; we have an infinite prompted one, priced in $THREE via the existing cosmetics economy.
-- Migrate the 4 RPM bases' hair/outfits through auto-fit so the composer's existing variety carries over; this also deletes the rest-pose-group restriction (composer v2 vertex rebinding falls out for free).
-
-### Phase 4: free sculpt (change literally anything)
+- Parameter set: height, leg and arm length, shoulder width, neck length, head size, hand and
+ foot scale, hip width. Implement as per-bone scale plus rest-pose offsets on the canonical
+ skeleton, applied at load and baked at export.
+- Extend `src/animation-retarget.js`'s hip-translation rescale to honor per-bone leg scale so
+ walks do not foot-slide. Add a regression case per changed path.
+- UI: a "Proportions" group in the sculpt panel. The sliders are already generic.
-Brush-drag directly on the mesh: radius/falloff brush edits vertex positions, recorded as a per-avatar **custom delta morph** (so it exports, serializes, and composes with the library morphs). Symmetry toggle on/off (asymmetry is a feature Avaturn lacks). This is the "every single minor thing" guarantee: anything no slider covers, the brush does.
+## Task 3: free sculpt (phase 4, the "change literally anything" guarantee)
-### Phase 5: identity lanes resolve into parameters
+A radius and falloff brush edits vertex positions directly on the mesh, recorded as a per-avatar
+custom delta morph so it exports, serializes and composes with the library morphs. Symmetry
+toggle on and off (asymmetry is a feature the competition lacks). Verify the delta survives a
+round trip through the export bake.
-- **Selfie**: MICA+FLAME dense fit (owner approved paying MPI for the commercial FLAME license; blocked on that signature) feeding `register_head_to_target`, then project the result INTO the morph library (least-squares fit over slider space + residual as a custom morph). The user gets their face AND every slider still works on it. Avaturn gives you a locked scanned head.
-- **Text**: LLM maps a prompt ("older, sharper jaw, elvish ears, lean runner's build") to a parameter vector over the named slider set. Cheap, no GPU, huge demo value; ship early behind the same parameter API.
-- **Randomize/seed**: composer-style seeded recipes become parameter-vector presets.
+## Task 4: the parameter model, as a real spec
-### Phase 6: skin and texture layers
-
-Layered material system over the canonical UVs: base tone, complexion (freckles/redness), makeup, tattoos/decals (project-on-click), scars, age maps, nail/lip/eye color, heterochromia. Live as separate layers in the editor; composited to a single atlas at export by extending `api/_lib/bake.js` (sharp is already in the pipeline). Optional AI restyle pass (existing restyle lane) as a layer, not a replacement.
-
-### Phase 7: animation personality
-
-The clip library and retargeter already outclass Avaturn. Add per-avatar animation identity: default idle/walk pick, gesture intensity, mood-blend defaults (embodiment/emotion.js already blends), and saved emote loadouts. Because everything sits on one canonical skeleton, retarget cost for the parametric base is zero.
-
-## Parameter model (the contract)
-
-One serializable document per avatar; this is what saves, shares, forks, and mints:
+One serializable document per avatar is what saves, shares, forks and mints. It is a
+load-bearing wire format (editor, baker, shop and embeds all consume it), so it belongs in
+`specs/`, not in a comment:
```json
{
"base": "parametric-v1",
- "morphs": { "noseWidth": 0.3, "earPoint": 0.8, "...": 0 },
- "skeleton": { "height": 1.78, "armLength": 1.02, "...": 1 },
+ "morphs": { "noseWidth": 0.3, "earPoint": 0.8 },
+ "skeleton": { "height": 1.78, "armLength": 1.02 },
"sculpt": "r2://sculpt-deltas/<id>.bin",
- "slots": { "hair": "asset:curly-04", "top": "asset:forge-8fa2", "...": null },
+ "slots": { "hair": "asset:curly-04", "top": "asset:forge-8fa2" },
"layers": [ { "type": "tattoo", "decal": "...", "uv": [0.4, 0.6] } ],
"animation": { "idle": "breathing-02", "walk": "confident", "mood": "warm" }
}
```
-Spec lands in `specs/` when Phase 1 ships (it is a load-bearing wire format: editor, baker, shop, and embeds all consume it).
-
-## Licensing gates (the only external blockers)
-
-- FLAME commercial license: owner signs with MPI (Phase 5 selfie lane only; nothing else waits on it).
-- MakeHuman targets are CC0 with a community caveat on fully-automated pipelines: port via our own one-time conversion script and commit the converted artifacts, which is the accepted clean pattern.
-- Everything else chosen (Anny, ICT-FaceKit, GHUM) is Apache/MIT/CC0.
-
-## Build order rationale
-
-Phase 1 alone is a visible leap (the studio goes from ~10 usable morphs to hundreds). Phases 2 and 4 complete "change everything". Phase 3 is the competitive moat and revenue surface. 5 to 7 are compounding differentiators. Each phase ships independently behind the existing studio UI; no phase requires a rewrite of the animation, export, or economy stacks.
+Write `specs/PARAMETRIC_AVATAR.md` with the field-by-field contract, versioning rule, and what
+each consumer is allowed to ignore. Then make the editor read and write exactly that shape.
+
+## Definition of done
+
+- [ ] Slider count grown, grouped and rendering; GLB size recorded before and after.
+- [ ] Proportion parameters apply at load, bake at export, and do not break retargeting
+ (`npm run gate` and the retarget suite green, walk verified with no foot sliding).
+- [ ] Free sculpt edits export, reload and compose with library morphs, proven by round trip.
+- [ ] `specs/PARAMETRIC_AVATAR.md` written; the editor reads and writes that document.
+- [ ] Verified in a real browser at 320, 768 and 1440 px with no console errors.
+- [ ] `npm test` green; `data/changelog.json` entry; `STRUCTURE.md` row updated if a surface
+ changed.
+- [ ] `npm run check:rules -- --paths <files you touched>` clean.
+
+## Never blocked (pre-answered)
+
+| Blocker | Do this |
+|---|---|
+| Hundreds of morphs look expensive at runtime | three.js handles them through texture-based morph targets and only nonzero influences cost anything. Measure before optimizing. |
+| A target file does not map cleanly onto the topology | Skip it, list it in the report, and keep the curated set clean. A wrong slider is worse than a missing one. |
+| The FLAME selfie lane is tempting | It is licence-blocked (owner signature with MPI) and is phase 5. Nothing in this work order waits on it. |
+| A change would alter shared retarget behavior | Flag-gate it, default to current behavior, and prove backward compatibility with tests before flipping. |
+| Garment fitting comes up | That is phase 3 and the `workers/garment-forge` lane. Out of scope here; note the seam. |
+
+## Appendix: the later phases (context, not this session's scope)
+
+- **Phase 3, conforming assets and the AI catalog flywheel (the moat):** auto-fit binds garment
+ vertices to the nearest body surface and transfers skin weights and morph deltas, so a garment
+ follows every slider. Slot taxonomy with per-slot body-hide masks prevents clipping. The forge
+ text-to-3D lane generates garments and hair against the canonical body, auto-fits them, and
+ lands them in the cosmetics shop. The competition has a fixed paid catalog; we get an infinite
+ prompted one.
+- **Phase 5, identity lanes resolve into parameters:** selfie via dense fit projected into the
+ morph library (least-squares over slider space, residual as a custom morph), text via an LLM
+ mapping a prompt to a parameter vector over the named slider set.
+- **Phase 6, skin and texture layers:** base tone, complexion, makeup, tattoos and decals,
+ scars, age maps, eye colour, composited to one atlas at export.
+- **Phase 7, animation personality:** per-avatar default idle and walk, gesture intensity,
+ mood-blend defaults, saved emote loadouts. Retarget cost is zero because everything sits on
+ one canonical skeleton.
diff --git a/scripts/set-r2-cors.mjs b/scripts/set-r2-cors.mjs
index 276149cfd..3790178f4 100644
--- a/scripts/set-r2-cors.mjs
+++ b/scripts/set-r2-cors.mjs
@@ -13,21 +13,33 @@
* 2. Write — PUT of presigned uploads from the same web origins.
*
* Usage:
- * # Pull production R2 creds into .env, then run.
- * vercel env pull .env
- * node scripts/set-r2-cors.mjs # apply (idempotent)
- * node scripts/set-r2-cors.mjs --get # show what's live
+ * node scripts/set-r2-cors.mjs --probe # measure the LIVE policy from outside (no bucket creds)
+ * node scripts/set-r2-cors.mjs --get # read the live policy (needs an admin token)
* node scripts/set-r2-cors.mjs --dry-run # print the policy, don't push
+ * node scripts/set-r2-cors.mjs # apply (idempotent, needs an admin token)
*
- * Requires the same env as the API: S3_ENDPOINT, S3_ACCESS_KEY_ID,
- * S3_SECRET_ACCESS_KEY, S3_BUCKET. R2 implements the S3 PutBucketCors
- * API verbatim, so this script also works against AWS S3 and B2.
+ * Where the credentials come from:
+ * - `.env` / `.env.local` hold S3_ENDPOINT, S3_ACCESS_KEY_ID,
+ * S3_SECRET_ACCESS_KEY, S3_BUCKET. The token normally checked in here is
+ * "Object Read & Write" scoped, which is enough for --probe but NOT for
+ * Get/PutBucketCors. Put an "Admin Read & Write" R2 token in `.env.local`
+ * as R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY to use --get or apply.
+ * - Production runtime values live on the Cloud Run service, readable with
+ * `gcloud run services describe three-ws-api --region us-central1
+ * --project aerial-vehicle-466722-p5 --format=yaml`. Those are the same
+ * object-scoped keys, so they do not unlock --get either.
+ * - Do NOT use `vercel env pull`: it returns empty for secret-type vars, and
+ * production has not run on Vercel since 2026-07-07.
+ *
+ * R2 implements the S3 PutBucketCors API verbatim, so this script also works
+ * against AWS S3 and B2.
*/
import {
S3Client,
GetBucketCorsCommand,
PutBucketCorsCommand,
+ ListObjectsV2Command,
} from '@aws-sdk/client-s3';
import { readFileSync, existsSync } from 'node:fs';
@@ -53,8 +65,8 @@ const missing = required.filter((k) => !process.env[k]);
if (missing.length) {
// Deploy-time invocation: missing env is not a deploy failure. Local-dev
// invocation: surface the hint. Either way, exit 0 so a CI step can chain.
- console.log(`[set-r2-cors] skipped — missing env: ${missing.join(', ')}`);
- console.log('[set-r2-cors] (local: drop R2_ACCOUNT_ID/R2_ACCESS_KEY_ID/R2_SECRET_ACCESS_KEY/R2_BUCKET in .env.local, or run `vercel env pull .env` for production creds.)');
+ console.log(`[set-r2-cors] skipped, missing env: ${missing.join(', ')}`);
+ console.log('[set-r2-cors] (local: drop R2_ACCOUNT_ID/R2_ACCESS_KEY_ID/R2_SECRET_ACCESS_KEY/R2_BUCKET in .env.local. Production values: gcloud run services describe three-ws-api --region us-central1 --project aerial-vehicle-466722-p5 --format=yaml)');
process.exit(0);
}
@@ -116,6 +128,10 @@ const s3 = new S3Client({
const Bucket = process.env.S3_BUCKET;
+if (flag('--probe')) {
+ process.exit((await probe()) ? 0 : 1);
+}
+
if (flag('--get')) {
let current;
try {
@@ -156,6 +172,112 @@ if (JSON.stringify(before) === JSON.stringify(after)) {
console.log('Rules:', after.CORSRules.map((r) => `${r.ID || '(no id)'} → ${r.AllowedMethods.join(',')}`).join(' | '));
}
+// Measure the policy the bucket actually enforces, using only object-scoped
+// credentials. GetBucketCors needs an admin token that most environments do
+// not have, so without this the live policy is unverifiable and drift between
+// POLICY above and the bucket goes unnoticed for months (it did: 2026-08-01).
+//
+// Two requests per origin, one per rule:
+// read — GET on the public host; the `public-read` rule should echo every origin.
+// write — PUT preflight on the S3 endpoint; only ALLOWED_ORIGINS should get 204.
+// Exits nonzero when the measurement disagrees with POLICY.
+async function probe() {
+ const publicHost = process.env.S3_PUBLIC_DOMAIN || process.env.R2_PUBLIC_DOMAIN;
+ if (!publicHost) {
+ console.error('--probe needs S3_PUBLIC_DOMAIN (the public r2.dev or custom-domain host).');
+ return false;
+ }
+
+ const key = await probeKey();
+ if (!key) {
+ console.error('--probe could not find a public object to read. Pass one with --key=<object key>.');
+ return false;
+ }
+
+ const readUrl = `${publicHost.replace(/\/$/, '')}/${encodeR2Key(key)}`;
+ const writeUrl = `${process.env.S3_ENDPOINT.replace(/\/$/, '')}/${Bucket}/${PROBE_WRITE_KEY}`;
+
+ console.log(`Probing ${Bucket} (read: ${readUrl})\n`);
+ console.log(`${'ORIGIN'.padEnd(38)} ${'READ'.padEnd(6)} ${'WRITE'.padEnd(6)} EXPECTED`);
+
+ let ok = true;
+ for (const origin of PROBE_ORIGINS) {
+ const [read, write] = await Promise.all([
+ corsAllowed(readUrl, origin, 'GET'),
+ corsAllowed(writeUrl, origin, 'PUT'),
+ ]);
+ const wantRead = ruleAllows('public-read', origin);
+ const wantWrite = ruleAllows('browser-upload', origin);
+ const bad = read !== wantRead || write !== wantWrite;
+ if (bad) ok = false;
+ const want = `read=${wantRead ? 'yes' : 'no'} write=${wantWrite ? 'yes' : 'no'}${bad ? ' <- DRIFT' : ''}`;
+ console.log(`${origin.padEnd(38)} ${(read ? 'yes' : 'no').padEnd(6)} ${(write ? 'yes' : 'no').padEnd(6)} ${want}`);
+ }
+
+ console.log('');
+ if (ok) {
+ console.log('Live policy matches POLICY in this script.');
+ } else {
+ console.log('Live policy DIFFERS from POLICY in this script. Apply it with an admin token:');
+ console.log(' node scripts/set-r2-cors.mjs');
+ }
+ return ok;
+}
+
+// A key whose object is world-readable, so the read probe measures CORS rather
+// than auth. Prefers a caller-supplied --key, else the first thumbnail.
+async function probeKey() {
+ const explicit = process.argv.find((a) => a.startsWith('--key='));
+ if (explicit) return explicit.slice('--key='.length);
+ try {
+ const r = await s3.send(new ListObjectsV2Command({ Bucket, Prefix: 'thumb/', MaxKeys: 1 }));
+ return r.Contents?.[0]?.Key || null;
+ } catch {
+ return null;
+ }
+}
+
+// True when the browser would be allowed through: a matching
+// Access-Control-Allow-Origin on the actual request for GET, and a non-error
+// preflight for PUT (which never touches a real object, so the key need not exist).
+async function corsAllowed(url, origin, method) {
+ const headers = { origin };
+ // HEAD, not GET: same CORS rule, none of the bytes.
+ let init = { method: 'HEAD', headers, redirect: 'manual' };
+ if (method === 'PUT') {
+ init = {
+ method: 'OPTIONS',
+ headers: { ...headers, 'access-control-request-method': 'PUT', 'access-control-request-headers': 'content-type' },
+ };
+ }
+ let res;
+ try {
+ res = await fetch(url, init);
+ } catch {
+ return false;
+ }
+ if (method === 'PUT' && !res.ok) return false;
+ const allow = res.headers.get('access-control-allow-origin');
+ return allow === '*' || allow === origin;
+}
+
+// Does POLICY's named rule cover this origin? Mirrors S3 matching: one `*` per
+// entry, matched against the whole origin string.
+function ruleAllows(id, origin) {
+ const rule = POLICY.CORSRules.find((r) => r.ID === id);
+ if (!rule) return false;
+ return rule.AllowedOrigins.some((pattern) => {
+ if (pattern === '*') return true;
+ if (!pattern.includes('*')) return pattern === origin;
+ const [head, tail] = pattern.split('*');
+ return origin.startsWith(head) && origin.endsWith(tail) && origin.length >= head.length + tail.length;
+ });
+}
+
+function encodeR2Key(key) {
+ return key.split('/').map(encodeURIComponent).join('/');
+}
+
async function getCors() {
try {
const r = await s3.send(new GetBucketCorsCommand({ Bucket }));
diff --git a/scripts/verify-sign-avatar.mjs b/scripts/verify-sign-avatar.mjs
index 1e4c39d1d..acdf02ffd 100644
--- a/scripts/verify-sign-avatar.mjs
+++ b/scripts/verify-sign-avatar.mjs
@@ -88,6 +88,10 @@ for (const route of ['/sign-language', '/asl-alphabet']) {
}
// The camera: a drag has to move the view and surface the reset affordance.
+ // Measure only once the stage is centred, or the earlier interactions leave
+ // it scrolled and the synthetic drag lands somewhere else entirely.
+ await page.$eval(stageSel, (el) => el.scrollIntoView({ block: 'center' }));
+ await page.waitForTimeout(500);
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 };
diff --git a/src/glb-canonicalize.js b/src/glb-canonicalize.js
index 83156a320..64ecc1867 100644
--- a/src/glb-canonicalize.js
+++ b/src/glb-canonicalize.js
@@ -435,6 +435,114 @@ function _lookupBone(name) {
return LOOKUP.get(key) ?? UNREAL_ALIASES.get(key) ?? EXTRA_ALIASES.get(key) ?? null;
}
+// A joint spelled like the shoulder blade / collar bone rather than the limb.
+const CLAVICLE_SPELLING = /shoulder|clavicle|collar|scapula/i;
+// A joint spelled like the upper arm itself.
+const UPPER_ARM_SPELLING = /upper.?arm|humerus/i;
+// Clavicle-only spellings: `shoulder` is deliberately absent, because SMPL-style
+// rigs use it FOR the upper arm (`left_shoulder`) and name the clavicle
+// `left_collar`. Used by the mirror-image pass.
+const COLLAR_ONLY_SPELLING = /clavicle|collar|scapula/i;
+
+/**
+ * Resolve the clavicle / upper-arm naming collision on a canonicalization plan.
+ *
+ * Anatomical rigs give the two bones names that normalize onto ONE canonical
+ * name, and no name-only table can separate them, because the same spelling
+ * means different bones on different rigs:
+ *
+ * - Rigify names the clavicle `shoulder.L` and the upper arm `upper_arm.L`;
+ * both resolve to `LeftArm`, so the clip's arm rotation binds to the
+ * clavicle and the arm swings from the shoulder blade.
+ * - SMPL names the clavicle `left_collar` and the upper arm `left_shoulder`;
+ * both resolve to `LeftShoulder`, leaving `LeftArm` vacant and the arm clip
+ * unbound entirely.
+ * - The hand-built hobby rig spells its upper arm `shoulderL` with no clavicle
+ * at all, so re-pointing that spelling would freeze its arms.
+ *
+ * The collision is therefore resolved by contention, not by spelling: a target
+ * is only reassigned when two joints contest it AND the sibling target is free,
+ * so a rig without the collision is never touched. When more than one contender
+ * is eligible and the caller supplies an `isAncestor` test, skeleton hierarchy
+ * breaks the tie: the clavicle is the parent of the upper arm.
+ *
+ * Mutates each entry's `canonical` in place.
+ *
+ * @param {Array<{raw: string, canonical: string}>} plan candidate assignments
+ * @param {{ isAncestor?: (a: object, b: object) => boolean }} [opts]
+ * @returns {number} entries reassigned
+ */
+export function resolveArmShoulderCollisions(plan, opts = {}) {
+ const isAncestor = typeof opts.isAncestor === 'function' ? opts.isAncestor : null;
+ const count = new Map();
+ for (const p of plan) count.set(p.canonical, (count.get(p.canonical) || 0) + 1);
+
+ // Of several eligible entries, prefer the one that sits ABOVE another
+ // contender in the skeleton (the clavicle parents the upper arm). Falls back
+ // to document order when there is no hierarchy to read.
+ const outermost = (eligible, contenders) => {
+ if (eligible.length < 2 || !isAncestor) return eligible[0];
+ return eligible.find((e) => contenders.some((o) => o !== e && isAncestor(e, o))) || eligible[0];
+ };
+ const innermost = (eligible, contenders) => {
+ if (eligible.length < 2 || !isAncestor) return eligible[0];
+ return eligible.find((e) => contenders.some((o) => o !== e && isAncestor(o, e))) || eligible[0];
+ };
+
+ const move = (entry, from, to) => {
+ entry.canonical = to;
+ count.set(from, (count.get(from) || 1) - 1);
+ count.set(to, (count.get(to) || 0) + 1);
+ };
+
+ let changed = 0;
+ // Arm contested (Rigify): demote the clavicle-spelled contender to Shoulder.
+ for (const side of ['Left', 'Right']) {
+ const arm = `${side}Arm`;
+ const shoulder = `${side}Shoulder`;
+ if ((count.get(arm) || 0) < 2 || (count.get(shoulder) || 0) > 0) continue;
+ const contenders = plan.filter((p) => p.canonical === arm);
+ if (!contenders.some((p) => UPPER_ARM_SPELLING.test(p.raw))) continue;
+ const eligible = contenders.filter(
+ (p) => CLAVICLE_SPELLING.test(p.raw) && !UPPER_ARM_SPELLING.test(p.raw),
+ );
+ const pick = outermost(eligible, contenders);
+ if (!pick) continue;
+ move(pick, arm, shoulder);
+ changed++;
+ }
+
+ // Shoulder contested (SMPL): promote the shoulder-spelled contender to Arm.
+ for (const side of ['Left', 'Right']) {
+ const arm = `${side}Arm`;
+ const shoulder = `${side}Shoulder`;
+ if ((count.get(shoulder) || 0) < 2 || (count.get(arm) || 0) > 0) continue;
+ const contenders = plan.filter((p) => p.canonical === shoulder);
+ if (!contenders.some((p) => COLLAR_ONLY_SPELLING.test(p.raw))) continue;
+ const eligible = contenders.filter(
+ (p) => /shoulder/i.test(p.raw) && !COLLAR_ONLY_SPELLING.test(p.raw),
+ );
+ const pick = innermost(eligible, contenders);
+ if (!pick) continue;
+ move(pick, shoulder, arm);
+ changed++;
+ }
+ return changed;
+}
+
+// Whether glTF node `a` is an ancestor of node `b`, walking up `parentOf`.
+// Tolerates the cyclic parentage a malformed GLB can carry: the visited set
+// stops the walk instead of looping forever.
+function isAncestorNode(parentOf, aIndex, bIndex) {
+ if (aIndex == null || bIndex == null || aIndex === bIndex) return false;
+ const seen = new Set([bIndex]);
+ for (let cur = parentOf.get(bIndex); cur != null && !seen.has(cur); cur = parentOf.get(cur)) {
+ if (cur === aIndex) return true;
+ seen.add(cur);
+ }
+ return false;
+}
+
/**
* Walk a parsed glTF JSON object and canonicalize joint-node names in place.
* Only nodes referenced from `skins[].joints[]` are touched — non-bone nodes
@@ -455,20 +563,22 @@ export function canonicalizeJointNodes(json) {
}
// Pass 1: resolve each joint to a canonical target (or null).
const plan = [];
- const targetCount = new Map();
for (const idx of jointIndices) {
const node = json.nodes[idx];
if (!node || typeof node.name !== 'string') continue;
const canonical = canonicalizeBoneName(node.name);
if (!canonical || canonical === node.name) continue;
- plan.push({ node, raw: node.name, canonical });
- targetCount.set(canonical, (targetCount.get(canonical) || 0) + 1);
+ plan.push({ node, index: idx, raw: node.name, canonical });
}
- // Pass 1.5/1.6: the clavicle/upper-arm collision, resolved for both lanes by
- // the shared resolver below.
+ // Pass 1.5/1.6: the clavicle/upper-arm collision, resolved by the shared
+ // resolver the runtime lane also uses.
+ const parentOf = new Map();
+ json.nodes.forEach((n, i) => {
+ if (Array.isArray(n.children)) for (const c of n.children) parentOf.set(c, i);
+ });
resolveArmShoulderCollisions(plan, {
- isAncestor: (a, b) => isAncestorNode(json, a.index, b.index),
+ isAncestor: (a, b) => isAncestorNode(parentOf, a.index, b.index),
});
// Pass 2: apply. A canonical name is assigned at most once — when two joints