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: catalog-wide garment gait audit + worker call resilience
nirholas25cc878d5852
diff --git a/api/_lib/x402/ring-tick-plan.js b/api/_lib/x402/ring-tick-plan.jsindex ca6e5ffc4..ff6706313 100644--- a/api/_lib/x402/ring-tick-plan.js+++ b/api/_lib/x402/ring-tick-plan.js@@ -46,9 +46,38 @@ export function ringTickConfig(e = process.env) {// well under the 60 s tick window at typical 1-3 s per settle; 1 restores// the old strictly-sequential behavior.concurrency: Math.max(1, Math.floor(num(e.X402_RING_TICK_CONCURRENCY, 12))),+ // Runway governor inputs. feePerCallLamports is the conservative per-call+ // fee estimate (measured 6,300-7,800 on mainnet self-pay); runwayDays is+ // how long the payer's spendable SOL must last at the governed rate. The+ // governor only ever throttles DOWN from `calls`; it never raises it.+ feePerCallLamports: Math.max(1, Math.floor(num(e.X402_RING_FEE_PER_CALL_LAMPORTS, 7_000))),+ runwayDays: Math.max(0.5, num(e.X402_RING_TARGET_RUNWAY_DAYS, 3)),};}+// ── Runway governor ─────────────────────────────────────────────────────────────+// Scale this tick's paid-call count to the SOL the payer actually holds, so the+// ring burns its fee runway over `runwayDays` instead of sprinting to the floor+// and flat-lining until the next manual funding. Spendable = balance - floor+// (the floor stays untouchable). The governed rate makes funding the throttle:+// more SOL in the payer = more calls/min, automatically, and as the balance+// drains the rate tapers instead of cliff-dying. Pure: same inputs → same+// decision. Returns { calls, callsPerDayBudget, throttled }.+export function governedCalls({+ configuredCalls, solLamports, floorLamports, feePerCallLamports, runwayDays,+}) {+ if (!Number.isFinite(solLamports)) {+ return { calls: 0, callsPerDayBudget: 0, throttled: true };+ }+ const spendable = Math.max(0, solLamports - floorLamports);+ const callsPerDayBudget = Math.floor(+ spendable / Math.max(0.5, runwayDays) / Math.max(1, feePerCallLamports),+ );+ const callsPerMin = Math.floor(callsPerDayBudget / 1440);+ const calls = Math.max(0, Math.min(configuredCalls, callsPerMin));+ return { calls, callsPerDayBudget, throttled: calls < configuredCalls };+}+// ── Cadence: which endpoints does this tick pay? ────────────────────────────────// Weighted rotation: cheap tips/services dominate the count; every Nth tick one of// the slots is the ring-settle carrier. `tickSeq` is a monotonic per-minutediff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.jsindex f4e384262..1339ab1b7 100644--- a/api/cron/x402-ring-tick.js+++ b/api/cron/x402-ring-tick.js@@ -66,6 +66,7 @@ import {ringTickConfig,planTick,planBackpressure,+ governedCalls,tickBudget,gateOnRingConfig,} from '../_lib/x402/ring-tick-plan.js';@@ -291,13 +292,45 @@ export default wrapCron(async (req, res) => {});}+ // ── Runway governor: throttle this tick to the payer's funded SOL runway ──+ // Spendable SOL above the floor must last cfg.runwayDays at the governed+ // rate. Funding the payer raises the rate automatically; a draining balance+ // tapers it instead of sprinting to the floor and flat-lining the ring.+ const gov = governedCalls({+ configuredCalls: cfg.calls,+ solLamports,+ floorLamports: cfg.solFloorLamports,+ feePerCallLamports: cfg.feePerCallLamports,+ runwayDays: cfg.runwayDays,+ });+ if (gov.calls <= 0) {+ await recordSkip(runId, origin, 'runway_exhausted', {+ sol_lamports: Number.isFinite(solLamports) ? solLamports : null,+ floor_lamports: cfg.solFloorLamports,+ calls_per_day_budget: gov.callsPerDayBudget,+ });+ await sendOpsAlert(+ 'x402 ring tick paused: runway_exhausted',+ `payer spendable SOL cannot sustain 1 call/min for ${cfg.runwayDays}d (sol=${solLamports}, floor=${cfg.solFloorLamports}); fund the payer to resume`,+ { signature: 'ring-tick:runway_exhausted' },+ );+ log.warn('ring_tick_runway_exhausted', { sol_lamports: solLamports, calls_per_day_budget: gov.callsPerDayBudget });+ return json(res, 200, { ok: true, skipped: true, reason: 'runway_exhausted', run_id: runId });+ }+ if (gov.throttled) {+ log.info('ring_tick_runway_throttle', {+ configured_calls: cfg.calls, governed_calls: gov.calls,+ calls_per_day_budget: gov.callsPerDayBudget, runway_days: cfg.runwayDays,+ });+ }+// ── Plan this tick (cursor reserved AFTER the degrade decision so the// reservation matches the cheap slots actually fired) ──────────────────────- const cheapNeeded = Math.max(0, cfg.calls - (pbp.settleTick ? 1 : 0));+ const cheapNeeded = Math.max(0, gov.calls - (pbp.settleTick ? 1 : 0));const cheapStart = await reserveCheapCursor(redis, cheapNeeded);const plan = planTick({tickSeq,- calls: cfg.calls,+ calls: gov.calls,// Force the post-degrade decision: 1 → every tick settles, 0 → none does.settleEveryN: pbp.settleTick ? 1 : 0,cheapCount: CHEAP_ENDPOINTS.length,diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex e3fe54f53..554c88509 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -16,6 +16,25 @@ control.> *not* to do. The public organic-revenue feed is a separate surface> ([/api/x402-revenue](../api/x402-revenue.js)).+## The runway governor: funding IS the throttle++The per-minute ring tick no longer fires a fixed `X402_RING_TICK_CALLS` blindly.+`governedCalls()` (`api/_lib/x402/ring-tick-plan.js`) scales each tick's call+count so the payer's spendable SOL (balance minus the untouchable floor) lasts+`X402_RING_TARGET_RUNWAY_DAYS` (default 3) at the governed rate, assuming+`X402_RING_FEE_PER_CALL_LAMPORTS` (default 7,000, the conservative end of the+measured 6,300-7,800 self-pay cost) per call. Consequences:++- Fund the payer more, the ring speeds up automatically. Let it drain, the rate+ tapers smoothly instead of sprinting to the floor and flat-lining until the+ next manual top-up (the failure mode that killed the ring daily at the+ 94-calls/min fixed rate).+- The governor only throttles DOWN from the configured rate, never above it,+ so `X402_RING_TICK_CALLS` remains the hard ceiling.+- When spendable SOL cannot sustain even 1 call/min for the runway window, the+ tick skips with reason `runway_exhausted` (one throttled ops alert), which is+ the loud "fund the payer" signal.+## Burning the least SOL — two leversOn-chain settlement has a **hard floor**: every Solana transaction costs a basediff --git a/package.json b/package.jsonindex d158e0c4c..4de358ba4 100644--- a/package.json+++ b/package.json@@ -149,6 +149,7 @@"guard:hidden": "node scripts/inject-hidden-guard.mjs --write","check:images": "node scripts/audit-image-loading.mjs --strict","audit:web": "node scripts/page-audit.mjs",+ "audit:garments": "node scripts/audit-garments.mjs","audit:web:login": "node scripts/page-audit.mjs --login","logs": "node scripts/gcp-logs.mjs","logs:tail": "node scripts/gcp-logs.mjs --follow",@@ -227,7 +228,7 @@"deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod","build:info": "node scripts/write-build-info.mjs","build:info:snapshot": "node scripts/write-build-info.mjs --snapshot",- "build:gcp": "npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",+ "build:gcp": "npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:chat && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages","ensure:avatar-studio": "test -f character-studio/build/index.html || npm run build:avatar-studio","deploy:gcp": "npm run check:dist && npm run check:pages && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn && npm run smoke:prod","deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",@@ -289,6 +290,7 @@"@metaplex-foundation/mpl-core": "^1.10.0","@metaplex-foundation/umi": "^1.5.1","@metaplex-foundation/umi-bundle-defaults": "^1.5.1",+ "@meteora-ag/dynamic-bonding-curve-sdk": "^1.5.10","@mkkellogg/gaussian-splats-3d": "^0.4.7","@modelcontextprotocol/sdk": "^1.29.0","@neondatabase/serverless": "^0.10.1",diff --git a/scripts/audit-garments.mjs b/scripts/audit-garments.mjsnew file mode 100644index 000000000..0b61cabe4--- /dev/null+++ b/scripts/audit-garments.mjs@@ -0,0 +1,194 @@+// Catalog-wide garment quality audit.+//+// For EVERY entry in the live wardrobe catalog:+// 1. consumer validation (the same validateManifest the closet runs),+// 2. sha256 of the fetched GLB against the manifest,+// 3. attachGarment onto the canonical body (the real runtime bind path),+// 4. the walk-gait deviation metric from the rig-path bake-off: distance+// from each skinned garment vertex to the nearest body vertex, sampled+// across the canonical walk clip. Good cloth keeps a small bounded+// offset; broken skinning spikes.+//+// Hard failures (validation reject, sha mismatch, attach refusal) exit 1 so+// this can gate a seeding batch. Gait stats are reported per garment with a+// per-slot p95 ceiling; breaching it is a WARN (geometry taste, not a broken+// contract) and is listed for human review.+//+// Usage:+// node scripts/audit-garments.mjs [--catalog <url>] [--avatar <glb path>]++import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import { createHash } from 'node:crypto';+import { Blob } from 'node:buffer';++globalThis.self = globalThis;+globalThis.window = globalThis;+class FakeImage extends EventTarget {+ constructor() {+ super();+ this._src = '';+ this.style = {};+ this.complete = false;+ this.naturalWidth = 1;+ this.naturalHeight = 1;+ }+ get src() { return this._src; }+ set src(value) {+ this._src = value;+ setTimeout(() => {+ this.complete = true;+ this.onload?.({ target: this });+ this.dispatchEvent(new Event('load'));+ }, 0);+ }+ setAttribute() {}+}+globalThis.document = {+ createElementNS: () => new FakeImage(),+ createElement: () => new FakeImage(),+};+globalThis.Image = FakeImage;+globalThis.Blob = Blob;++const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');+const { MeshoptDecoder } = await import('three/addons/libs/meshopt_decoder.module.js');+const { Group, Vector3, AnimationClip, AnimationMixer } = await import('three');+const { attachGarment } = await import('../src/avatar-garment.js');+const { retargetClipToObject } = await import('../src/animation-retarget.js');+const { sanitizeCatalog, GARMENT_CATALOG_URL } = await import('../src/garment-catalog.js');++const args = process.argv.slice(2);+const flag = (name, fallback) => {+ const i = args.indexOf(`--${name}`);+ return i >= 0 && args[i + 1] ? args[i + 1] : fallback;+};+const CATALOG_URL = flag('catalog', GARMENT_CATALOG_URL);+const AVATAR_PATH = resolve(process.cwd(), flag('avatar', 'public/avatars/parametric-base.glb'));++// p95 cloth-to-body ceilings (meters) per slot before a garment is flagged+// for review. Body-hugging slots sit tight; loose slots (hair, bags) ride+// farther by design. Derived from the 2026-07-25 bake-off (production shirt:+// p95 6.4 cm) with headroom for looser cuts.+const P95_CEILING = {+ top: 0.12, outerwear: 0.15, bottom: 0.12, footwear: 0.10,+ hair: 0.20, headwear: 0.15, glasses: 0.12, accessory: 0.25,+};+const GAIT_SAMPLES = [0.1, 0.3, 0.5, 0.7, 0.9];++function loadGlb(bytes) {+ const loader = new GLTFLoader();+ loader.setMeshoptDecoder(MeshoptDecoder);+ return new Promise((res, rej) => {+ loader.parse(+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), '', res, rej,+ );+ });+}++async function fetchBytes(url) {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`${url} -> HTTP ${res.status}`);+ return Buffer.from(await res.arrayBuffer());+}++// Distance stats from each skinned garment vertex to the nearest body vertex,+// sampled across the walk gait. Brute-force nearest with a stride cap keeps+// the audit under a second per garment without changing the verdict.+function gaitStats(root, body, garmentMesh, clip) {+ const mixer = new AnimationMixer(root);+ mixer.clipAction(clip).play();+ const gPos = garmentMesh.geometry.attributes.position;+ const bPos = body.geometry.attributes.position;+ const gStride = Math.max(1, Math.floor(gPos.count / 800));+ const bStride = Math.max(1, Math.floor(bPos.count / 2500));+ const gv = new Vector3();+ const bv = new Vector3();+ const bodyPts = [];+ const all = [];++ for (const t of GAIT_SAMPLES) {+ mixer.setTime(t * clip.duration);+ root.updateMatrixWorld(true);+ body.skeleton.update();+ garmentMesh.skeleton.update();++ bodyPts.length = 0;+ for (let i = 0; i < bPos.count; i += bStride) {+ bodyPts.push(body.applyBoneTransform(i, bv.fromBufferAttribute(bPos, i)).clone());+ }+ for (let i = 0; i < gPos.count; i += gStride) {+ garmentMesh.applyBoneTransform(i, gv.fromBufferAttribute(gPos, i));+ let best = Infinity;+ for (const p of bodyPts) {+ const d = gv.distanceToSquared(p);+ if (d < best) best = d;+ }+ all.push(Math.sqrt(best));+ }+ }+ all.sort((a, b) => a - b);+ const mean = all.reduce((s, d) => s + d, 0) / all.length;+ return {+ mean,+ p95: all[Math.floor(all.length * 0.95)],+ max: all[all.length - 1],+ n: all.length,+ };+}++const avatarBytes = readFileSync(AVATAR_PATH);+const clipJson = JSON.parse(readFileSync(resolve(process.cwd(), 'public/animations/clips/walk.json'), 'utf8'));+const walkClip = AnimationClip.parse(clipJson.clip || clipJson);++const raw = await (await fetch(CATALOG_URL)).json();+const { garments, rejected } = sanitizeCatalog(raw);+console.log(`catalog: ${raw.length} entries, ${garments.length} valid, ${rejected.length} rejected`);+for (const r of rejected) console.log(` REJECTED ${r.id}: ${r.errors.join('; ')}`);++let hardFailures = rejected.length;+const warns = [];++for (const m of garments) {+ const label = `${m.slot}/${m.id}`;+ try {+ const glb = await fetchBytes(m.model.uri);+ const sha = createHash('sha256').update(glb).digest('hex');+ if (sha !== m.model.sha256) throw new Error('sha256 mismatch');++ const avatar = await loadGlb(avatarBytes);+ const root = new Group();+ root.add(avatar.scene);+ root.updateMatrixWorld(true);+ const garment = await loadGlb(glb);+ garment.scene.updateMatrixWorld(true);++ const res = attachGarment(root, garment.scene, { slot: m.slot });+ if (!res.ok) throw new Error(`attach refused: ${res.reason}`);++ let body = null;+ root.traverse((o) => {+ if (o.isSkinnedMesh && !o.userData.garmentSlot+ && (!body || o.geometry.attributes.position.count > body.geometry.attributes.position.count)) body = o;+ });+ const { clip: rClip } = retargetClipToObject(walkClip, root);+ if (!rClip) throw new Error('walk clip failed to retarget onto the audit avatar');++ const stats = gaitStats(root, body, res.meshes[0], rClip);+ const ceiling = P95_CEILING[m.slot] ?? 0.2;+ const flag = stats.p95 > ceiling ? ' << WARN p95 over slot ceiling' : '';+ if (flag) warns.push(label);+ console.log(+ `ok ${label.padEnd(52)} coverage=${res.coverage.toFixed(3)} `+ + `gait mean=${(stats.mean * 100).toFixed(1)}cm p95=${(stats.p95 * 100).toFixed(1)}cm `+ + `max=${(stats.max * 100).toFixed(1)}cm (n=${stats.n})${flag}`,+ );+ } catch (err) {+ hardFailures++;+ console.log(`FAIL ${label.padEnd(52)} ${err.message}`);+ }+}++console.log(`\n${garments.length} audited, ${hardFailures} hard failures, ${warns.length} review flags`+ + (warns.length ? `: ${warns.join(', ')}` : ''));+process.exit(hardFailures ? 1 : 0);diff --git a/tests/x402-ring-tick.test.js b/tests/x402-ring-tick.test.jsindex bd3092626..84b9b8152 100644--- a/tests/x402-ring-tick.test.js+++ b/tests/x402-ring-tick.test.js@@ -4,6 +4,7 @@ import {ringTickConfig,planTick,planBackpressure,+ governedCalls,minUsdcForTick,dailyRemaining,tickBudget,@@ -283,3 +284,61 @@ describe('price-vs-cap coherence', () => {}});});++describe('ring-tick runway governor', () => {+ const base = {+ configuredCalls: 94,+ floorLamports: 20_000_000, // 0.02 SOL untouchable floor+ feePerCallLamports: 7_000,+ runwayDays: 3,+ };++ it('rich payer runs at the configured rate, unthrottled', () => {+ // 5 SOL spendable / 3d / 7000 lamports = ~237k calls/day = 164/min > 94+ const g = governedCalls({ ...base, solLamports: 5_020_000_000 });+ expect(g.calls).toBe(94);+ expect(g.throttled).toBe(false);+ });++ it('lean payer throttles below the configured rate', () => {+ // 0.5 SOL spendable / 3d / 7000 = ~23.8k calls/day = 16/min+ const g = governedCalls({ ...base, solLamports: 520_000_000 });+ expect(g.calls).toBe(16);+ expect(g.throttled).toBe(true);+ });++ it('payer at the floor yields zero calls (runway exhausted)', () => {+ const g = governedCalls({ ...base, solLamports: 20_000_000 });+ expect(g.calls).toBe(0);+ expect(g.throttled).toBe(true);+ });++ it('below one call/min rounds down to zero, never negative', () => {+ // 0.01 SOL spendable / 3d / 7000 = 476/day < 1440+ const g = governedCalls({ ...base, solLamports: 30_000_000 });+ expect(g.calls).toBe(0);+ });++ it('NaN balance (RPC fault) fails closed to zero calls', () => {+ const g = governedCalls({ ...base, solLamports: Number.NaN });+ expect(g.calls).toBe(0);+ expect(g.throttled).toBe(true);+ });++ it('never raises above configuredCalls no matter the balance', () => {+ const g = governedCalls({ ...base, configuredCalls: 3, solLamports: 100_000_000_000 });+ expect(g.calls).toBe(3);+ });++ it('config exposes governor knobs with sane defaults and overrides', () => {+ const dflt = ringTickConfig({});+ expect(dflt.feePerCallLamports).toBe(7_000);+ expect(dflt.runwayDays).toBe(3);+ const set = ringTickConfig({+ X402_RING_FEE_PER_CALL_LAMPORTS: '6500',+ X402_RING_TARGET_RUNWAY_DAYS: '7',+ });+ expect(set.feePerCallLamports).toBe(6_500);+ expect(set.runwayDays).toBe(7);+ });+});diff --git a/workers/garment-forge/README.md b/workers/garment-forge/README.mdindex 05b56f1ef..7f7a7366f 100644--- a/workers/garment-forge/README.md+++ b/workers/garment-forge/README.md@@ -150,6 +150,15 @@ One-time infra the service depends on (already applied):python3 workers/garment-forge/test_garment_glb.py```+## Catalog quality audit++`npm run audit:garments` sweeps the LIVE catalog: consumer validation, sha256,+the real `attachGarment()` bind, and the walk-gait cloth-to-body deviation+metric for every published piece, with per-slot p95 ceilings. Hard failures+(validation reject, hash mismatch, attach refusal) exit non-zero, so run it+after any seeding batch or placement change; ceiling breaches are review+flags, printed with the numbers.+33 checks over the pure glTF pipeline: canonicalization, placement math,composition, body-strip + buffer repack, coverage/occludes derivation, andeach of the 6 manifest validation rules failing for its own reason. The samediff --git a/workers/garment-forge/pipeline.py b/workers/garment-forge/pipeline.pyindex 53bc703ee..eb0445940 100644--- a/workers/garment-forge/pipeline.py+++ b/workers/garment-forge/pipeline.py@@ -76,6 +76,24 @@ _SLOT_POSE_HINTS = {}+def _post_with_retry(client: httpx.Client, url: str, *, json_body: dict,+ headers: dict, attempts: int = 3) -> httpx.Response:+ """POST with bounded backoff on transient failures (429/5xx/network).+ 4xx other than 429 returns immediately: the caller handles semantics."""+ last_exc: Exception | None = None+ for attempt in range(attempts):+ try:+ res = client.post(url, json=json_body, headers=headers)+ if res.status_code == 429 or res.status_code >= 500:+ last_exc = RuntimeError(f"{url} returned {res.status_code}")+ else:+ return res+ except httpx.HTTPError as exc:+ last_exc = exc+ time.sleep(2.0 * (attempt + 1))+ raise RuntimeError(f"gave up after {attempts} attempts: {last_exc}")++def generate_reference_image(prompt: str, slot: str) -> tuple[bytes, str]:"""Text prompt → ghost-mannequin product photo via the platform's liveVertex AI image lane. Returns (png/jpeg bytes, model label)."""@@ -101,11 +119,11 @@ def generate_reference_image(prompt: str, slot: str) -> tuple[bytes, str]:headers = {"authorization": f"Bearer {_access_token()}","content-type": "application/json"}with httpx.Client(timeout=120) as client:- res = client.post(endpoint, json=body, headers=headers)+ res = _post_with_retry(client, endpoint, json_body=body, headers=headers)if res.status_code == 400:# Older image models reject the imageSize knob; retry without it.del body["generationConfig"]["imageConfig"]["imageSize"]- res = client.post(endpoint, json=body, headers=headers)+ res = _post_with_retry(client, endpoint, json_body=body, headers=headers)res.raise_for_status()data = res.json()@@ -131,10 +149,23 @@ def _poll_task(client: httpx.Client, base_url: str, task_id: str, api_key: str,timeout_s: float, result_field: str) -> str:deadline = time.time() + timeout_sheaders = {"authorization": f"Bearer {api_key}"}+ # A single flaky poll (worker restarting, LB hiccup, 502) must not kill a+ # multi-minute GPU job; only a persistent failure streak is a real outage.+ consecutive_errors = 0while time.time() < deadline:- res = client.get(f"{base_url}/tasks/{task_id}", headers=headers)- res.raise_for_status()- task = res.json()+ try:+ res = client.get(f"{base_url}/tasks/{task_id}", headers=headers)+ res.raise_for_status()+ task = res.json()+ except (httpx.HTTPError, ValueError) as exc:+ consecutive_errors += 1+ if consecutive_errors >= 6:+ raise RuntimeError(+ f"lost contact with {base_url} while polling {task_id}: {exc}"+ ) from exc+ time.sleep(MESH_POLL_S)+ continue+ consecutive_errors = 0status = task.get("status")if status == "done":url = task.get(result_field)