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.

Implement IRL proximity/room/sensor + AR lifecycle + animation retarget

nirholasc48ec8f7a0d9
diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.html
index d33a489a3..23a5395a1 100644
--- a/pages/ibm/x402-demo.html
+++ b/pages/ibm/x402-demo.html
@@ -3,62 +3,79 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
+<meta name="color-scheme" content="light">
<title>x402 live demo — three.ws × IBM</title>
<meta name="description" content="A live, self-contained x402 demo: pay $0.001 in USDC from your own wallet to call a real three.ws data API. Settled on-chain on Base or Solana. No backend, no account.">
-<link rel="preconnect" href="https://fonts.googleapis.com">
-<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
-<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
+<meta property="og:title" content="x402 live demo — three.ws × IBM">
+<meta property="og:description" content="Pay $0.001 in USDC from your own wallet to call a real three.ws API. See HTTP 402 micropayments settle on-chain in about a second.">
+<meta property="og:type" content="website">
<style>
+/* ─── Self-hosted IBM Plex (latin subset) — no third-party font CDN, so a
+ strict `font-src 'self'` CSP on the host page won't break typography.
+ Files travel with this page under ./fonts/. ─────────────────────────────── */
+@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:300;font-display:swap;src:url('./fonts/IBMPlexSans-300.woff2') format('woff2')}
+@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:400;font-display:swap;src:url('./fonts/IBMPlexSans-400.woff2') format('woff2')}
+@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:500;font-display:swap;src:url('./fonts/IBMPlexSans-500.woff2') format('woff2')}
+@font-face{font-family:'IBM Plex Sans';font-style:normal;font-weight:600;font-display:swap;src:url('./fonts/IBMPlexSans-600.woff2') format('woff2')}
+@font-face{font-family:'IBM Plex Mono';font-style:normal;font-weight:400;font-display:swap;src:url('./fonts/IBMPlexMono-400.woff2') format('woff2')}
+@font-face{font-family:'IBM Plex Mono';font-style:normal;font-weight:500;font-display:swap;src:url('./fonts/IBMPlexMono-500.woff2') format('woff2')}
+
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
--ibm-blue:#0f62fe;
--ibm-blue-hover:#0353e9;
--ibm-ink:#161616;
- --ibm-muted:#525252;
- --ibm-subtle:#6f6f6f;
+ --ibm-muted:#525252; /* AA on white (7.4:1) */
+ --ibm-subtle:#595959; /* AA on white (7:1) — was #6f6f6f (3.9:1, failed) */
--ibm-border:#e0e0e0;
--ibm-divider:#c6c6c6;
--ibm-field:#f4f4f4;
- --ibm-green:#198038;
+ --ibm-green:#0e7a32; /* darkened for AA on light fills */
--ibm-red:#da1e28;
- --ibm-amber:#8e6a00;
+ --ibm-amber:#8a6100;
+ --font-sans:'IBM Plex Sans',system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;
+ --font-mono:'IBM Plex Mono',ui-monospace,'SF Mono',Menlo,Consolas,monospace;
+ --ease:cubic-bezier(.2,.7,.3,1);
}
-html,body{
- background:transparent;
- font-family:'IBM Plex Sans',sans-serif;
- color:var(--ibm-ink);
- font-size:16px;line-height:1.5;
- -webkit-font-smoothing:antialiased;
-}
+html,body{background:transparent;font-family:var(--font-sans);color:var(--ibm-ink);font-size:16px;line-height:1.5;-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
a{color:var(--ibm-blue);text-decoration:none}
a:hover{text-decoration:underline}
-.mono{font-family:'IBM Plex Mono',monospace}
+.mono{font-family:var(--font-mono)}
+
+/* Visible focus everywhere — never rely on the UA default the reset removes. */
+:focus-visible{outline:2px solid var(--ibm-blue);outline-offset:2px}
+a:focus-visible{outline-offset:3px}
+
+.skip-link{position:absolute;left:-9999px;top:0;background:var(--ibm-blue);color:#fff;padding:10px 16px;z-index:50;font-weight:600;font-size:14px}
+.skip-link:focus{left:8px;top:8px;text-decoration:none}
.inner{max-width:880px;margin:0 auto;padding:0 16px}
.section{padding:40px 0;border-bottom:1px solid var(--ibm-border)}
.section:last-child{border-bottom:none}
+/* ── Global error banner (resilience safety net) ── */
+.err-banner{position:fixed;left:0;right:0;top:0;z-index:60;background:#fff1f1;border-bottom:1px solid #ffb3b8;color:#a2191f;font-size:13px;padding:10px 16px;display:none;align-items:center;gap:12px;justify-content:center}
+.err-banner.show{display:flex}
+.err-banner button{background:none;border:1px solid #ffb3b8;color:#a2191f;font-family:inherit;font-size:12px;font-weight:600;padding:4px 10px;cursor:pointer}
+.err-banner button:hover{background:#ffe0e0}
+
/* ── Hero ── */
.hero{padding:56px 0 36px}
-.partner-label{
- display:inline-flex;align-items:center;gap:12px;
- border:1px solid var(--ibm-border);padding:6px 14px;
- font-size:12px;letter-spacing:.08em;text-transform:uppercase;
- color:var(--ibm-muted);margin-bottom:28px;
-}
+.partner-label{display:inline-flex;align-items:center;gap:12px;border:1px solid var(--ibm-border);padding:6px 14px;font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-muted);margin-bottom:28px}
+.ibm-mark{font-family:var(--font-sans);font-weight:600;font-size:13px;letter-spacing:.02em;color:#fff;background:#0530ad;padding:3px 8px;line-height:1}
.hero h1{font-size:clamp(30px,5vw,46px);font-weight:300;line-height:1.1;margin-bottom:18px;max-width:680px}
.hero h1 strong{font-weight:600}
.hero-sub{font-size:18px;color:var(--ibm-muted);max-width:620px;font-weight:300;line-height:1.6}
-/* ── How-it-works strip ── */
-.steps{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--ibm-border);border:1px solid var(--ibm-border)}
+/* ── How-it-works ── */
+.steps{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--ibm-border);border:1px solid var(--ibm-border);list-style:none;margin-top:24px}
.step{background:#fff;padding:24px 22px}
-.step-n{font-family:'IBM Plex Mono',monospace;font-size:12px;color:var(--ibm-blue);font-weight:500;margin-bottom:10px}
+.step-n{font-family:var(--font-mono);font-size:12px;color:var(--ibm-blue);font-weight:500;margin-bottom:10px}
.step h3{font-size:15px;font-weight:600;margin-bottom:6px}
.step p{font-size:13px;color:var(--ibm-muted);font-weight:300;line-height:1.55}
-.step code{font-family:'IBM Plex Mono',monospace;font-size:12px;background:var(--ibm-field);padding:1px 5px;color:var(--ibm-ink)}
+.step code{font-family:var(--font-mono);font-size:12px;background:var(--ibm-field);padding:1px 5px;color:var(--ibm-ink);word-break:break-word}
/* ── Section heads ── */
.section-tag{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:var(--ibm-blue);margin-bottom:8px;font-weight:500}
@@ -80,96 +97,101 @@ a:hover{text-decoration:underline}
.demo-body{padding:22px 24px}
/* 402 preview */
-.preview{
- border:1px solid var(--ibm-border);background:var(--ibm-field);
- padding:14px 16px;margin-bottom:22px;font-family:'IBM Plex Mono',monospace;font-size:12px;
-}
-.preview-label{font-family:'IBM Plex Sans',sans-serif;font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--ibm-subtle);margin-bottom:10px;display:flex;align-items:center;gap:8px}
+.preview{border:1px solid var(--ibm-border);background:var(--ibm-field);padding:14px 16px;margin-bottom:22px;font-family:var(--font-mono);font-size:12px}
+.preview-label{font-family:var(--font-sans);font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--ibm-subtle);margin-bottom:10px;display:flex;align-items:center;gap:8px}
.preview-label .dot{width:7px;height:7px;border-radius:50%;background:var(--ibm-subtle);flex:0 0 auto}
.preview-label.ok .dot{background:var(--ibm-green)}
+.preview-label.ok.fresh .dot{animation:dotpulse 1.2s var(--ease) 1}
.preview-label.err .dot{background:var(--ibm-red)}
+@keyframes dotpulse{0%{box-shadow:0 0 0 0 rgba(14,122,50,.5)}100%{box-shadow:0 0 0 9px rgba(14,122,50,0)}}
.preview-row{display:flex;gap:12px;padding:3px 0;flex-wrap:wrap}
.preview-row .k{color:var(--ibm-subtle);min-width:84px}
.preview-row .v{color:var(--ibm-ink);word-break:break-all}
-.badge{display:inline-block;font-family:'IBM Plex Sans',sans-serif;font-size:11px;font-weight:500;padding:1px 8px;border:1px solid var(--ibm-divider);margin-right:6px;border-radius:2px}
+.badge{display:inline-block;font-family:var(--font-sans);font-size:11px;font-weight:500;padding:1px 8px;border:1px solid var(--ibm-divider);margin-right:6px;border-radius:2px}
+.pv-retry{margin-top:10px;background:none;border:1px solid var(--ibm-divider);color:var(--ibm-ink);font-family:var(--font-sans);font-size:12px;font-weight:500;padding:6px 12px;cursor:pointer}
+.pv-retry:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
+/* skeleton */
+.sk{height:11px;border-radius:2px;background:linear-gradient(90deg,#e8e8e8 25%,#f4f4f4 37%,#e8e8e8 63%);background-size:400% 100%;animation:sk 1.4s ease infinite}
+@keyframes sk{0%{background-position:100% 0}100%{background-position:0 0}}
/* input row */
-.field-row{display:flex;gap:0;flex-wrap:wrap;align-items:stretch;margin-bottom:18px}
+.field-row{display:flex;gap:0;flex-wrap:wrap;align-items:flex-end;margin-bottom:10px}
.field-wrap{flex:1 1 240px;min-width:0}
.field-wrap label{display:block;font-size:12px;color:var(--ibm-muted);margin-bottom:6px;font-weight:500}
-.field{
- width:100%;height:48px;padding:0 14px;border:none;border-bottom:1px solid var(--ibm-divider);
- background:var(--ibm-field);font-family:'IBM Plex Mono',monospace;font-size:15px;color:var(--ibm-ink);
- letter-spacing:.04em;outline:none;transition:border-color .12s,background .12s;
-}
+.field{width:100%;height:48px;padding:0 14px;border:none;border-bottom:1px solid var(--ibm-divider);background:var(--ibm-field);font-family:var(--font-mono);font-size:15px;color:var(--ibm-ink);letter-spacing:.04em;outline:none;transition:border-color .12s,background .12s}
.field:focus{border-bottom:2px solid var(--ibm-blue);background:#fff}
+.field[aria-invalid="true"]{border-bottom:2px solid var(--ibm-red)}
.field-hint{font-size:11px;color:var(--ibm-subtle);margin-top:6px}
+.field-hint.err{color:var(--ibm-red)}
-.btn{
- display:inline-flex;align-items:center;justify-content:center;gap:10px;
- background:var(--ibm-blue);color:#fff;border:none;cursor:pointer;
- font-family:'IBM Plex Sans',sans-serif;font-size:15px;font-weight:500;letter-spacing:.01em;
- padding:0 24px;height:48px;min-width:200px;align-self:flex-end;
- transition:background .12s,transform .04s;
-}
+.btn{display:inline-flex;align-items:center;justify-content:center;gap:10px;background:var(--ibm-blue);color:#fff;border:none;cursor:pointer;font-family:var(--font-sans);font-size:15px;font-weight:500;letter-spacing:.01em;padding:0 24px;height:48px;min-width:200px;transition:background .12s,transform .04s}
.btn:hover:not(:disabled){background:var(--ibm-blue-hover)}
.btn:active:not(:disabled){transform:translateY(1px)}
.btn:disabled{background:#c6c6c6;cursor:not-allowed}
.btn .arrow{font-size:17px;line-height:1}
+.btn .spin{width:15px;height:15px;border:2px solid rgba(255,255,255,.45);border-top-color:#fff;border-radius:50%;animation:spin .7s linear infinite;display:none}
+.btn.loading .spin{display:inline-block}
+.btn.loading .arrow{display:none}
@media(min-width:560px){.btn{margin-left:1px}}
+.wallet-hint{font-size:11px;color:var(--ibm-subtle);margin-bottom:18px;line-height:1.5}
+.wallet-hint.offline{color:var(--ibm-amber);font-weight:500}
+
/* result panel */
.result{border:1px solid var(--ibm-border);min-height:96px;padding:18px 20px;background:#fff;transition:border-color .15s}
.result.is-empty{display:flex;align-items:center;justify-content:center;color:var(--ibm-subtle);font-size:13px;text-align:center;font-weight:300;border-style:dashed}
.result.is-loading{border-color:var(--ibm-blue)}
.result.is-error{border-color:var(--ibm-red)}
-.result.is-done{border-color:var(--ibm-green)}
+.result.is-done{border-color:var(--ibm-green);animation:reveal .28s var(--ease)}
+@keyframes reveal{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
-.r-status{display:flex;align-items:center;gap:10px;font-size:13px;font-weight:500;margin-bottom:0}
+.r-status{display:flex;align-items:center;gap:10px;font-size:13px;font-weight:500}
.r-status .spin{width:14px;height:14px;border:2px solid var(--ibm-divider);border-top-color:var(--ibm-blue);border-radius:50%;animation:spin .8s linear infinite;flex:0 0 auto}
@keyframes spin{to{transform:rotate(360deg)}}
.r-status.err{color:var(--ibm-red)}
+.r-status.ok{color:var(--ibm-green)}
+.r-check{display:inline-flex;width:18px;height:18px;border-radius:50%;background:var(--ibm-green);color:#fff;align-items:center;justify-content:center;font-size:11px;flex:0 0 auto;animation:pop .3s var(--ease)}
+@keyframes pop{0%{transform:scale(0)}60%{transform:scale(1.15)}100%{transform:scale(1)}}
-.r-headline{font-size:18px;font-weight:300;margin:2px 0 4px}
+.r-headline{font-size:18px;font-weight:300;margin:12px 0 4px}
.r-headline strong{font-weight:600}
.r-reco{font-size:14px;color:var(--ibm-ink);margin-bottom:14px;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.pill{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.05em;padding:2px 9px;border-radius:2px}
.pill.ok{background:#defbe6;color:var(--ibm-green)}
-.pill.warn{background:#fff8e1;color:var(--ibm-amber)}
-.pill.bad{background:#fff1f1;color:var(--ibm-red)}
+.pill.warn{background:#fcf4d6;color:var(--ibm-amber)}
+.pill.bad{background:#fff1f1;color:#a2191f}
.matches{border-top:1px solid var(--ibm-border);margin-top:6px;padding-top:12px}
.matches h4{font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--ibm-subtle);margin-bottom:8px;font-weight:600}
.match{display:flex;justify-content:space-between;gap:12px;padding:5px 0;font-size:13px;border-bottom:1px solid var(--ibm-field)}
.match:last-child{border-bottom:none}
-.match .m-name{color:var(--ibm-ink)}
+.match .m-name{color:var(--ibm-ink);min-width:0;word-break:break-word}
.match .m-name b{font-weight:600}
-.match .m-sim{font-family:'IBM Plex Mono',monospace;color:var(--ibm-muted);font-size:12px;flex:0 0 auto}
+.match .m-sim{font-family:var(--font-mono);color:var(--ibm-muted);font-size:12px;flex:0 0 auto}
.receipt{margin-top:14px;padding-top:12px;border-top:1px solid var(--ibm-border);display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px 20px}
.receipt .rk{font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--ibm-subtle);margin-bottom:2px}
-.receipt .rv{font-family:'IBM Plex Mono',monospace;font-size:12px;color:var(--ibm-ink);word-break:break-all}
+.receipt .rv{font-family:var(--font-mono);font-size:12px;color:var(--ibm-ink);word-break:break-all}
.raw{margin-top:14px}
.raw summary{cursor:pointer;font-size:12px;color:var(--ibm-muted);font-weight:500;user-select:none}
.raw summary:hover{color:var(--ibm-blue)}
-.raw pre{margin-top:10px;background:#161616;color:#e0e0e0;padding:14px 16px;overflow:auto;max-height:300px;font-family:'IBM Plex Mono',monospace;font-size:12px;line-height:1.5}
+.raw pre{margin-top:10px;background:#161616;color:#e0e0e0;padding:14px 16px;overflow:auto;max-height:300px;font-family:var(--font-mono);font-size:12px;line-height:1.5}
.retry{margin-top:14px;background:none;border:1px solid var(--ibm-divider);color:var(--ibm-ink);padding:9px 16px;font-family:inherit;font-size:13px;font-weight:500;cursor:pointer;transition:border-color .12s,color .12s}
.retry:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
-/* requirements note */
.note{display:flex;gap:14px;margin-top:22px;padding:16px 18px;border:1px solid var(--ibm-border);background:var(--ibm-field)}
.note svg{flex:0 0 auto;width:20px;height:20px;color:var(--ibm-blue);margin-top:1px}
.note p{font-size:13px;color:var(--ibm-muted);line-height:1.6;font-weight:300}
.note p b{color:var(--ibm-ink);font-weight:600}
/* embed snippet */
-.embed-block{background:#161616;color:#e0e0e0;border:1px solid #393939;padding:18px 20px;overflow:auto;margin-top:24px;font-family:'IBM Plex Mono',monospace;font-size:13px;line-height:1.6}
+.embed-block{background:#161616;color:#e0e0e0;border:1px solid #393939;padding:18px 20px;overflow:auto;margin-top:24px;font-family:var(--font-mono);font-size:13px;line-height:1.6;white-space:pre}
.embed-block .c-tag{color:#82cfff}
.embed-block .c-attr{color:#a6c8ff}
.embed-block .c-str{color:#a7f0ba}
-.embed-block .c-com{color:#8d8d8d}
+.embed-block .c-com{color:#a8a8a8}
.copy-row{display:flex;justify-content:flex-end;margin-top:10px}
.copy-btn{background:none;border:1px solid var(--ibm-divider);color:var(--ibm-muted);font-family:inherit;font-size:12px;font-weight:500;padding:7px 14px;cursor:pointer;transition:border-color .12s,color .12s}
.copy-btn:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
@@ -185,56 +207,71 @@ a:hover{text-decoration:underline}
.steps{grid-template-columns:1fr}
.demo-head{flex-direction:column;align-items:flex-start}
.price-tag{text-align:left}
- .btn{width:100%;align-self:stretch}
+ .field-row{gap:14px}
+ .btn{width:100%;min-width:0}
+}
+
+@media(prefers-reduced-motion:reduce){
+ *,*::before,*::after{animation-duration:.001ms!important;animation-iteration-count:1!important;transition-duration:.001ms!important}
}
</style>
</head>
<body>
+<a href="#demo" class="skip-link">Skip to the demo</a>
+
+<div class="err-banner" id="errBanner" role="alert">
+ <span id="errBannerText">Something went wrong.</span>
+ <button type="button" id="errBannerClose">Dismiss</button>
+</div>
+
<!-- ══ HERO ══ -->
-<div class="hero">
+<header class="hero">
<div class="inner">
<div class="partner-label">
- <svg width="40" height="16" viewBox="0 0 48 19" fill="none" aria-hidden="true"><rect width="48" height="19" fill="#1F70C1"/><text x="4" y="14" font-family="Arial" font-size="11" font-weight="700" fill="white">IBM</text></svg>
+ <!-- IBM brand: neutral wordmark lockup. Confirm exact mark + "Business Partner"
+ usage rights with IBM before public launch (see task 08 / HOSTING.md). -->
+ <span class="ibm-mark">IBM</span>
<span>Business Partner</span>
- <span style="color:var(--ibm-border)">|</span>
+ <span style="color:var(--ibm-border)" aria-hidden="true">|</span>
<span class="mono">three.ws</span>
</div>
<h1>See <strong>x402</strong> work — pay a fraction of a cent for a real API call</h1>
<p class="hero-sub">x402 turns the dormant HTTP <span class="mono">402 Payment Required</span> status into a payment rail. A normal request comes back with machine-readable payment terms; your wallet signs a stablecoin authorization and retries; the call settles on-chain in about a second. No keys, no account, no invoice. Try it below with your own wallet.</p>
</div>
-</div>
+</header>
+<main>
<!-- ══ HOW IT WORKS ══ -->
-<div class="section">
+<section class="section" aria-labelledby="how-h">
<div class="inner">
<div class="section-tag">The protocol in three moves</div>
- <h2>How <strong>x402</strong> works</h2>
- <div class="steps" style="margin-top:24px">
- <div class="step">
+ <h2 id="how-h">How <strong>x402</strong> works</h2>
+ <ol class="steps">
+ <li class="step">
<div class="step-n">01 · REQUEST</div>
<h3>You ask normally</h3>
<p>A plain <code>GET</code> to a paid endpoint — no payment attached yet.</p>
- </div>
- <div class="step">
+ </li>
+ <li class="step">
<div class="step-n">02 · 402 CHALLENGE</div>
<h3>Server quotes a price</h3>
<p>It replies <code>402</code> with exactly what it wants: amount, asset, network, and the address to pay.</p>
- </div>
- <div class="step">
+ </li>
+ <li class="step">
<div class="step-n">03 · PAY &amp; RETRY</div>
<h3>Wallet signs, call settles</h3>
<p>You sign a gasless USDC authorization, resend with an <code>X-PAYMENT</code> header, and get your data.</p>
- </div>
- </div>
+ </li>
+ </ol>
</div>
-</div>
+</section>
<!-- ══ LIVE DEMO ══ -->
-<div class="section">
+<section class="section" id="demo" aria-labelledby="demo-h">
<div class="inner">
<div class="section-tag">Live · production endpoint</div>
- <h2>Buy a <strong>data call</strong> for $0.001</h2>
+ <h2 id="demo-h">Buy a <strong>data call</strong> for $0.001</h2>
<p class="section-lead">This calls a real three.ws API — a token-symbol availability check — for one tenth of a cent in USDC, settled on Base or Solana mainnet. Nothing here is mocked: the price below is read live from the server's own 402 response.</p>
<div class="demo">
@@ -251,20 +288,25 @@ a:hover{text-decoration:underline}
<div class="demo-body">
<!-- live 402 preview -->
- <div class="preview" aria-live="polite">
+ <div class="preview" aria-live="polite" aria-busy="true">
<div class="preview-label" id="pvLabel"><span class="dot"></span><span id="pvLabelText">Reading the server's 402 challenge…</span></div>
- <div id="pvRows"></div>
+ <div id="pvRows">
+ <div class="preview-row"><span class="sk" style="width:38%"></span></div>
+ <div class="preview-row"><span class="sk" style="width:54%"></span></div>
+ <div class="preview-row"><span class="sk" style="width:46%"></span></div>
+ </div>
</div>
<!-- input -->
<div class="field-row">
<div class="field-wrap">
<label for="ticker">Ticker to check</label>
- <input id="ticker" class="field" value="GRANITE" maxlength="32" autocomplete="off" spellcheck="false" aria-describedby="tickerHint">
+ <input id="ticker" class="field" value="GRANITE" maxlength="32" autocomplete="off" spellcheck="false" inputmode="latin" aria-describedby="tickerHint">
<div class="field-hint" id="tickerHint">A–Z and 0–9, up to 32 characters.</div>
</div>
- <button id="payBtn" class="btn">Pay $0.001 &amp; run <span class="arrow">→</span></button>
+ <button id="payBtn" class="btn" type="button"><span class="spin" aria-hidden="true"></span><span class="label">Pay $0.001 &amp; run</span> <span class="arrow" aria-hidden="true">→</span></button>
</div>
+ <div class="wallet-hint" id="walletHint">On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.</div>
<!-- result -->
<div id="result" class="result is-empty" role="status" aria-live="polite">
@@ -274,18 +316,18 @@ a:hover{text-decoration:underline}
<!-- requirements -->
<div class="note">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>
- <p>You'll need a browser wallet — <b>MetaMask</b> (for Base) or <b>Phantom</b> (for Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends real funds, but only a tenth of a cent. The payment is a gasless signature; the network fee is sponsored. Don't have a wallet? You can still watch the 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>.</p>
+ <p>You'll need a browser wallet — <b>MetaMask</b> (for Base) or <b>Phantom</b> (for Solana) — holding at least <b>$0.001 USDC</b> on mainnet. This spends real funds, but only a tenth of a cent. The payment is a gasless signature; the network fee is sponsored by the facilitator. No wallet? You can still watch the 402 challenge above and read the <a href="https://three.ws/docs/x402" target="_blank" rel="noopener">protocol docs</a>.</p>
</div>
</div>
</div>
</div>
-</div>
+</section>
<!-- ══ EMBED ══ -->
-<div class="section">
+<section class="section" aria-labelledby="embed-h">
<div class="inner">
<div class="section-tag">For developers</div>
- <h2>Add a paywall in <strong>eight lines</strong></h2>
+ <h2 id="embed-h">Add a paywall in <strong>eight lines</strong></h2>
<p class="section-lead">The button above is powered by one drop-in script. Any element with a <span class="mono">data-x402-endpoint</span> opens the wallet flow on click — no framework, no build step, no SDK.</p>
<div class="embed-block" id="embedCode"><span class="c-com">&lt;!-- one script tag, served from three.ws --&gt;</span>
<span class="c-tag">&lt;script</span> <span class="c-attr">type</span>=<span class="c-str">"module"</span> <span class="c-attr">src</span>=<span class="c-str">"https://three.ws/x402.js"</span><span class="c-tag">&gt;&lt;/script&gt;</span>
@@ -297,14 +339,15 @@ a:hover{text-decoration:underline}
<span class="c-attr">data-x402-action</span>=<span class="c-str">"Check symbol"</span><span class="c-tag">&gt;</span>
Pay $0.001 &amp; run
<span class="c-tag">&lt;/button&gt;</span></div>
- <div class="copy-row"><button class="copy-btn" id="copyBtn">Copy snippet</button></div>
+ <div class="copy-row"><button class="copy-btn" id="copyBtn" type="button">Copy snippet</button></div>
</div>
-</div>
+</section>
+</main>
<!-- ══ FOOTER ══ -->
-<div class="footer">
+<footer class="footer">
<div class="inner">
- <nav class="footer-nav">
+ <nav class="footer-nav" aria-label="Footer">
<a href="https://three.ws" target="_blank" rel="noopener">Platform</a>
<a href="https://three.ws/docs/x402" target="_blank" rel="noopener">x402 Protocol</a>
<a href="https://three.ws/docs/ibm-x402" target="_blank" rel="noopener">IBM × x402 Docs</a>
@@ -315,7 +358,7 @@ a:hover{text-decoration:underline}
Live x402 demo · three.ws, an IBM Business Partner. Payments settle in USDC on Base or Solana mainnet via the x402 protocol. The only coin this platform issues is $THREE (FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump).
</div>
</div>
-</div>
+</footer>
<!-- x402 drop-in payment modal (Phantom/MetaMask wallet flow + 402 retry) -->
<script type="module" src="https://three.ws/x402.js"></script>
@@ -325,13 +368,31 @@ a:hover{text-decoration:underline}
'use strict';
// The paid endpoint this demo calls. Swap to any three.ws x402 GET endpoint
- // (e.g. /api/x402/skill-marketplace) and the page adapts automatically.
+ // and the price tag + 402 preview adapt automatically (the result renderer is
+ // shaped for symbol-availability — update renderResultDone if you change it).
var ENDPOINT = 'https://three.ws/api/x402/symbol-availability';
// Per-call spend ceiling (micro-USD) handed to the widget as a safety rail:
// $0.01, so a $0.001 call always clears but a misconfigured price can't drain.
var MAX_PER_CALL_MICRO_USD = 10000;
var $ = function (id) { return document.getElementById(id); };
+ var inFlight = false;
+
+ // ── global resilience net ────────────────────────────────────────────────
+ function showBanner(msg) {
+ var b = $('errBanner'); if (!b) return;
+ $('errBannerText').textContent = msg || 'Something went wrong. Reload the page if it persists.';
+ b.classList.add('show');
+ }
+ window.addEventListener('error', function (e) {
+ // Ignore benign ResizeObserver noise; surface anything real, non-fatally.
+ if (e && e.message && /ResizeObserver/.test(e.message)) return;
+ showBanner('A script error occurred. The demo may be degraded — reload to recover.');
+ });
+ window.addEventListener('unhandledrejection', function () {
+ showBanner('A background request failed. Check your connection and try again.');
+ });
+ $('errBannerClose').addEventListener('click', function () { $('errBanner').classList.remove('show'); });
function escapeHtml(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
@@ -343,15 +404,17 @@ a:hover{text-decoration:underline}
}
function shortAddr(a) {
if (!a) return '—';
+ a = String(a);
return a.length > 16 ? a.slice(0, 6) + '…' + a.slice(-4) : a;
}
function fmtUsd(atomics, decimals) {
var n = Number(atomics) / Math.pow(10, decimals == null ? 6 : decimals);
+ if (!isFinite(n)) return '$—';
if (n < 0.01) return '$' + n.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
return '$' + n.toFixed(2);
}
function networkLabel(net) {
- if (!net) return net;
+ if (!net) return '—';
if (net.indexOf('solana') === 0) return 'Solana';
if (net === 'eip155:8453') return 'Base';
if (net.indexOf('eip155:') === 0) return 'EVM ' + net.split(':')[1];
@@ -364,48 +427,42 @@ a:hover{text-decoration:underline}
return null;
}
- // ── 1. Read the live 402 challenge so visitors see the real, current terms ──
+ // ── 1. live 402 challenge preview ─────────────────────────────────────────
function loadChallengePreview() {
var ticker = sanitizeTicker($('ticker').value) || 'GRANITE';
+ var preview = document.querySelector('.preview');
+ if (preview) preview.setAttribute('aria-busy', 'true');
fetch(ENDPOINT + '?ticker=' + encodeURIComponent(ticker), { method: 'GET' })
.then(function (res) {
- // Standard x402: 402 with the envelope in the body (and PAYMENT-REQUIRED header).
- if (res.status !== 402 && res.status !== 401) {
- throw new Error('Expected 402, got ' + res.status);
- }
+ if (res.status !== 402 && res.status !== 401) throw new Error('expected 402, got ' + res.status);
return res.json().catch(function () { return null; });
})
.then(function (body) {
var accepts = (body && body.accepts) || [];
- if (!accepts.length) throw new Error('No payment terms in challenge');
+ if (!accepts.length) throw new Error('no payment terms in challenge');
renderChallengePreview(accepts);
})
.catch(function (err) {
var label = $('pvLabel'); label.className = 'preview-label err';
- $('pvLabelText').textContent = 'Could not reach the endpoint (' + err.message + '). The demo still works once it is back.';
- $('pvRows').innerHTML = '';
- });
+ $('pvLabelText').textContent = 'Could not reach the endpoint (' + err.message + ').';
+ $('pvRows').innerHTML = '<button class="pv-retry" type="button" id="pvRetry">Retry</button>';
+ var r = $('pvRetry'); if (r) r.addEventListener('click', loadChallengePreview);
+ })
+ .then(function () { if (preview) preview.setAttribute('aria-busy', 'false'); });
}
function renderChallengePreview(accepts) {
- // Dedupe to one entry per network (the server advertises a Permit2 sibling
- // on Base that the browser modal doesn't use — collapse it for clarity).
var byNet = {};
- accepts.forEach(function (a) {
- var key = a.network;
- if (!byNet[key] || (a.extra && a.extra.assetTransferMethod === 'permit2' && byNet[key].extra && byNet[key].extra.assetTransferMethod === 'permit2')) {
- if (!byNet[key]) byNet[key] = a;
- }
- });
+ accepts.forEach(function (a) { if (a && a.network && !byNet[a.network]) byNet[a.network] = a; });
var nets = Object.keys(byNet).map(function (k) { return byNet[k]; });
var first = nets[0];
var decimals = (first.extra && first.extra.decimals) || 6;
$('priceAmt').innerHTML = first.amount === '1000'
? '$<strong>0.001</strong>'
- : fmtUsd(first.amount, decimals).replace(/^\$/, '$<strong>') + '</strong>';
+ : escapeHtml(fmtUsd(first.amount, decimals)).replace(/^\$/, '$<strong>') + '</strong>';
- var label = $('pvLabel'); label.className = 'preview-label ok';
+ var label = $('pvLabel'); label.className = 'preview-label ok fresh';
$('pvLabelText').innerHTML = '<span class="mono">HTTP 402 Payment Required</span> — the server is quoting these terms right now';
var rows = '';
@@ -419,46 +476,38 @@ a:hover{text-decoration:underline}
$('pvRows').innerHTML = rows;
}
- // ── 2. Result rendering states ───────────────────────────────────────────
+ // ── 2. result states ──────────────────────────────────────────────────────
function setResultEmpty() {
- var el = $('result');
- el.className = 'result is-empty';
+ var el = $('result'); el.className = 'result is-empty';
el.innerHTML = 'Run the call to see live, on-chain-paid data appear here.';
}
function setResultLoading(msg) {
- var el = $('result');
- el.className = 'result is-loading';
- el.innerHTML = '<div class="r-status"><span class="spin"></span><span>' + escapeHtml(msg || 'Waiting for your wallet…') + '</span></div>';
+ var el = $('result'); el.className = 'result is-loading';
+ el.innerHTML = '<div class="r-status"><span class="spin" aria-hidden="true"></span><span>' + escapeHtml(msg || 'Waiting for your wallet…') + '</span></div>';
}
function setResultError(msg) {
- var el = $('result');
- el.className = 'result is-error';
- el.innerHTML =
- '<div class="r-status err">✕ <span>' + escapeHtml(msg || 'Something went wrong.') + '</span></div>' +
- '<button class="retry" id="retryBtn">Try again</button>';
+ var el = $('result'); el.className = 'result is-error';
+ el.innerHTML = '<div class="r-status err">✕ <span>' + escapeHtml(msg || 'Something went wrong.') + '</span></div><button class="retry" type="button" id="retryBtn">Try again</button>';
var rb = $('retryBtn'); if (rb) rb.addEventListener('click', runPayment);
}
-
function recoPill(result) {
if (result.exact_collision) return '<span class="pill bad">taken</span>';
var sim = result.similar && result.similar[0];
- if (sim && sim.similarity >= 0.8) return '<span class="pill warn">close match</span>';
+ if (sim && Number(sim.similarity) >= 0.8) return '<span class="pill warn">close match</span>';
return '<span class="pill ok">available</span>';
}
-
function setResultDone(out) {
var result = out.result || {};
var payment = out.payment || {};
- var el = $('result');
- el.className = 'result is-done';
+ var el = $('result'); el.className = 'result is-done';
var html = '';
- html += '<div class="r-status" style="color:var(--ibm-green)">✓ <span>Payment settled — response delivered</span></div>';
- html += '<div class="r-headline" style="margin-top:12px">Ticker <strong>$' + escapeHtml(result.ticker || '') + '</strong></div>';
- html += '<div class="r-reco">' + recoPill(result) + '<span>' + escapeHtml(result.recommendation || '') + '</span></div>';
+ html += '<div class="r-status ok"><span class="r-check" aria-hidden="true">✓</span><span>Payment settled — response delivered</span></div>';
+ if (result.ticker) html += '<div class="r-headline">Ticker <strong>$' + escapeHtml(result.ticker) + '</strong></div>';
+ if (result.recommendation) html += '<div class="r-reco">' + recoPill(result) + '<span>' + escapeHtml(result.recommendation) + '</span></div>';
- var exact = result.exact_matches || [];
- var similar = result.similar || [];
+ var exact = Array.isArray(result.exact_matches) ? result.exact_matches : [];
+ var similar = Array.isArray(result.similar) ? result.similar : [];
if (exact.length || similar.length) {
html += '<div class="matches">';
if (exact.length) {
@@ -476,33 +525,43 @@ a:hover{text-decoration:underline}
html += '</div>';
}
- // on-chain receipt
var explorer = explorerUrl(payment.network, payment.transaction);
html += '<div class="receipt">';
- html += '<div><div class="rk">Network</div><div class="rv">' + escapeHtml(networkLabel(payment.network) || '—') + '</div></div>';
+ html += '<div><div class="rk">Network</div><div class="rv">' + escapeHtml(networkLabel(payment.network)) + '</div></div>';
html += '<div><div class="rk">Payer</div><div class="rv">' + escapeHtml(shortAddr(payment.payer)) + '</div></div>';
html += '<div><div class="rk">Transaction</div><div class="rv">' +
(payment.transaction
? (explorer ? '<a href="' + explorer + '" target="_blank" rel="noopener">' + escapeHtml(shortAddr(payment.transaction)) + ' ↗</a>' : escapeHtml(shortAddr(payment.transaction)))
- : '—') +
- '</div></div>';
+ : '—') + '</div></div>';
html += '</div>';
- // raw payload for the curious
html += '<details class="raw"><summary>View raw response &amp; settlement</summary><pre>' +
- escapeHtml(JSON.stringify({ response: result, payment: payment }, null, 2)).slice(0, 6000) +
- '</pre></details>';
+ escapeHtml(JSON.stringify({ response: result, payment: payment }, null, 2)).slice(0, 6000) + '</pre></details>';
el.innerHTML = html;
}
- // ── 3. Drive the payment via the drop-in widget ──────────────────────────
+ // ── 3. payment ────────────────────────────────────────────────────────────
+ function setBusy(b) {
+ inFlight = b;
+ var btn = $('payBtn');
+ btn.disabled = b || !navigator.onLine;
+ btn.classList.toggle('loading', b);
+ btn.querySelector('.label').textContent = b ? 'Working…' : 'Pay $0.001 & run';
+ }
+ function setTickerError(msg) {
+ var f = $('ticker'); var h = $('tickerHint');
+ if (msg) { f.setAttribute('aria-invalid', 'true'); h.className = 'field-hint err'; h.textContent = msg; }
+ else { f.removeAttribute('aria-invalid'); h.className = 'field-hint'; h.textContent = 'A–Z and 0–9, up to 32 characters.'; }
+ }
+
function runPayment() {
+ if (inFlight) return; // double-click guard
+ if (!navigator.onLine) { setResultError('You appear to be offline. Reconnect and try again.'); return; }
+
var ticker = sanitizeTicker($('ticker').value);
- if (!ticker) {
- setResultError('Enter a ticker (A–Z, 0–9) to check.');
- return;
- }
+ if (!ticker) { setTickerError('Enter a ticker (A–Z, 0–9) to check.'); $('ticker').focus(); return; }
+ setTickerError(null);
$('ticker').value = ticker;
if (!window.X402 || typeof window.X402.pay !== 'function') {
@@ -510,11 +569,12 @@ a:hover{text-decoration:underline}
return;
}
+ var trigger = document.activeElement; // restore focus here when the modal closes
+ setBusy(true);
setResultLoading('Opening wallet… approve the $0.001 USDC payment to continue.');
- var endpoint = ENDPOINT + '?ticker=' + encodeURIComponent(ticker);
window.X402.pay({
- endpoint: endpoint,
+ endpoint: ENDPOINT + '?ticker=' + encodeURIComponent(ticker),
method: 'GET',
merchant: 'three.ws',
action: 'Check $' + ticker + ' availability',
@@ -524,16 +584,36 @@ a:hover{text-decoration:underline}
else setResultError('The call did not complete. Please try again.');
}).catch(function (err) {
if (err && err.code === 'cancelled') { setResultEmpty(); return; }
- setResultError((err && err.message) || 'Payment failed.');
+ setResultError((err && err.message) || 'Payment failed. Please try again.');
+ }).then(function () {
+ setBusy(false);
+ var t = (trigger && trigger.focus) ? trigger : $('payBtn');
+ try { t.focus(); } catch (_) {}
});
}
- // ── wiring ───────────────────────────────────────────────────────────────
+ // ── offline awareness ──────────────────────────────────────────────────────
+ function syncOnline() {
+ var hint = $('walletHint'); var btn = $('payBtn');
+ if (!navigator.onLine) {
+ hint.classList.add('offline');
+ hint.innerHTML = 'You are offline. Reconnect to read the live price and pay.';
+ btn.disabled = true;
+ } else {
+ hint.classList.remove('offline');
+ hint.innerHTML = 'On a phone? Open this page inside your <b>MetaMask</b> or <b>Phantom</b> in-app browser to pay.';
+ if (!inFlight) btn.disabled = false;
+ }
+ }
+ window.addEventListener('online', function () { syncOnline(); loadChallengePreview(); });
+ window.addEventListener('offline', syncOnline);
+
+ // ── wiring ──────────────────────────────────────────────────────────────────
$('payBtn').addEventListener('click', runPayment);
- $('ticker').addEventListener('keydown', function (e) { if (e.key === 'Enter') runPayment(); });
- // Refresh the live 402 preview when the ticker changes (debounced).
+ $('ticker').addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); runPayment(); } });
var pvTimer;
$('ticker').addEventListener('input', function () {
+ setTickerError(null);
clearTimeout(pvTimer);
pvTimer = setTimeout(loadChallengePreview, 400);
});
@@ -547,16 +627,15 @@ a:hover{text-decoration:underline}
' data-x402-action="Check symbol">\n' +
' Pay $0.001 & run\n' +
'</button>';
- navigator.clipboard.writeText(snippet).then(function () {
- var b = $('copyBtn'); var t = b.textContent;
- b.textContent = 'Copied ✓';
- setTimeout(function () { b.textContent = t; }, 1600);
- }).catch(function () {
- var b = $('copyBtn'); b.textContent = 'Copy failed';
- setTimeout(function () { b.textContent = 'Copy snippet'; }, 1600);
- });
+ var done = function (label) { var b = $('copyBtn'); b.textContent = label; setTimeout(function () { b.textContent = 'Copy snippet'; }, 1600); };
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(snippet).then(function () { done('Copied ✓'); }, function () { done('Copy failed — select manually'); });
+ } else {
+ done('Select the code above to copy');
+ }
});
+ syncOnline();
loadChallengePreview();
})();
</script>
diff --git a/scripts/build-canonical-rest.mjs b/scripts/build-canonical-rest.mjs
new file mode 100644
index 000000000..2280312e8
--- /dev/null
+++ b/scripts/build-canonical-rest.mjs
@@ -0,0 +1,77 @@
+// Generate the canonical authoring rest pose for animation retargeting.
+//
+// The pre-baked clip library (public/animations/clips/*.json) stores ABSOLUTE
+// local bone rotations authored against one reference rig: the Avaturn-rigged
+// public/avatars/cz.glb (clips play on it verbatim with zero correction). To
+// drive a rig with a different rest pose (e.g. a Mixamo T-pose vs cz's A-pose),
+// src/animation-retarget.js replays each clip bone's deviation-from-rest in the
+// target rig's own rest frame: Ta = Tr · Sr⁻¹ · Sa, where Sr is THIS file.
+//
+// We emit cz.glb's bone rotations VERBATIM (the exact JSON numbers) so that
+// retargeting back onto cz yields C = Tr · Sr⁻¹ = identity (within FP noise) and
+// the clip round-trips byte-for-byte — the absolute no-regression invariant.
+//
+// Run: node scripts/build-canonical-rest.mjs
+// Reads: public/avatars/cz.glb
+// Writes: src/animation-canonical-rest.js
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { canonicalizeBoneName } from '../src/glb-canonicalize.js';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const REFERENCE_RIG = path.join(ROOT, 'public/avatars/cz.glb');
+const OUT = path.join(ROOT, 'src/animation-canonical-rest.js');
+
+// Parse the JSON chunk of a binary glTF (GLB) without three/DOM.
+function readGlbJson(file) {
+ const buf = fs.readFileSync(file);
+ const magic = buf.readUInt32LE(0);
+ if (magic !== 0x46546c67) throw new Error(`${file}: not a GLB (bad magic)`);
+ const chunkLen = buf.readUInt32LE(12);
+ const chunkType = buf.readUInt32LE(16);
+ if (chunkType !== 0x4e4f534a) throw new Error(`${file}: first chunk is not JSON`);
+ return JSON.parse(buf.slice(20, 20 + chunkLen).toString('utf8'));
+}
+
+const gltf = readGlbJson(REFERENCE_RIG);
+const nodes = gltf.nodes || [];
+
+// First occurrence wins, matching canonicalRestMapFromObject's traversal order.
+const rest = new Map();
+for (const node of nodes) {
+ if (!node?.name) continue;
+ const canonical = canonicalizeBoneName(node.name);
+ if (!canonical || rest.has(canonical)) continue;
+ // glTF node rotation defaults to identity [0,0,0,1] when omitted.
+ const r = Array.isArray(node.rotation) ? node.rotation : [0, 0, 0, 1];
+ rest.set(canonical, r);
+}
+
+if (rest.size === 0) throw new Error(`${REFERENCE_RIG}: no canonical bones found`);
+
+// Stable, human-diffable ordering.
+const sorted = [...rest.entries()].sort((a, b) => a[0].localeCompare(b[0]));
+const body = sorted
+ .map(([bone, q]) => `\t${bone}: [${q.map((n) => +n).join(', ')}],`)
+ .join('\n');
+
+const out = `// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.
+// Do not edit by hand — re-run the generator instead.
+//
+// Each entry is a canonical bone's local rest (bind-pose) quaternion [x,y,z,w]
+// on the Avaturn reference rig the clip library is authored against. Consumed by
+// src/animation-retarget.js to replay clip motion in a target rig's own rest
+// frame (Ta = Tr · Sr⁻¹ · Sa), so clips authored for cz's A-pose drive a
+// Mixamo T-pose (or any rig) without breaking limb poses. Values are verbatim
+// from cz.glb so retargeting onto cz is identity → byte-for-byte round-trip.
+
+export const CANONICAL_REST = Object.freeze({
+${body}
+});
+`;
+
+fs.writeFileSync(OUT, out);
+console.log(`wrote ${path.relative(ROOT, OUT)} — ${rest.size} canonical bones`);
+console.log('bones:', sorted.map(([b]) => b).join(', '));
diff --git a/scripts/rank-backlog.mjs b/scripts/rank-backlog.mjs
new file mode 100644
index 000000000..b7cc2cdf5
--- /dev/null
+++ b/scripts/rank-backlog.mjs
@@ -0,0 +1,52 @@
+#!/usr/bin/env node
+// Rank the open (partial/pending) backlog by a transparent composite priority score.
+import { readFileSync, writeFileSync, existsSync } from 'node:fs';
+
+const rows = JSON.parse(readFileSync('reports/task-completion-verified.json', 'utf8'))
+ .filter(x => x.verdict !== 'done' && existsSync(x.file));
+
+const LABEL = /priority[:*\s]*\**\s*(critical|high|medium|low|p0|p1|p2|p3)/i;
+const labelWeight = { critical: 4, p0: 4, high: 3, p1: 3, medium: 1, p2: 1, p3: -1, low: -1 };
+
+// product-value weights, grounded in repo focus + memory
+function valueWeight(file) {
+ if (/^tasks\/nvidia-nim|^prompts\/tripo-gap|^prompts\/animation-studio/.test(file)) return 3; // generation suite = top focus
+ if (/^prompts\/agent-fixes/.test(file)) return 3; // live production bug fixes
+ if (/^tasks\/onchain-deployment|^prompts\/siwx|^tasks\/pumpfun-launchpad/.test(file)) return 2; // payments/onchain infra
+ if (/^tasks\/agent-monetization|^tasks\/monetization-feature/.test(file)) return 1; // real monetization backend
+ if (/^prompts\/monetization(\/|-)/.test(file)) return -2; // duplicate prompt explosion -> dedupe, not 90 tasks
+ return 0; // walk/site-overhaul/wow-sprint/etc.
+}
+
+for (const r of rows) {
+ const t = readFileSync(r.file, 'utf8');
+ const m = t.match(LABEL);
+ r.label = m ? m[1].toLowerCase() : '';
+ let score = 0;
+ score += r.label ? labelWeight[r.label] : 0;
+ score += r.verdict === 'partial' ? 2 : 0;
+ score += r.confidence === 'high' ? 1 : 0;
+ score += valueWeight(r.file);
+ r.score = score;
+}
+rows.sort((a, b) => b.score - a.score || (a.verdict < b.verdict ? -1 : 1) || a.file.localeCompare(b.file));
+
+writeFileSync('reports/task-priority.csv',
+ 'rank,score,verdict,confidence,label,file,missing\n' +
+ rows.map((r, i) => [i + 1, r.score, r.verdict, r.confidence, r.label || '-', r.file,
+ JSON.stringify((r.missing || '').replace(/\s+/g, ' ').slice(0, 160))].join(',')).join('\n'));
+
+const dups = rows.filter(r => valueWeight(r.file) === -2);
+const quickWins = rows.filter(r => r.verdict === 'partial' && r.confidence === 'high' && valueWeight(r.file) >= 0);
+const topPending = rows.filter(r => r.verdict === 'pending' && r.score >= 3);
+
+const show = (r) => ` [${r.score}] ${r.verdict}/${r.confidence}${r.label ? ' ·' + r.label : ''} ${r.file}\n ↳ ${(r.missing || '').replace(/\s+/g, ' ').slice(0, 130)}`;
+
+console.log(`open backlog: ${rows.length}\n`);
+console.log(`=== TIER 1 — QUICK WINS (partial + high confidence, real value): ${quickWins.length} ===`);
+quickWins.slice(0, 12).forEach(r => console.log(show(r)));
+console.log(`\n=== TIER 2 — HIGH PRIORITY, NOT STARTED (score>=3, pending): ${topPending.length} ===`);
+topPending.slice(0, 12).forEach(r => console.log(show(r)));
+console.log(`\n=== DEPRIORITIZE / DEDUPE — duplicate monetization prompts: ${dups.length} ===`);
+console.log(` (collapse into one canonical set instead of treating as ${dups.length} tasks)`);
+console.log(`\nFull ranking: reports/task-priority.csv`);
diff --git a/src/animation-canonical-rest.js b/src/animation-canonical-rest.js
new file mode 100644
index 000000000..cc7103990
--- /dev/null
+++ b/src/animation-canonical-rest.js
@@ -0,0 +1,64 @@
+// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.
+// Do not edit by hand — re-run the generator instead.
+//
+// Each entry is a canonical bone's local rest (bind-pose) quaternion [x,y,z,w]
+// on the Avaturn reference rig the clip library is authored against. Consumed by
+// src/animation-retarget.js to replay clip motion in a target rig's own rest
+// frame (Ta = Tr · Sr⁻¹ · Sa), so clips authored for cz's A-pose drive a
+// Mixamo T-pose (or any rig) without breaking limb poses. Values are verbatim
+// from cz.glb so retargeting onto cz is identity → byte-for-byte round-trip.
+
+export const CANONICAL_REST = Object.freeze({
+ Head: [-0.11706881878098431, 9.438845082943482e-9, 3.72654613409334e-8, 0.993123804804428],
+ Hips: [0.0010741148761599644, 6.537898515070053e-8, 7.022659074474357e-11, 0.9999994231384476],
+ LeftArm: [-0.003089573263103852, 0.08018148459223169, -0.025041829737156785, 0.9964608827384491],
+ LeftFoot: [0.5523737034239063, 0.0002518875693487157, 0.0036538113016644914, 0.8335885543726441],
+ LeftForeArm: [-2.6826767953574183e-7, 1.2816740072681333e-7, 0.012369379808617674, 0.9999234962951223],
+ LeftHand: [-0.0012910117424963744, 0.002537815819541244, 0.010116448936771993, 0.9999447735952517],
+ LeftHandIndex1: [0.028803290204768833, 0.011362422123976328, 0.055965724298468224, 0.9979524555518633],
+ LeftHandIndex2: [-0.005195237841915152, 0.014315447122751807, 0.00021581682553071412, 0.9998840087229335],
+ LeftHandIndex3: [-0.0013151015878908295, -0.016941197343945148, -0.006458334440614796, 0.9998347644768737],
+ LeftHandMiddle1: [0.027532617383276645, -0.031607746403852485, 0.016931179482824785, 0.9989775976007271],
+ LeftHandMiddle2: [-0.001267981765488788, 0.0010468621884392817, -0.004466175725402764, 0.9999886747239598],
+ LeftHandMiddle3: [-0.0015803533040544947, 0.0018352886876119797, 0.0038040706030556736, 0.9999898315711762],
+ LeftHandPinky1: [0.009345046842530319, -0.07377447953394943, -0.04207784173776388, 0.9963430390695086],
+ LeftHandPinky2: [-0.0019002180814112143, 0.0002770864318134059, 0.0004968185265866393, 0.9999980327809131],
+ LeftHandPinky3: [-0.0014157518824255099, -0.005595319155644295, -0.004606740515194791, 0.9999727326242506],
+ LeftHandRing1: [0.018207541076892743, -0.03436008716699126, -0.036855349348364555, 0.9985637451229231],
+ LeftHandRing2: [-0.0006571286469542868, 0.015477225242721515, 0.01003471962236163, 0.9998296495318929],
+ LeftHandRing3: [0.001815607007583071, -0.003099595768579846, 0.0072046170631637615, 0.999967594260012],
+ LeftHandThumb1: [0.1900227602341495, -0.058826116539083484, 0.3478783626049766, 0.9161940209594684],
+ LeftHandThumb2: [0.01801363066187901, -0.020968588375318502, -0.22063576333056306, 0.9749644544258214],
+ LeftHandThumb3: [-0.014498565873099356, 0.03466160908487025, 0.011599642488048602, 0.9992266072970502],
+ LeftLeg: [-0.022987686472704008, -0.0006608912898930547, 0.00007960712093047862, 0.9997355266049326],
+ LeftShoulder: [0.5181706903502131, 0.5134387363832796, -0.48299308003518876, 0.4843526489955184],
+ LeftToeBase: [0.23652217735689587, 0.0006644108661216591, -0.002051152932444189, 0.9716236982227819],
+ LeftUpLeg: [-0.00004952055077835167, 0.0032567616062252223, 0.9999946186652781, -0.00039203576089550014],
+ Neck: [0.2225107795455935, -2.3352293238692193e-7, -1.9647139012020554e-8, 0.974930229804142],
+ RightArm: [-0.003089570938390283, -0.08018164882954634, 0.025041835809991725, 0.9964608693782484],
+ RightFoot: [0.5523737112340288, -0.00025188760500252676, -0.0036538107149212758, 0.8335885491999105],
+ RightForeArm: [-2.706717415294191e-7, 6.0675494372234465e-9, -0.012369382961452784, 0.9999234962561284],
+ RightHand: [-0.0012910114923260908, -0.002537815924782367, -0.010116450486313036, 0.9999447735796301],
+ RightHandIndex1: [0.028803284769926347, -0.01136242475457741, -0.05596571258489258, 0.9979524563349205],
+ RightHandIndex2: [-0.005195229421057241, -0.014315442233259087, -0.00021582506177354608, 0.9998840088349297],
+ RightHandIndex3: [-0.0013151045827228072, 0.016941319655899355, 0.006458327385746035, 0.9998347624459482],
+ RightHandMiddle1: [0.027532662650122483, 0.03160778647114273, -0.01693120529165708, 0.9989775946478099],
+ RightHandMiddle2: [-0.0012680273836480952, -0.0010469047250576836, 0.004466199390698661, 0.9999886745158897],
+ RightHandMiddle3: [-0.0015803562094451136, -0.001835288773706009, -0.003804068167924464, 0.9999898315756854],
+ RightHandPinky1: [0.009345030274151258, 0.07377446325595405, 0.04207784564870347, 0.9963430402658229],
+ RightHandPinky2: [-0.0019002008217559384, -0.0002769620503994165, -0.0004968229018870381, 0.9999980328459891],
+ RightHandPinky3: [-0.0014157497333212687, 0.0055951881780210025, 0.004606743315319843, 0.9999727333471813],
+ RightHandRing1: [0.01820754441109714, 0.03436008722907556, 0.03685535429214536, 0.9985637448787448],
+ RightHandRing2: [-0.0006571335802527884, -0.015477230302375519, -0.010034723368684675, 0.999829649412505],
+ RightHandRing3: [0.0018156069598940002, 0.003099598646436032, -0.007204626788931167, 0.9999675941811231],
+ RightHandThumb1: [0.19002276085311107, 0.05882618704962336, -0.3478783387552461, 0.9161940229953188],
+ RightHandThumb2: [0.018013663274561078, 0.020968550782212388, 0.22063584956274163, 0.9749644350943654],
+ RightHandThumb3: [-0.014498582331377526, -0.03466161961137741, -0.011599713293476643, 0.9992266058762234],
+ RightLeg: [-0.022987685898989207, 0.0006609402907891899, -0.00007960698692017099, 0.9997355265857409],
+ RightShoulder: [0.5181706006117709, -0.5134387953473804, 0.4829931766210871, 0.4843525890882128],
+ RightToeBase: [0.23652222014073046, -0.0006644109035597298, 0.0020511526077556528, 0.9716236878087238],
+ RightUpLeg: [0.000049438593286575395, 0.003256759408127677, 0.9999946186765544, 0.0003920356017771739],
+ Spine: [-0.018332562694809717, -1.4544833124647894e-7, 2.6976261645093277e-10, 0.9998319444511763],
+ Spine1: [-0.03815628571181615, 2.0010687323521798e-8, 5.34807122500512e-9, 0.9992717837809081],
+ Spine2: [-0.056998031890724846, 1.3546308636882866e-7, -8.861325315468363e-10, 0.9983742907149431],
+});
diff --git a/src/animation-retarget.js b/src/animation-retarget.js
index 4eab97816..7fb5c060e 100644
--- a/src/animation-retarget.js
+++ b/src/animation-retarget.js
@@ -16,6 +16,7 @@
import { AnimationClip, Quaternion, Vector3 } from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
+import { CANONICAL_REST } from './animation-canonical-rest.js';
// A clip retargets cleanly only when enough of its tracks find a home on the
// target rig. Below this the motion would read as a few twitching joints rather
@@ -23,21 +24,23 @@ import { canonicalizeBoneName } from './glb-canonicalize.js';
export const MIN_COVERAGE = 0.5;
// Rest (bind-pose) local rotation of each canonical bone *on the authoring rig*
-// the clips were baked against (canonical Avaturn). The library stores absolute
-// local rotations, so a clip only looks right when the target bone's rest
-// matches the authoring rest — otherwise we must replay the motion in the
-// target's own rest frame (see `bindCorrections`).
+// the clips were baked against (the Avaturn-rigged public/avatars/cz.glb). The
+// library stores absolute local rotations, so a clip only looks right when the
+// target bone's rest matches the authoring rest — otherwise we must replay the
+// motion in the target's own rest frame (see `bindCorrections`).
//
-// Only Hips is listed: it's the skeleton root, the one bone that carries the
-// up-axis convention. Mixamo/FBX exports bake a +90°X on the armature node and a
-// −90°X on Hips; copying the clip's (≈identity) Hips rotation verbatim wipes that
-// −90°X out and tips the whole body onto its back. The authoring rig's Hips rest
-// is identity, so a correction of `targetHipsRest · I` re-applies whatever rest
-// the target rig needs. Limb bones aren't listed because their authoring rest is
-// avatar-specific and copying verbatim has always been the (acceptable) status
-// quo for non-Avaturn rigs; adding them would require shipping the full authoring
-// rest pose and would change limb output for every rig.
-const SOURCE_REST = new Map([['Hips', new Quaternion(0, 0, 0, 1)]]);
+// The full skeleton is covered (generated from cz.glb into
+// animation-canonical-rest.js), not just Hips. Hips carries the up-axis
+// convention — Mixamo/FBX bake a +90°X on the armature and a −90°X on Hips, and
+// copying the clip's Hips rotation verbatim wipes that out and tips the body onto
+// its back. The limb bones carry the pose convention — cz rests in an A-pose,
+// Mixamo in a T-pose — so without per-limb correction an upright avatar still
+// plays clips with the arms/legs in the wrong frame. Because the values are cz's
+// own rest, retargeting back onto cz yields an identity correction per bone
+// (skipped below), so a matching rig round-trips byte-for-byte.
+const SOURCE_REST = new Map(
+ Object.entries(CANONICAL_REST).map(([bone, q]) => [bone, new Quaternion(q[0], q[1], q[2], q[3])]),
+);
// A quaternion within this of identity (|w| ≈ 1) is treated as no rotation, so a
// rig that already matches the authoring convention round-trips bit-for-bit.
diff --git a/src/ar/anchor-lifecycle.js b/src/ar/anchor-lifecycle.js
new file mode 100644
index 000000000..5ab11ce03
--- /dev/null
+++ b/src/ar/anchor-lifecycle.js
@@ -0,0 +1,111 @@
+// Pure lifecycle policy for the WebXR floor-anchor session.
+//
+// AR's happy path is easy; production readiness lives entirely in the unhappy
+// ones — the app gets backgrounded, ARCore loses tracking in low light, a device
+// advertises anchors it can't honour, the user taps before the first GPS fix.
+// Each of those must resolve to a defined, recoverable outcome. The rules that
+// decide those outcomes live here, free of DOM / Three.js / wall-clock, so every
+// branch is proven by `tests/ar-anchor-lifecycle.test.js` rather than a phone.
+//
+// `src/ar/webxr.js` and `src/irl.js` consume these helpers; they own only the
+// side effects (callbacks, render loop, pin persistence), never the policy.
+
+// ── Tracking loss ───────────────────────────────────────────────────────────
+// A single frame with no viewer pose is normal jitter; a sustained run of them
+// means the device has lost its fix on the room. Surface "lost" only after a
+// short run (not a one-frame blip) and recover the instant a pose returns —
+// transition-only, exactly like the hit-test reticle's searching/found state.
+
+/** Consecutive pose-less frames before we declare tracking lost (~0.5s @ 60fps). */
+export const TRACKING_LOSS_FRAMES = 30;
+
+/**
+ * Advance the tracking-health state machine by one frame.
+ * @param {{misses:number, lost:boolean}|null} prev Prior state (null = fresh).
+ * @param {boolean} hasPose Whether this frame yielded a viewer pose.
+ * @param {number} [threshold=TRACKING_LOSS_FRAMES] Misses tolerated before "lost".
+ * @returns {{state:{misses:number,lost:boolean}, changed:boolean, lost:boolean}}
+ * `changed` is true only on the lost↔recovered transition, so callers can fire
+ * a host callback once per state change instead of every frame.
+ */
+export function nextTrackingState(prev, hasPose, threshold = TRACKING_LOSS_FRAMES) {
+ const cur = prev || { misses: 0, lost: false };
+ if (hasPose) {
+ // A pose this frame clears the miss streak; report recovery if we were lost.
+ return { state: { misses: 0, lost: false }, changed: cur.lost === true, lost: false };
+ }
+ const misses = cur.misses + 1;
+ const lost = misses >= threshold;
+ return { state: { misses, lost }, changed: lost && !cur.lost, lost };
+}
+
+// ── Visibility / interruption ────────────────────────────────────────────────
+// XRSession.visibilityState ('visible' | 'visible-blurred' | 'hidden'): only the
+// first means the session is in the foreground and worth animating.
+
+/** visibilityState values where the session is interrupted (backgrounded/blurred). */
+export const XR_PAUSED_STATES = new Set(['hidden', 'visible-blurred']);
+
+/**
+ * @param {string} visibilityState XRSession.visibilityState.
+ * @returns {boolean} true when the session is foreground-visible.
+ */
+export function isXrVisible(visibilityState) {
+ return !XR_PAUSED_STATES.has(visibilityState);
+}
+
+// ── Degraded-anchor honesty ──────────────────────────────────────────────────
+// When createAnchor() yields no XRAnchor the agent is frozen at the tap pose —
+// it still works and still saves a pin, but it may drift. Say so rather than
+// pretending it's rock-solid.
+
+/**
+ * @param {boolean} degraded true when no real XRAnchor backs the placement.
+ * @returns {string} Honest, user-facing placement copy.
+ */
+export function placementHint(degraded) {
+ return degraded
+ ? 'Placed — this device can’t lock it perfectly, so it may drift a little'
+ : 'Anchored — walk around, it stays put';
+}
+
+// ── Pre-GPS replay gate ──────────────────────────────────────────────────────
+// The one durable side effect of a placement is the GPS pin, and it must save
+// EXACTLY once. A tap with a live fix saves immediately; a tap during GPS
+// warm-up holds the pose and saves on the first fix; leaving before that fix
+// drops it (the user walked away — don't surprise them with a late pin). The
+// gate owns the held pose and the consumed-guard so no caller can double-save,
+// save zero times, or save a pose that was abandoned.
+
+/**
+ * @param {(pose:any)=>void} persist Side effect that durably saves one pose.
+ * @returns {{
+ * place:(pose:any, ready:boolean)=>'persisted'|'held',
+ * onFix:(ready:boolean)=>boolean,
+ * drop:()=>void,
+ * hasPending:()=>boolean,
+ * }}
+ */
+export function createPersistGate(persist) {
+ let pending = null;
+ return {
+ // A tap landed. With a live fix, persist now; otherwise hold for the fix.
+ place(pose, ready) {
+ if (ready) { persist(pose); return 'persisted'; }
+ pending = pose;
+ return 'held';
+ },
+ // The first GPS fix landed. Persist a held pose once, then forget it.
+ // Returns true iff this call performed the (single) persist.
+ onFix(ready) {
+ if (!ready || pending === null) return false;
+ const pose = pending;
+ pending = null;
+ persist(pose);
+ return true;
+ },
+ // Session ended before a fix — drop the held pose. Idempotent.
+ drop() { pending = null; },
+ hasPending() { return pending !== null; },
+ };
+}
diff --git a/src/ar/webxr.js b/src/ar/webxr.js
index 25b169fef..86b3207ec 100644
--- a/src/ar/webxr.js
+++ b/src/ar/webxr.js
@@ -10,6 +10,8 @@
import { Matrix4, Mesh, MeshBasicMaterial, Quaternion, RingGeometry, Vector3 } from 'three';
+import { isXrVisible, nextTrackingState, TRACKING_LOSS_FRAMES } from './anchor-lifecycle.js';
+
const LOWER_BODY_FRAGMENTS = [
'upleg', 'leg', 'thigh', 'knee', 'shin', 'calf',
'foot', 'toe', 'ankle',
@@ -38,23 +40,36 @@ export class WebXRSession {
* @param {Function} [opts.onEnd] Called after the XR session ends + restores.
* @param {boolean} [opts.halfBody] Collapse lower-body bones (demo mode).
* @param {Function} [opts.onAnchored] Called once on first tap with the anchored
- * local-space pose `{ position: Vector3, quaternion: Quaternion }` for persistence.
+ * local-space pose `{ position: Vector3, quaternion: Quaternion }` and a
+ * `{ degraded }` flag (degraded = no real XRAnchor; placement may drift).
* @param {Function} [opts.onHit] Called with `true`/`false` as the hit-test
* reticle gains/loses a surface — drives the "point at the floor" searching state.
+ * @param {Function} [opts.onTracking] Called with `true`/`false` as the device
+ * regains/loses its fix on the room — drives the "move to a brighter spot" hint.
+ * @param {Function} [opts.onVisibility] Called with `true`/`false` as the session
+ * is foregrounded/backgrounded (lock, incoming call, app switch).
* @param {Element} [opts.domOverlayRoot] Element to surface as the WebXR
* `dom-overlay` root (in-session hint + exit affordance). Optional.
*/
- constructor(viewer, { onEnd, halfBody = false, onAnchored, onHit, domOverlayRoot } = {}) {
+ constructor(viewer, { onEnd, halfBody = false, onAnchored, onHit, onTracking, onVisibility, domOverlayRoot } = {}) {
this._viewer = viewer;
this._halfBody = halfBody;
this._onEnd = onEnd;
this._onAnchored = onAnchored;
this._onHit = onHit;
+ this._onTracking = onTracking;
+ this._onVisibility = onVisibility;
this._domOverlayRoot = domOverlayRoot ?? null;
this._session = null;
this._hitTestSource = null;
this._localSpace = null;
this._anchored = false;
+ /** Tracking-health state machine (transition-only "lost"/"recovered"). */
+ this._trackingState = { misses: 0, lost: false };
+ /** True while the session is backgrounded/blurred — skips non-essential work. */
+ this._paused = false;
+ /** Idempotency latch so an OS-initiated end and our own end() can't double-clean. */
+ this._ended = false;
/** @type {XRAnchor|null} Real world anchor created on tap (feature-detected). */
this._anchor = null;
/** @type {XRHitTestResult|null} Most recent hit, used to create the anchor. */
@@ -72,6 +87,7 @@ export class WebXRSession {
this._halfBodyBones = [];
this._handleEnd = this._handleEnd.bind(this);
this._handleSelect = this._handleSelect.bind(this);
+ this._handleVisibilityChange = this._handleVisibilityChange.bind(this);
}
static async isSupported() {
@@ -103,9 +119,18 @@ export class WebXRSession {
const session = await navigator.xr.requestSession('immersive-ar', sessionInit);
this._session = session;
+ // Fresh session: clear the lifecycle latches a prior run may have left set.
+ this._ended = false;
+ this._paused = false;
+ this._trackingState = { misses: 0, lost: false };
+ // An OS-initiated end (user locks the phone, takes a call, swipes the app
+ // away) fires 'end' just like our exit button — both land in _handleEnd, so
+ // restoration is identical and idempotent no matter who ended the session.
session.addEventListener('end', this._handleEnd);
// 'select' fires on controller trigger or screen tap
session.addEventListener('select', this._handleSelect);
+ // Backgrounding/blurring pauses non-essential work and surfaces a resume hint.
+ session.addEventListener('visibilitychange', this._handleVisibilityChange);
await renderer.xr.setSession(session);
@@ -148,6 +173,26 @@ export class WebXRSession {
const dt = viewer.prevTime ? (time - viewer.prevTime) / 1000 : 0.016;
viewer.prevTime = time;
+ // Paused (app backgrounded, incoming call, screen locked): hold the agent
+ // still and skip animation, hit-testing, and tracking checks so nothing
+ // drifts or burns cycles. Submit a frame so the compositor stays happy, then
+ // wait for visibilitychange → resume. No work, no console noise.
+ if (this._paused) {
+ renderer.render(viewer.scene, viewer.activeCamera);
+ return;
+ }
+
+ // Tracking health: a frame with no viewer pose means the device has lost its
+ // fix on the room (low light, blank wall, fast motion). Run it through the
+ // transition-only state machine so the host hears "lost"/"recovered" once,
+ // not every frame, and hide the reticle the moment we're lost.
+ if (frame && this._localSpace) {
+ const hasPose = !!frame.getViewerPose(this._localSpace);
+ const t = nextTrackingState(this._trackingState, hasPose, TRACKING_LOSS_FRAMES);
+ this._trackingState = t.state;
+ if (t.changed) this._setTracking(!t.lost);
+ }
+
if (viewer.mixer) viewer.mixer.update(dt);
viewer.animationManager.update(dt);
@@ -217,7 +262,10 @@ export class WebXRSession {
// the feature — fall back to the frozen tap pose rather than failing.
this._anchor = null;
}
- this._onAnchored?.(anchorPose);
+ // Disclose a degraded placement: with no real XRAnchor the agent is frozen
+ // at the tap pose and may drift. We still persist the pin; we just stop
+ // pretending it's rock-solid so the host can say so honestly.
+ this._onAnchored?.(anchorPose, { degraded: this._anchor === null });
}
// Build the floor reticle: a flat ring whose geometry is pre-rotated into the
@@ -250,6 +298,23 @@ export class WebXRSession {
this._onHit?.(has);
}
+ // Tracking lost/recovered. On loss, hide the reticle so the user never taps a
+ // stale one; the host surfaces a recoverable "move to a brighter spot" hint.
+ _setTracking(ok) {
+ if (!ok && this._reticle) this._reticle.visible = false;
+ this._onTracking?.(ok);
+ }
+
+ // Foreground/background transition. Pause non-essential work while hidden and
+ // hand the host a hint; resume cleanly when foregrounded. An OS that ends the
+ // session instead of merely hiding it lands in _handleEnd, not here.
+ _handleVisibilityChange() {
+ const visible = isXrVisible(this._session?.visibilityState);
+ this._paused = !visible;
+ if (!visible && this._reticle) this._reticle.visible = false;
+ this._onVisibility?.(visible);
+ }
+
// Decompose the captured tap-moment hit matrix into a local-space pose the host
// converts to a GPS pin (metres from the session origin → lat/lng + floor height).
_readAnchorPose() {
@@ -275,9 +340,18 @@ export class WebXRSession {
}
_handleEnd() {
+ // Idempotent: the 'end' event and a direct end() can both reach here, and an
+ // OS-initiated end must restore exactly once — same path as the exit button.
+ if (this._ended) return;
+ this._ended = true;
+
const viewer = this._viewer;
const renderer = viewer.renderer;
+ // Stop listening before tearing down so a late visibilitychange during
+ // teardown can't re-pause a session that's already gone.
+ this._session?.removeEventListener('visibilitychange', this._handleVisibilityChange);
+
renderer.setAnimationLoop(null);
renderer.xr.enabled = false;
@@ -293,6 +367,8 @@ export class WebXRSession {
this._anchor = null;
this._latestHit = null;
this._hasHit = false;
+ this._paused = false;
+ this._trackingState = { misses: 0, lost: false };
// Restore background
viewer.scene.background = this._savedBg;
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index ef2f93d5f..ca6601633 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -114,7 +114,11 @@ const STYLE = `<style>
.sn-live { background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); }
.sn-live-head { display: flex; align-items: center; justify-content: space-between; padding: 14px 16px; border-bottom: 1px solid var(--nxt-line); }
.sn-live-title { font-size: 14px; font-weight: 600; display: flex; gap: 8px; align-items: center; }
-.sn-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--nxt-success); animation: sn-pulse 2s ease infinite; }
+.sn-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--nxt-success); animation: sn-pulse 2s ease infinite; flex-shrink: 0; }
+.sn-live-dot.connecting, .sn-live-dot.reconnecting { background: var(--nxt-warn, #f59e0b); }
+.sn-live-dot.offline { background: var(--nxt-danger, #f87171); animation: none; }
+.sn-conn-status { font-size: 11px; font-weight: 500; color: var(--nxt-ink-faint); letter-spacing: .02em; }
+.sn-live-links { display: flex; gap: 8px; align-items: center; }
@keyframes sn-pulse { 0%,100% { opacity: 1 } 50% { opacity: .35 } }
.sn-pos-list { padding: 0; }
.sn-pos-row { display: grid; grid-template-columns: 1fr auto auto auto; gap: 10px; align-items: center; padding: 11px 16px; border-bottom: 1px solid var(--nxt-line); }
@@ -204,9 +208,11 @@ const STYLE = `<style>
// ── Main render ───────────────────────────────────────────────────────────────
let _strategies = [];
-let _positions = [];
let _agents = [];
let _sseSource = null;
+let _sseTimer = null;
+let _sseRetry = 0;
+let _positionsMap = new Map();
async function refresh(root) {
const [stratData, agentData] = await Promise.all([
@@ -520,13 +526,18 @@ function intelFields(s) {
// ── Live positions ────────────────────────────────────────────────────────────
function livePositionsSection() {
+ const ghostBtn = 'font-size:12px;padding:5px 12px;border-radius:var(--nxt-radius-sm);border:1px solid var(--nxt-stroke);text-decoration:none;color:var(--nxt-ink);';
return `<div class="sn-live">
<div class="sn-live-head">
<div class="sn-live-title">
- <span class="sn-live-dot"></span>
- Live Positions
+ <span class="sn-live-dot connecting"></span>
+ Your Live Positions
+ <span class="sn-conn-status" id="sn-conn-status" role="status" aria-live="polite">Connecting…</span>
+ </div>
+ <div class="sn-live-links">
+ <a class="sn-btn ghost" style="${ghostBtn}" href="/leaderboard" target="_blank" rel="noopener">Leaderboard ↗</a>
+ <a class="sn-btn ghost" style="${ghostBtn}" href="/play/arena" target="_blank" rel="noopener">Sniper Arena ↗</a>
</div>
- <a class="sn-btn ghost" style="font-size:12px;padding:5px 12px;border-radius:var(--nxt-radius-sm);border:1px solid var(--nxt-stroke);text-decoration:none;color:var(--nxt-ink);" href="/play/arena" target="_blank" rel="noopener">Sniper Arena ↗</a>
</div>
<div id="sn-positions" class="sn-pos-list">
<p class="sn-empty">Connecting…</p>
@@ -546,16 +557,19 @@ function renderPositions(positions) {
}
function posRow(p) {
- const pnlSol = p.unrealized_pnl_sol != null ? p.unrealized_pnl_sol : null;
- const pnlStr = pnlSol != null ? `<span class="${clr(pnlSol)}">${fmtSol(pnlSol)}</span>` : '—';
- const link = p.entry_buy_sig && p.entry_buy_sig !== 'SIMULATED'
- ? `<a class="sn-pos-link" href="${solscanTx(p.entry_buy_sig)}" target="_blank" rel="noopener">Solscan ↗</a>`
+ const pnlSol = p.unrealized_pnl_sol;
+ const pnlPct = p.unrealized_pct;
+ const pnlStr = pnlSol != null
+ ? `<span class="${clr(pnlSol)}">${pnlSol >= 0 ? '+' : ''}${fmtSol(pnlSol)}${pnlPct != null ? ` · ${pnlPct >= 0 ? '+' : ''}${pnlPct.toFixed(1)}%` : ''}</span>`
+ : '—';
+ const link = p.buy_url
+ ? `<a class="sn-pos-link" href="${esc(p.buy_url)}" target="_blank" rel="noopener">Solscan ↗</a>`
: p.mint ? `<a class="sn-pos-link" href="${pumpUrl(p.mint)}" target="_blank" rel="noopener">pump.fun ↗</a>` : '';
const mintAttr = p.mint ? ` data-oracle-mint="${esc(p.mint)}"` : '';
return `<div class="sn-pos-row"${mintAttr}>
<div class="sn-pos-info">
<div class="sn-pos-sym">${esc(p.symbol || p.mint?.slice(0, 8) || '—')}</div>
- <div class="sn-pos-sub">${esc(p.agent_name || '')} · opened ${relTime(p.opened_at)}</div>
+ <div class="sn-pos-sub">${esc(p.agent_name || '')}${p.opened_at ? ` · opened ${relTime(p.opened_at)}` : ''}</div>
</div>
<div class="sn-pos-pnl">${pnlStr}</div>
<span class="sn-pos-oracle"></span>
diff --git a/src/irl.js b/src/irl.js
index d6879c6fc..8b9ace1fc 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -53,6 +53,8 @@ import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
import { detectTier, BUDGETS, TIER_ORDER, shiftTier } from './irl/perf-budget.js';
import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';
import { roomOriginWorld, agentWorldPosition } from './irl/room-anchor.js';
+import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch } from './irl/sensor-fusion.js';
+import { pinBandAction } from './irl/proximity-band.js';
import { loadInto } from './shared/async-state.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
@@ -842,6 +844,8 @@ let devOrientBaseCamPitch = 0;
let prefersAbsOrientation = false; // true once a north-referenced bearing is seen (source tagging)
let hasAbsoluteEventStream = false; // true if the dedicated deviceorientationabsolute event fires (Android)
let lastCompassHeading = null; // iOS true compass bearing (deg, 0=N clockwise); null = none/uncalibrated
+let lastCompassAt = 0; // performance.now() of the last finite compass sample; 0 = never seen
+let lockYawMode = 'relative'; // last frame's yaw path ('absolute'|'relative') for a seamless handoff
// iOS Safari's magnetic-north bearing. A negative webkitCompassAccuracy means the
// magnetometer isn't calibrated yet — treat that as no absolute reference rather
@@ -862,32 +866,65 @@ function compassToYaw(headingDeg) {
}
function onDeviceOrientation(e) {
- const a = e.alpha ?? 0;
- const b = e.beta ?? 90;
- lastDevAlpha = a;
- lastDevBeta = b;
+ // Hold the last valid reading when a frame delivers null/undefined/NaN. The old
+ // `?? 0` / `?? 90` only caught null/undefined and let NaN through into the delta
+ // math (→ a NaN quaternion → the avatar vanishes); and substituting 0/90 yanks
+ // the yaw to page-north and slams the pitch to the horizon. A held value simply
+ // pauses the view for one bad frame until the sensor recovers.
+ if (isFiniteReading(e.alpha, e.beta)) {
+ lastDevAlpha = e.alpha;
+ lastDevBeta = e.beta;
+ }
+ const a = lastDevAlpha;
+ const b = lastDevBeta;
const compass = readCompassHeading(e);
- if (compass !== null) { lastCompassHeading = compass; prefersAbsOrientation = true; }
- else if (hasAbsoluteEventStream) { prefersAbsOrientation = true; }
+ if (compass !== null) {
+ lastCompassHeading = compass;
+ lastCompassAt = performance.now();
+ prefersAbsOrientation = true;
+ } else if (hasAbsoluteEventStream) {
+ prefersAbsOrientation = true;
+ }
if (!avatarLocked || !arActive || devOrientBaseAlpha === null) return;
- if (lastCompassHeading !== null && gpsModeActive) {
- // Absolute frame (iOS compass + a GPS world-anchor): yaw tracks the real
- // bearing, so panning the phone leaves the avatar planted on its real-world
- // direction for everyone. Only meaningful once a GPS pin gives the scene an
- // absolute origin — a local-only lock (below) must stay relative or the
- // avatar would jump off-frame to its compass bearing the instant it locks.
- cameraYaw = compassToYaw(lastCompassHeading);
- } else {
- // Page-relative fallback (no compass) AND local no-GPS lock: integrate alpha
- // deltas from the lock baseline so the view rotates with the phone while the
- // avatar holds the exact spot it was pinned at.
- let dAlpha = a - devOrientBaseAlpha;
- if (dAlpha > 180) dAlpha -= 360;
- if (dAlpha < -180) dAlpha += 360;
- cameraYaw = devOrientBaseCamYaw + dAlpha * (Math.PI / 180);
+
+ // A stale compass (uncalibrated, or walked into a magnetic dead-zone) keeps its
+ // last heading forever — detect that and fall back to the relative gyro path
+ // instead of steering by a dead bearing.
+ const compassFresh = isCompassFresh(lastCompassAt, performance.now());
+ const useAbsolute = shouldUseAbsoluteYaw({ gpsModeActive, compassHeading: lastCompassHeading, compassFresh });
+
+ // On an absolute→relative handoff (the compass just went stale), re-baseline the
+ // relative integrator to the current pose so it continues from where the absolute
+ // path left off rather than snapping back to the lock-time baseline.
+ if (lockYawMode === 'absolute' && !useAbsolute) {
+ devOrientBaseAlpha = a;
+ devOrientBaseCamYaw = cameraYaw;
}
- cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX,
- devOrientBaseCamPitch - (b - devOrientBaseBeta) * (Math.PI / 180)));
+
+ // Absolute path: yaw eases toward the true bearing along the shortest arc (so a
+ // 359°→1° turn is a ~2° move, never a spin) — only meaningful once a GPS pin
+ // gives the scene an absolute origin. Relative path: integrate alpha deltas from
+ // the lock baseline so the view rotates with the phone while the avatar holds the
+ // exact spot it was pinned at.
+ const nextYaw = resolveLockYaw({
+ useAbsolute,
+ prevYaw: cameraYaw,
+ alpha: a,
+ baseAlpha: devOrientBaseAlpha,
+ baseYaw: devOrientBaseCamYaw,
+ compassHeading: lastCompassHeading,
+ });
+ lockYawMode = useAbsolute ? 'absolute' : 'relative';
+
+ const nextPitch = clampPitch(
+ devOrientBaseCamPitch - (b - devOrientBaseBeta) * (Math.PI / 180),
+ PITCH_MIN, PITCH_MAX);
+
+ // Final backstop: never write a non-finite value to the camera. The helpers
+ // guarantee this given finite inputs, but a corrupted baseline must never spin
+ // or freeze the view — hold the prior frame instead.
+ if (Number.isFinite(nextYaw)) cameraYaw = nextYaw;
+ if (Number.isFinite(nextPitch)) cameraPitch = nextPitch;
}
// Two orientation streams: Android's dedicated absolute event (north-referenced
@@ -1009,6 +1046,7 @@ async function setLocked(next) {
devOrientBaseAlpha = null;
gyroLockCamPos = null;
_pendingGpsLock = false;
+ lockYawMode = 'relative';
arFrozenCamPos = camera.position.clone();
arFrozenCamLook = camLookCurrent.clone();
document.body.classList.remove('is-locked');
@@ -1225,9 +1263,24 @@ function blendOrigin(prev, fix) {
}
// Tight "stumble upon" gate: an agent only renders once you're within ~40 m of
-// it (matches the server's hard radius cap). You discover one by physically being
-// near it with your camera up — never from a list, map, or neighbourhood feed.
+// it. You discover one by physically being near it with your camera up — never from
+// a list, map, or neighbourhood feed. This is the band's ENTER threshold; a rendered
+// pin is then held out to EXIT_RADIUS_M (proximity-band.js) so edge GPS jitter can't
+// pop it in and out.
const NEARBY_RADIUS = 40; // metres
+// Ask the server for the wider read (its hard 60 m cap), NOT the tight discovery
+// radius. A wider set keeps an edge agent stably returned so it can't blink in/out as
+// GPS jitters; loadNearbyPins() then trims that coarse set to the asymmetric band
+// locally (pinBandAction). Never widen past the cap — the server still gates the
+// roster to 60 m, so this discovers nothing the user couldn't already stumble upon.
+const NEARBY_READ_RADIUS = 60; // metres — matches api/irl/pins.js Math.min(60, …)
+
+// Honour the OS "reduce motion" setting for the spawn/despawn transitions below —
+// scale in/out for everyone else, instant for users who asked for less animation.
+function prefersReducedMotion() {
+ return typeof matchMedia === 'function'
+ && matchMedia('(prefers-reduced-motion: reduce)').matches;
+}
function onGPSPosition(pos) {
const wasReady = gpsState.ready;
@@ -1722,6 +1775,33 @@ let nearbyPins = []; // [{ id, lat, lng, avatar_url, avatar_name, caption, x402_
// a failed refresh shows a visible indicator on the badge instead of going silent.
let _nearbyError = false;
+// ── "Newly stable in-range" signal (task 04 → task 03) ──────────────────────
+// The hysteresis band (proximity-band.js) makes membership steady: a pin only
+// joins `nearbyPins` once it has genuinely crossed the tight ENTER gate, and it
+// can't leave until it's been out-of-band for DROP_POLLS *consecutive* polls. So
+// the single moment the band promotes a pin from not-rendered → the stable set
+// (the band's 'spawn' action below) is exactly one clean, debounced arrival — it
+// never re-fires while a steady agent jitters at the edge, because a rendered pin
+// is never re-spawned. Task 03's proximity-arrival cue consumes this: it gets one
+// callback per agent the viewer has genuinely walked up to, never a flicker storm.
+//
+// A subscriber registry (not a single hook) so other surfaces can listen too
+// without fighting over one slot; emission is fire-and-forget and never lets a
+// listener throw into the membership reconcile. Subscribing returns an unsubscribe.
+const _pinStableListeners = new Set();
+function onPinStable(listener) {
+ if (typeof listener !== 'function') return () => {};
+ _pinStableListeners.add(listener);
+ return () => { _pinStableListeners.delete(listener); };
+}
+function emitPinStable(pin) {
+ if (!_pinStableListeners.size) return;
+ for (const listener of _pinStableListeners) {
+ try { listener(pin); }
+ catch (err) { log.error('[irl] pin-stable listener failed:', err); }
+ }
+}
+
// Briefly tint a pin's floating label so a deep-linked target (?highlight= or
// ?agent=) is easy to spot among the nearby agents. No-op for a missing pin/label.
function flashPinLabel(pin) {
@@ -1761,6 +1841,28 @@ function removeNearbyPin(id) {
updateNearbyBadge();
}
+// ── Animated spawn / despawn (membership transitions) ───────────────────────
+// A pin that genuinely arrives or leaves should ease in/out, never pop — even a
+// legitimate exit looks like a glitch as a hard cut. Spawn grows the group from 0→1
+// (cubic ease-out, set in spawnNearbyPin + advanced in tick); despawn shrinks it
+// 1→0 here, then disposes. Both honour prefers-reduced-motion (instant). These are
+// purely visual: the pin is already gone from `nearbyPins` (membership) before it
+// fades, so the band logic, labels and LOD never touch a leaving avatar.
+const DESPAWN_DURATION = 0.32; // seconds for the despawn shrink
+const _despawningPins = []; // pins fading out before disposePin
+
+// Begin an animated despawn for a pin the band has evicted. The caller has already
+// removed it from `nearbyPins`; we cancel any in-flight GLB (it's leaving), hide its
+// 2D label immediately (a frozen HTML label can't shrink with the 3D group), then
+// either dispose at once (reduced motion / no group) or queue the fade.
+function despawnNearbyPin(p) {
+ if (p.labelEl) p.labelEl.style.display = 'none';
+ if (prefersReducedMotion() || !p.group) { disposePin(p); return; }
+ cancelPinGLB(p);
+ p._despawnT = 0;
+ _despawningPins.push(p);
+}
+
// ── Realtime presence + reactions (D2/D3) ───────────────────────────────────
// IrlNet joins the irl_world room for the viewer's geocell — but ONLY for live
// PRESENCE (who else is viewing nearby) and ambient REACTIONS. The room is NOT a
@@ -2012,43 +2114,79 @@ function refreshKnownPin(known, pin) {
applyPinUpdate(known, pin);
}
+// Ground-plane distance (m) from the viewer to a pin, computed locally from the
+// SMOOTHED origin via pinWorldPos — stable even when the server's coarse set jitters
+// at the edge, and valid before a pin has a group (a fresh server row). This is what
+// the membership band measures, NOT the live camera distance (which tracks AR head
+// movement); membership is "how far is this agent from where I'm standing".
+function bandDistance(pin) {
+ const wp = pinWorldPos(pin);
+ return Math.hypot(wp.x, wp.z);
+}
+
async function loadNearbyPins() {
if (!gpsState.ready) return;
- // The proximity poll is the SOLE pin-discovery transport: the server returns only
- // the agents within a tight radius of our live position (no roster, no map), so
- // this both finds new arrivals and drops ones we've walked away from.
+ // The proximity poll is the SOLE pin-discovery transport: the server returns the
+ // agents within a tight radius of our live position (no roster, no map). We ask for
+ // the wider read (NEARBY_READ_RADIUS = the 60 m cap) so an agent on the discovery
+ // edge stays stably returned, then apply the asymmetric ENTER/EXIT band + despawn
+ // debounce CLIENT-side (pinBandAction) so consumer GPS jitter can't pop it in and out.
try {
const r = await fetch(
- `/api/irl/pins?lat=${gpsState.lat}&lng=${gpsState.lng}&radius=${NEARBY_RADIUS}`,
+ `/api/irl/pins?lat=${gpsState.lat}&lng=${gpsState.lng}&radius=${NEARBY_READ_RADIUS}`,
);
if (!r.ok) { _nearbyError = true; updateNearbyBadge(); return; }
const { pins } = await r.json();
_nearbyError = false;
- const incoming = pins.filter(p => !gpsPin?.id || p.id !== gpsPin.id);
- const inIds = new Set(incoming.map(p => p.id));
-
- // Remove disappeared pins — dispose their GPU resources, don't just
- // detach. At a busy location agents come and go constantly; without
- // freeing geometries/materials/textures a long session leaks steadily.
- nearbyPins = nearbyPins.filter(p => {
- if (inIds.has(p.id)) return true;
- disposePin(p);
- return false;
- });
+ const incoming = pins.filter(p => !gpsPin?.id || p.id !== gpsPin.id);
+ const incomingById = new Map(incoming.map(p => [p.id, p]));
+
+ // 1) Reconcile already-rendered pins through the hysteresis band. Refresh each
+ // from its fresh server row FIRST (a calibrate/edit may have moved it) so the
+ // band distance is measured against the current position, then keep / debounce
+ // / drop. A pin is out-of-band when it's beyond EXIT_RADIUS_M *or* the server
+ // no longer lists it (deleted, hidden, or walked far past the cap); either way
+ // it must stay out-of-band for DROP_POLLS consecutive polls before disposal, so
+ // a single bad fix or inconsistent reply never evicts a steady agent. Despawn
+ // is animated (despawnNearbyPin); disposal frees every GPU resource it held.
+ const survivors = [];
+ for (const p of nearbyPins) {
+ const row = incomingById.get(p.id);
+ if (row) refreshKnownPin(p, row);
+ const action = pinBandAction({
+ distance: bandDistance(p),
+ rendered: true,
+ listed: !!row,
+ oobPolls: p._oobPolls || 0,
+ }, { enter: NEARBY_RADIUS });
+ if (action === 'keep') { p._oobPolls = 0; survivors.push(p); }
+ else if (action === 'wait') { p._oobPolls = (p._oobPolls || 0) + 1; survivors.push(p); }
+ else { despawnNearbyPin(p); } // 'drop'
+ }
+ nearbyPins = survivors;
- // Spawn new arrivals; refresh any already-known pin. The feed carries the
- // pin's current position (a calibrate/edit may have moved it), caption, name
- // and avatar_version, so refreshKnownPin moves/relabels it and swaps the GLB
- // on a C6 re-skin — the poll is the single propagation path for every change.
+ // 2) Spawn genuinely new arrivals — only those that have crossed the tight ENTER
+ // gate. A server row sitting in the 40–55 m band we've never rendered stays
+ // 'ignore'd: you DISCOVER an agent by getting within the enter radius, never by
+ // drifting near its outer edge. Each new pin starts the spawn-in scale (once).
for (const pin of incoming) {
- const known = nearbyPins.find(n => n.id === pin.id);
- if (known) refreshKnownPin(known, pin);
- else {
- const entry = { ...pin, group: null, labelEl: null, glbLoaded: false };
- nearbyPins.push(entry);
- spawnNearbyPin(entry);
- }
+ if (nearbyPins.some(n => n.id === pin.id)) continue;
+ const entry = { ...pin, group: null, labelEl: null, glbLoaded: false, _oobPolls: 0 };
+ const action = pinBandAction({
+ distance: bandDistance(entry),
+ rendered: false,
+ listed: true,
+ oobPolls: 0,
+ }, { enter: NEARBY_RADIUS });
+ if (action !== 'spawn') continue;
+ nearbyPins.push(entry);
+ spawnNearbyPin(entry);
+ // Clean, debounced "newly stable in-range" signal: the band only reaches
+ // 'spawn' for a pin that has genuinely crossed the ENTER gate and isn't
+ // already rendered, so this fires exactly once per real arrival — never on
+ // the GPS-edge jitter the hysteresis absorbs. Task 03's arrival cue listens.
+ emitPinStable(entry);
}
updateNearbyBadge();
@@ -2155,6 +2293,17 @@ function spawnNearbyPin(pin) {
g.userData.pin = pin;
scene.add(g);
+ // Spawn-in transition (membership): a freshly discovered agent eases up from
+ // nothing rather than popping into the scene. tick() advances _spawnT and scales
+ // the whole group (dot/impostor/full all ride it) with a cubic ease-out. Reduced
+ // motion lands it at full size immediately. See despawnNearbyPin for the exit.
+ if (prefersReducedMotion()) {
+ pin._spawnT = SPAWN_DURATION;
+ } else {
+ pin._spawnT = 0;
+ g.scale.setScalar(0.01);
+ }
+
// Confidence ring (A3) — a ground footprint sized to the real GPS uncertainty
// so users see the true precision instead of being misled into thinking it's
// centimetre-perfect. Amber when the lock is loose. Built before the label so
@@ -4036,6 +4185,26 @@ function tick() {
}
}
+ // Membership transitions (task 04): ease a freshly discovered agent up from
+ // nothing (scale 0 → 1, cubic ease-out), and shrink an evicted one to nothing
+ // before disposing it. Both run far from the viewer (spawn at the ~40 m enter
+ // edge, despawn past ~55 m), so they never collide with the close-range greet pop
+ // that drives scale.y. Reduced-motion skips straight to the end state.
+ for (const pin of nearbyPins) {
+ if (pin.group && pin._spawnT < SPAWN_DURATION) {
+ pin._spawnT += dt;
+ const t = Math.min(1, pin._spawnT / SPAWN_DURATION);
+ pin.group.scale.setScalar(1 - Math.pow(1 - t, 3));
+ }
+ }
+ for (let i = _despawningPins.length - 1; i >= 0; i--) {
+ const pin = _despawningPins[i];
+ pin._despawnT += dt;
+ const t = Math.min(1, pin._despawnT / DESPAWN_DURATION);
+ if (pin.group) pin.group.scale.setScalar(Math.max(0.001, (1 - t) * (1 - t)));
+ if (t >= 1) { disposePin(pin); _despawningPins.splice(i, 1); }
+ }
+
// Distance LOD / draw budget (E2) — ~4 Hz. Decides each pin's band, drives the
// queued GLB loads, impostor bakes and evictions, and sets the per-pin label
// allowance. Runs before awareness so head-tracking only touches mounted models.
@@ -4537,4 +4706,79 @@ if (import.meta.env.DEV) {
side: p.group.position.x > 0.5 ? 'right' : p.group.position.x < -0.5 ? 'left' : 'center',
depth: p.group.position.z > 0.5 ? 'behind' : p.group.position.z < -0.5 ? 'ahead' : 'level',
}));
+
+ // ── Simulated location (L1) ─────────────────────────────────────────────
+ // Run the REAL place/discover flow at any chosen coordinate without touching
+ // the device GPS. This is the only safe way to test on a phone (iOS Safari
+ // can't spoof location) and the only way to test a LAN dev build at all
+ // (geolocation is blocked on non-secure origins). Boot with
+ // `?mockLoc=lat,lng[&mockAcc=8]`, or call `__irlMockLocation(lat,lng)` /
+ // `__irlMockLocation(null)` from the console. A persistent badge makes a fake
+ // fix impossible to mistake for a real one.
+ let _mockBadge = null;
+ function showMockBadge(lat, lng) {
+ if (!_mockBadge) {
+ _mockBadge = document.createElement('div');
+ _mockBadge.id = 'irl-mock-badge';
+ _mockBadge.setAttribute('role', 'status');
+ _mockBadge.style.cssText = [
+ 'position:fixed', 'top:8px', 'left:50%', 'transform:translateX(-50%)',
+ 'z-index:99999', 'pointer-events:none',
+ 'padding:5px 11px', 'border-radius:999px',
+ 'background:rgba(20,16,4,.92)', 'border:1px solid #f0b400', 'color:#ffd45e',
+ 'font:600 11px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace',
+ 'letter-spacing:.04em', 'box-shadow:0 2px 10px rgba(0,0,0,.5)', 'white-space:nowrap',
+ ].join(';');
+ document.body.appendChild(_mockBadge);
+ }
+ _mockBadge.textContent = `📍 SIMULATED LOCATION · ${lat.toFixed(4)}, ${lng.toFixed(4)}`;
+ _mockBadge.style.display = '';
+ }
+ function hideMockBadge() { if (_mockBadge) _mockBadge.style.display = 'none'; }
+
+ // Seed a synthetic fix through the REAL onGPSPosition path (forcing the
+ // first-fix seed branch so the mock lands exactly, with no low-pass blend),
+ // after stopping any live watch so a real coordinate is never read.
+ function applyMockFix(lat, lng, accuracy = 10) {
+ if (gpsState.watchId != null) { navigator.geolocation.clearWatch(gpsState.watchId); gpsState.watchId = null; }
+ _mockLocation = true;
+ gpsState.ready = false; // force the exact-seed branch
+ onGPSPosition({ coords: { latitude: lat, longitude: lng, accuracy, altitude: null } });
+ showMockBadge(lat, lng);
+ }
+
+ window.__irlMockLocation = (lat, lng, acc = 10) => {
+ if (lat == null) {
+ _mockLocation = false;
+ hideMockBadge();
+ initGPS(); // resume the real watch
+ log.info('[irl] simulated location cleared — resuming real GPS');
+ return 'cleared';
+ }
+ if (!Number.isFinite(lat) || !Number.isFinite(lng) ||
+ lat < -90 || lat > 90 || lng < -180 || lng > 180) {
+ return 'usage: __irlMockLocation(lat, lng[, accuracyM]) — lat∈[-90,90], lng∈[-180,180]; null to clear';
+ }
+ applyMockFix(lat, lng, Number.isFinite(acc) ? acc : 10);
+ log.info(`[irl] simulated location set → ${lat}, ${lng}`);
+ return { mocked: { lat, lng, acc } };
+ };
+
+ // Boot-time URL param. Malformed input warns and falls through to real GPS.
+ try {
+ const params = new URLSearchParams(location.search);
+ const mp = params.get('mockLoc');
+ if (mp) {
+ const [a, b] = mp.split(',').map((s) => parseFloat(s.trim()));
+ const acc = parseFloat(params.get('mockAcc'));
+ if (Number.isFinite(a) && Number.isFinite(b) && a >= -90 && a <= 90 && b >= -180 && b <= 180) {
+ applyMockFix(a, b, Number.isFinite(acc) ? acc : 10);
+ log.info(`[irl] ?mockLoc → simulated location ${a}, ${b}`);
+ } else {
+ log.warn(`[irl] ignoring malformed ?mockLoc="${mp}" — expected "lat,lng"`);
+ }
+ }
+ } catch (e) {
+ log.warn('[irl] mockLoc parse failed:', e?.message || e);
+ }
}
diff --git a/src/irl/proximity-band.js b/src/irl/proximity-band.js
new file mode 100644
index 000000000..426743698
--- /dev/null
+++ b/src/irl/proximity-band.js
@@ -0,0 +1,57 @@
+// GPS-edge hysteresis for nearby-agent membership (IRL task 04).
+//
+// Consumer GPS is ~5–30 m noisy and the "stumble upon" discovery gate is tight
+// (40 m), so an agent sitting on the boundary would otherwise cross the threshold
+// on *every* fix — the server returns it, drops it, returns it — and the viewer
+// watches the avatar spawn, dispose its GPU resources, and respawn on repeat. The
+// origin low-pass (blendOrigin) smooths the *viewer* origin but does nothing for
+// *set membership* churn at the edge. This module is that missing piece.
+//
+// It is the PURE membership policy: given a pin's client-computed distance, whether
+// it's already rendered, whether the server still lists it, and how many consecutive
+// polls it's been out-of-band, it returns exactly one action. No DOM, no Three.js,
+// no clock — so the band (enter / exit / debounce) is proven in a unit test.
+//
+// Two ideas, both local so they hold regardless of the server's coarse set:
+// 1. Asymmetric band. A pin only ENTERS once it's within ENTER_RADIUS_M, but once
+// rendered it's KEPT until it clearly leaves (EXIT_RADIUS_M, well beyond enter).
+// The client asks the server for the wider read (the 60 m cap) so an edge agent
+// stays stably in the set; the client then trims that to the band itself.
+// 2. Debounced exit. A rendered pin must be out-of-band for DROP_POLLS *consecutive*
+// polls before eviction, so a single bad fix (or one inconsistent server reply)
+// never evicts a stable agent.
+
+// Enter when within this — matches the discovery gate (irl.js NEARBY_RADIUS). Metres.
+export const ENTER_RADIUS_M = 40;
+// Keep a rendered pin until it passes this. The 15 m band fully absorbs ±10 m GPS
+// noise at the 40 m edge: a pin jittering 30–50 m never crosses the exit line, so it
+// holds steady without a single dispose/respawn cycle.
+export const EXIT_RADIUS_M = 55;
+// Consecutive out-of-band polls before eviction. At irl.js POLL_INTERVAL_MS = 10 s
+// this is ~10–20 s of *sustained* absence — long enough that edge jitter never trips
+// it, short enough that a genuine walk-away or a server-side delete clears promptly.
+export const DROP_POLLS = 2;
+
+// Decide one pin's membership for this poll. Returns:
+// 'spawn' — not rendered, now within ENTER → render it (the discovery moment)
+// 'ignore' — not rendered, still outside ENTER → do nothing (no drift-in discovery)
+// 'keep' — rendered and in-band (within EXIT and the server still lists it) → reset debounce
+// 'wait' — rendered but out-of-band, debounce not yet elapsed → hold + increment
+// 'drop' — rendered and out-of-band for DROP_POLLS consecutive polls → dispose
+//
+// `listed` is whether the server returned this pin this poll. A pin absent from the
+// set (deleted, hidden, or walked far past the server cap) is treated as out-of-band
+// regardless of its possibly-stale client distance — so an owner delete clears even
+// from point-blank range, where distance alone would keep it rendered forever.
+export function pinBandAction({ distance, rendered, listed, oobPolls = 0 }, opts = {}) {
+ const enter = opts.enter ?? ENTER_RADIUS_M;
+ const exit = opts.exit ?? EXIT_RADIUS_M;
+ const dropPolls = opts.dropPolls ?? DROP_POLLS;
+
+ if (!rendered) {
+ return listed && distance <= enter ? 'spawn' : 'ignore';
+ }
+ const inBand = listed && distance <= exit;
+ if (inBand) return 'keep';
+ return oobPolls + 1 >= dropPolls ? 'drop' : 'wait';
+}
diff --git a/src/irl/room-session.js b/src/irl/room-session.js
new file mode 100644
index 000000000..73b9eabeb
--- /dev/null
+++ b/src/irl/room-session.js
@@ -0,0 +1,130 @@
+// Room authoring session for /irl "place agents around me" (Epic R / R1).
+//
+// Pure logic so the UI layer in src/irl.js stays thin and this is unit-tested
+// without a phone (mirrors src/irl/room-anchor.js, irl-reactions.js). It owns:
+// • establishing a room (origin = the placer's GPS + the north reference),
+// • turning the placer's live aim (heading + distance) into the POST `room`
+// block the API expects (delegating the geometry to room-anchor.js),
+// • serialize/revive for resuming the same room across reloads.
+//
+// It holds NO DOM, NO network, NO Three.js — the caller wires those. Randomness
+// and the location key are injected (not read here) so the functions are
+// deterministic under test.
+
+import { placeAround } from './room-anchor.js';
+
+// Mirrors api/irl/pins.js ROOM_ID_RE / REL_MAX_M — keep in sync.
+export const ROOM_ID_RE = /^[a-z0-9-]{1,64}$/;
+export const REL_MAX_M = 500;
+
+const DIST_MIN_M = 0.5;
+const DIST_MAX_M = 8;
+export const DIST_DEFAULT_M = 2.5;
+
+/**
+ * A stable, slug-safe room id: `r-<locationKey>-<rand>`, clamped to 64 chars and
+ * normalized to the API's `^[a-z0-9-]{1,64}$`. locationKey is a coarse,
+ * caller-supplied place token (e.g. a truncated geohash) so placements made at
+ * the same spot in one session share a room; rand keeps two nearby rooms apart.
+ */
+export function makeRoomId(locationKey, rand) {
+ const clean = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 24);
+ const loc = clean(locationKey) || 'room';
+ const r = clean(rand) || 'x';
+ return `r-${loc}-${r}`.slice(0, 64);
+}
+
+/**
+ * Establish a room from the placer's current pose. The origin is their GPS; the
+ * frame is true-north (originYawDeg 0) when an absolute compass heading is
+ * available, otherwise it pins to the current heading and the room is a
+ * relative-frame room (R2 reconciles cross-user, A3 down-weights its bearing).
+ * @returns {{id,originLat,originLng,originYawDeg,absolute,createdAt,count}}
+ */
+export function establishRoom({ lat, lng, headingDeg = 0, hasAbsoluteCompass, locationKey, rand, now = 0 }) {
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
+ throw new Error('establishRoom: a GPS fix (lat/lng) is required');
+ }
+ const absolute = !!hasAbsoluteCompass;
+ return {
+ id: makeRoomId(locationKey, rand),
+ originLat: lat,
+ originLng: lng,
+ originYawDeg: absolute ? 0 : (((headingDeg % 360) + 360) % 360),
+ absolute,
+ createdAt: now,
+ count: 0,
+ };
+}
+
+/** Clamp a distance to the aim slider's range. */
+export function clampDistance(distM) {
+ const d = Number(distM);
+ if (!Number.isFinite(d)) return DIST_DEFAULT_M;
+ return Math.min(DIST_MAX_M, Math.max(DIST_MIN_M, d));
+}
+
+/**
+ * Turn the placer's live aim into everything the room-aware POST needs. The
+ * placer need not stand on the origin — placeAround folds in their offset — so
+ * they can walk the room dropping agents that all land in the one shared frame.
+ * @returns {{ lat, lng, heading, room: {id,originLat,originLng,originYawDeg,relEast,relNorth} }}
+ */
+export function roomPlacement({ room, viewerLat, viewerLng, bearingDeg, distM, faceViewer = true }) {
+ if (!room || !ROOM_ID_RE.test(room.id)) throw new Error('roomPlacement: a valid room is required');
+ const p = placeAround({
+ originLat: room.originLat,
+ originLng: room.originLng,
+ viewerLat, viewerLng,
+ bearingDeg,
+ distM: clampDistance(distM),
+ faceViewer,
+ originYawDeg: room.originYawDeg || 0,
+ });
+ return {
+ lat: p.lat,
+ lng: p.lng,
+ heading: p.relYawDeg,
+ room: {
+ id: room.id,
+ originLat: room.originLat,
+ originLng: room.originLng,
+ originYawDeg: room.originYawDeg || 0,
+ relEast: p.relEast,
+ relNorth: p.relNorth,
+ },
+ };
+}
+
+/** Serialize a room for localStorage resume. */
+export function serializeRoom(room) {
+ if (!room) return '';
+ return JSON.stringify({
+ id: room.id, originLat: room.originLat, originLng: room.originLng,
+ originYawDeg: room.originYawDeg || 0, absolute: !!room.absolute,
+ createdAt: room.createdAt || 0, count: room.count || 0,
+ });
+}
+
+/**
+ * Revive a persisted room, validating every field. Returns null on anything
+ * malformed (a corrupt entry must never plant a room at 0,0 or with a bad id).
+ */
+export function reviveRoom(str) {
+ let o;
+ try { o = JSON.parse(str); } catch { return null; }
+ if (!o || typeof o !== 'object') return null;
+ if (!ROOM_ID_RE.test(String(o.id || ''))) return null;
+ const oLat = Number(o.originLat), oLng = Number(o.originLng);
+ if (!(oLat >= -90 && oLat <= 90 && oLng >= -180 && oLng <= 180)) return null;
+ if (oLat === 0 && oLng === 0) return null;
+ return {
+ id: o.id,
+ originLat: oLat,
+ originLng: oLng,
+ originYawDeg: ((Number(o.originYawDeg) || 0) % 360 + 360) % 360,
+ absolute: !!o.absolute,
+ createdAt: Number(o.createdAt) || 0,
+ count: Math.max(0, Number(o.count) || 0),
+ };
+}
diff --git a/src/irl/sensor-fusion.js b/src/irl/sensor-fusion.js
new file mode 100644
index 000000000..2730e5b60
--- /dev/null
+++ b/src/irl/sensor-fusion.js
@@ -0,0 +1,103 @@
+// Pure sensor-fusion helpers for the /irl world-lock camera.
+//
+// Why this exists
+// ───────────────
+// The world-lock camera is driven by `deviceorientation` (alpha/beta) and, on
+// iOS, `webkitCompassHeading`. Real devices deliver `null`, `NaN`, uncalibrated,
+// and discontinuous readings constantly: a magnetometer that walks into a
+// magnetic dead-zone keeps reporting its LAST heading forever; a dropped frame
+// arrives with `NaN` Euler angles; the compass bearing wraps 359°→1° as the user
+// turns. A single bad value flowing untreated into `cameraYaw`/`cameraPitch`
+// makes the avatar snap, spin, freeze, or vanish — the single worst reliability
+// failure the AR experience can have.
+//
+// This module is the pure decision logic that keeps a bad reading from ever
+// reaching the camera. No DOM, no Three.js, no sensors, no clock — plain numbers
+// in, plain numbers out — so src/irl.js wires it to the live event stream while
+// the test suite verifies the math directly (mirrors src/irl/room-anchor.js as a
+// pure, unit-tested core).
+//
+// Coordinate conventions — IDENTICAL to src/irl.js, do not drift:
+// cameraYaw (rad): world Y-rotation; renderedBearing = −cameraYaw.
+// Compass bearing: 0–359° clockwise from true north (0 = N, 90 = E).
+// World yaw from a bearing: yaw = −(deg · π/180) (matches compassToYaw).
+
+const DEG = Math.PI / 180;
+
+// A heading older than this (ms) is treated as dead. iOS fires orientation
+// events at ~60 Hz, so a gap this long means the magnetometer stopped updating
+// (uncalibrated, or in a magnetic dead-zone) — fall back to the relative gyro
+// path rather than keep steering by a frozen bearing.
+export const COMPASS_STALE_MS = 1500;
+
+// Shortest-path angular interpolation (radians). Mirrors `lerpAngle` in
+// src/irl.js; duplicated here so the pure core has no dependency on the DOM
+// bundle. Eases `from` toward `to` along the shortest arc, so crossing the
+// 359°→1° compass boundary is a ~2° move, never a ~360° one.
+export function shortestAngleLerp(from, to, t) {
+ let diff = ((to - from + Math.PI) % (Math.PI * 2)) - Math.PI;
+ if (diff < -Math.PI) diff += Math.PI * 2;
+ return from + diff * t;
+}
+
+// A deviceorientation reading is usable only if BOTH Euler angles are real,
+// finite numbers. `null`/`undefined`/`NaN`/`±Infinity` are all rejected so one
+// bad frame can never poison the camera quaternion. Callers hold the last valid
+// reading on a `false` here rather than substituting 0/90 (which would yank the
+// view's yaw to page-north and slam the pitch to the horizon).
+export function isFiniteReading(alpha, beta) {
+ return Number.isFinite(alpha) && Number.isFinite(beta);
+}
+
+// True while the last good compass sample is recent enough to trust. `lastGoodAt`
+// is the timestamp (same clock as `now`) of the last finite heading; a non-finite
+// `lastGoodAt` (never seen a compass) is never fresh.
+export function isCompassFresh(lastGoodAt, now, staleMs = COMPASS_STALE_MS) {
+ return Number.isFinite(lastGoodAt) && now - lastGoodAt <= staleMs;
+}
+
+// The absolute (north-referenced) yaw path is only correct when a GPS world-anchor
+// gives the scene an absolute origin AND a fresh compass bearing exists. Without
+// GPS the avatar would jump off-frame to its compass bearing the instant it locks;
+// without a fresh compass we are steering by a dead heading — both fall back to the
+// relative gyro path.
+export function shouldUseAbsoluteYaw({ gpsModeActive, compassHeading, compassFresh }) {
+ return Boolean(gpsModeActive) && compassHeading !== null && compassHeading !== undefined && compassFresh;
+}
+
+// Resolve the target `cameraYaw` for one orientation frame.
+//
+// absolute path — ease toward the true bearing along the shortest arc so the
+// avatar stays planted on its real-world direction for every
+// viewer, and a 359°→1° wrap never spins.
+// relative path — integrate alpha deltas from the lock baseline so the view
+// rotates with the phone while the avatar holds its pinned spot.
+//
+// All inputs are finite by contract (the caller holds the last valid reading);
+// the result is therefore always finite.
+export function resolveLockYaw({
+ useAbsolute,
+ prevYaw,
+ alpha,
+ baseAlpha,
+ baseYaw,
+ compassHeading,
+ absoluteSmooth = 0.4,
+}) {
+ if (useAbsolute) {
+ const target = -compassHeading * DEG;
+ return shortestAngleLerp(prevYaw, target, absoluteSmooth);
+ }
+ let dAlpha = alpha - baseAlpha;
+ if (dAlpha > 180) dAlpha -= 360;
+ if (dAlpha < -180) dAlpha += 360;
+ return baseYaw + dAlpha * DEG;
+}
+
+// Clamp a pitch into the camera's range, guaranteeing a finite result. A `NaN`
+// that slipped past upstream guards collapses to 0 (always inside the symmetric
+// range) instead of propagating — `Math.max/min` would otherwise return `NaN`.
+export function clampPitch(pitch, min, max) {
+ const p = Number.isFinite(pitch) ? pitch : 0;
+ return p < min ? min : p > max ? max : p;
+}
diff --git a/tasks/agent-wallet-trading/00-schema-baseline.md b/tasks/agent-wallet-trading/00-schema-baseline.md
new file mode 100644
index 000000000..b668bdebc
--- /dev/null
+++ b/tasks/agent-wallet-trading/00-schema-baseline.md
@@ -0,0 +1,136 @@
+# Task: Schema baseline — guarantee the columns the wallet/agent code writes to exist on a fresh DB
+
+> **Wave 0 — prerequisite. Blocks 01** (and therefore the whole epic). Every
+> wallet-provisioning write targets columns that the canonical `schema.sql`
+> never declares; a database initialised purely from `schema.sql` 500s on the
+> first wallet write. Fix this before the foundation task runs its backfill.
+
+## Context
+
+Agent wallet provisioning stores everything in `agent_identities.meta`:
+`generateSolanaAgentWallet()` / `provisionAgentWallets()` write
+`meta.solana_address`, `meta.encrypted_solana_secret`, `meta.encrypted_wallet_key`
+(`api/_lib/agent-wallet.js:325`, `:127`, `:64`), and the create path persists them
+at `api/agents.js:258`. The agent record also carries a `skills` field.
+
+But the canonical bootstrap schema does **not** declare those columns:
+
+- `CREATE TABLE IF NOT EXISTS agent_identities (…)` at `api/_lib/schema.sql:401-415`
+ has **no `meta` and no `skills` column**.
+- The additive `alter table agent_identities add column if not exists …` block at
+ `api/_lib/schema.sql:422-442` adds `wallet_address`, voice, farcaster, and persona
+ columns — but **not `meta`, not `skills`**.
+- `meta` only ever materialises through a migration that *assumes it already
+ exists* — `api/_lib/migrations/2026-04-29-onchain-unified.sql` does
+ `update agent_identities … meta` and `create index … on agent_identities
+ ((meta->'onchain'->>'chain'))` (`:22,:43,:69-74`) without ever adding the column.
+
+Net effect: a fresh DB provisioned only from `schema.sql` is missing `meta`/`skills`,
+so **every wallet write — and task 01's backfill — fails**. Existing deployments
+only work because the column was hand-added out-of-band, an unenforced deploy-order
+dependency (memory: `vercel-symlink-build-trap` / manual-migration class of bugs).
+
+Two related ordering bugs in the same file, fix them in the same pass:
+
+1. `create index … on agent_identities(wallet_address)` at `schema.sql:419-420`
+ runs **before** `alter table … add column if not exists wallet_address` at
+ `:423` — on a truly fresh DB the index references a column that does not exist
+ yet. Move the index after the column is guaranteed.
+2. Audit the surrounding indexes/`update`s for the same "reference-before-add"
+ pattern and the `is_public` note already flagged at `schema.sql:443-445`.
+
+## Goal
+
+`api/_lib/schema.sql` alone, applied to an empty Postgres database, produces a
+schema on which agent + wallet provisioning, the task-01 backfill, trading,
+sniping, and x402 all succeed with **zero** "column does not exist" errors — and
+re-applying it is a no-op. No code change to the provisioning logic; this is a
+schema-correctness task only.
+
+## Files to Read First
+
+- `api/_lib/schema.sql:401-445` — the `agent_identities` CREATE + additive ALTER
+ block + index ordering + the `is_public` note
+- `api/_lib/migrations/2026-04-29-onchain-unified.sql` — the migration that uses
+ `meta` without adding it; confirm what shape `meta` must hold
+- `api/_lib/agent-wallet.js:64,127,325` — exactly which `meta.*` keys are written
+- `api/agents.js:258-292`, `:150-169` — create + bootstrap paths writing `meta`/`skills`
+- A recent dated migration for the naming/format convention (e.g.
+ `api/_lib/migrations/20260615020000_agent_sniper.sql`)
+- How `schema.sql` is applied on bootstrap and how migrations are run (find the
+ runner; confirm whether `schema.sql` is the source of truth for fresh DBs or
+ whether the migration set is — fix whichever the bootstrap path actually uses)
+
+## What to Build / Do
+
+1. **Declare the missing columns idempotently.** Add to the additive block in
+ `api/_lib/schema.sql` (and mirror in a new dated migration under
+ `api/_lib/migrations/` so existing DBs converge):
+ ```sql
+ alter table agent_identities add column if not exists meta jsonb not null default '{}'::jsonb;
+ alter table agent_identities add column if not exists skills jsonb not null default '[]'::jsonb;
+ ```
+ Verify the exact type/shape `skills` is read/written as in the code before
+ committing to `jsonb`/`'[]'` — match reality, don't guess.
+2. **Fix the index ordering.** Move
+ `create index if not exists agent_identities_wallet on agent_identities(wallet_address)…`
+ to **after** the `add column if not exists wallet_address` statement so a fresh
+ apply never references a not-yet-created column. Apply the same fix to any other
+ index/`update` that references an additively-added column ahead of its `ADD`.
+3. **Fold in the manual migration's column intent.** Whatever `meta`/`onchain`
+ structure `2026-04-29-onchain-unified.sql` depends on must be guaranteed by
+ `schema.sql` so that migration (and the onchain indexes) can never run against a
+ missing column. Do not duplicate the data backfill — only guarantee the column
+ exists first.
+4. **Prove a clean-room apply.** Add a re-runnable verification (extend
+ `scripts/` or a test) that applies `schema.sql` to an empty database (a
+ throwaway/temp Postgres or the existing test harness), then runs the full
+ migration set, and asserts `agent_identities` has `meta` and `skills` and that a
+ simulated provisioning `update … set meta = …` succeeds. This is the regression
+ guard against the next column drifting out of `schema.sql`.
+
+## Constraints
+
+- **Idempotent and additive only.** `add column if not exists`, `create index if
+ not exists`; never `DROP`, never reorder existing data, safe to re-run. Do not
+ rewrite the historical migration files — converge via the new migration +
+ `schema.sql`.
+- **No data loss / no behaviour change.** Provisioning logic in
+ `api/_lib/agent-wallet.js` and `api/agents.js` is unchanged; this task only makes
+ the schema match what that code already assumes.
+- **Source-of-truth discipline.** Whichever artifact the bootstrap actually
+ applies for a fresh DB (`schema.sql` vs the migration set) must be the one that
+ ends up correct; keep both consistent so they can't diverge again.
+- Respect the shared worktree: stage only the files you change
+ (`api/_lib/schema.sql`, the new migration, the verification script/test), never
+ `git add -A`, re-check `git status` before committing.
+
+## Success Criteria
+
+- `agent_identities` has `meta jsonb` and `skills jsonb` declared in
+ `api/_lib/schema.sql` and in a new idempotent dated migration; re-applying either
+ is a no-op.
+- No index or `update` in `schema.sql` references an additively-added column before
+ that column's `ADD` (the `wallet_address` index ordering is fixed).
+- The clean-room verification applies `schema.sql` + migrations to an empty DB and
+ confirms a simulated wallet provisioning write to `meta` succeeds — committed and
+ re-runnable.
+- Task 01's backfill migration can run on a clean-room DB without a
+ "column meta does not exist" error.
+- `npm run typecheck` + `npm test` clean. This is internal infra — **no changelog
+ entry** (no user-visible change), per `CLAUDE.md`. Run the **completionist**
+ subagent on changed files.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
+
+```bash
+git rm "tasks/agent-wallet-trading/00-schema-baseline.md"
+```
+
+Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/agent-wallet-trading/10-e2e-smoke-and-dod-sweep.md b/tasks/agent-wallet-trading/10-e2e-smoke-and-dod-sweep.md
new file mode 100644
index 000000000..66c1c01d6
--- /dev/null
+++ b/tasks/agent-wallet-trading/10-e2e-smoke-and-dod-sweep.md
@@ -0,0 +1,109 @@
+# Task: End-to-end devnet smoke harness + platform-wide Definition-of-Done sweep
+
+## Context
+
+Tasks 01–09 build the full agent-wallet flow: wallet by default (01), fund via
+QR/copy (02), trade from the agent wallet (03/04), snipe (05/06), AMM exits (07),
+x402 pay (08), and withdraw + limits (09). This final task proves the **whole loop**
+works end-to-end and runs a single Definition-of-Done pass across every new surface
+so nothing ships half-wired. It is the gate before the epic is called done.
+
+Known funding constraint (memory `pump-devnet-smoke`, `three-ws-self-registration`):
+devnet airdrops have been rate-limited and platform signers have been unfunded, so
+the harness must run **simulate-first** and degrade gracefully to clearly-reported
+"blocked: needs funded devnet signer" rather than failing or faking a result.
+
+## Goal
+
+A re-runnable `scripts/agent-wallet-smoke.mjs` that exercises
+create → fund → trade → snipe → x402 → withdraw against real devnet/testnet state
+(simulate where live funding is unavailable, with honest blocked-reporting), plus a
+completed DoD sweep (states, a11y, mobile, dead paths, console-clean, typecheck,
+tests, changelog) across the new wallet hub and its tabs.
+
+## Files to Read First
+
+- All of `tasks/agent-wallet-trading/` (the epic README + tasks 01–09) — the success
+ criteria each task promised
+- `scripts/pump-devnet-smoke.mjs` (memory `pump-devnet-smoke`) — existing devnet smoke
+ pattern (simulate-only PASS, funding-gated live) to mirror
+- `scripts/onchain-smoke.mjs` precedent (`tasks/onchain-deployment/10`) — CI-runnable
+ smoke harness shape
+- The endpoints built by this epic: `POST /api/agents/:id/trade` (03),
+ `…/wallet/withdraw` (09), `api/sniper/strategy.js` (06), `api/x402-pay.js` (08),
+ `GET /api/agents/:id/solana` (balance)
+- `CLAUDE.md` "Definition of done" + "Self-review protocol"
+- `scripts/page-audit.mjs` (memory `page-audit-tooling`) + the console-audit baseline
+ (memory `console-audit-baseline`) — for the UI sweep + distinguishing real errors
+ from known non-bug noise
+
+## What to Build / Do
+
+1. **End-to-end smoke script** `scripts/agent-wallet-smoke.mjs` covering, in order:
+ 1. Create an agent → assert a Solana wallet is provisioned (`walletReady`,
+ `solana_address`).
+ 2. Fund: assert the deposit panel's address/QR/`solana:` URI resolve; on
+ devnet, fund the address (or report blocked) and assert the balance reads back.
+ 3. Trade: `POST /api/agents/:id/trade` buy then sell a synthetic/devnet mint;
+ assert confirmed signatures + balance/position changes (simulate if unfunded).
+ 4. Snipe: arm a strategy via `POST /api/sniper/strategy`; assert it persists and
+ (with the worker reachable) records a simulated fill.
+ 5. x402: pay a test endpoint from the agent wallet; assert settlement from the
+ agent's balance (not the platform wallet).
+ 6. Graduation: assert a graduated position exits via AMM (07) rather than parking.
+ 7. Withdraw: sweep SOL/SPL back out; assert confirmed signature + balances.
+ - Each step prints PASS / BLOCKED(reason) / FAIL. Live steps degrade to BLOCKED
+ with the exact missing credential/funding, never to a fake PASS.
+2. **DoD sweep across the new UI** (wallet hub + Deposit/Trade/Snipe/Pay/Withdraw
+ tabs): use `scripts/page-audit.mjs` + a real browser pass to verify, for each
+ surface: designed loading/empty/error/populated states; hover/active/focus on
+ every interactive element; mobile-responsive at 320/768/1440; semantic HTML +
+ ARIA + keyboard nav + focus rings; no dead buttons/links; no console
+ errors/warnings (filtered against the known-noise baseline). File a punch-list and
+ fix every real issue found (or hand specific items back to the owning task).
+3. **Build gates**: confirm `npm run build`, `npm run typecheck`, and `npm test` are
+ all clean across the epic's changes; confirm every user-visible change has a
+ `data/changelog.json` entry.
+4. **Epic completion report**: a short summary of what is fully live vs. what is
+ built-but-blocked-on-credentials/funding (Cloud Run deploy, funded devnet
+ signer), with the exact unblock step for each. Do not claim done for anything you
+ could not verify.
+
+## Constraints
+
+- Simulate-first, honest reporting: never fabricate an on-chain result; BLOCKED is a
+ first-class outcome with the precise reason and unblock step.
+- Use synthetic agent authorities + the $THREE mint (or a clearly-synthetic
+ placeholder) in tests — never a real third-party wallet or any non-$THREE mint.
+- The smoke script is re-runnable and idempotent (cleans up or reuses test agents);
+ no secrets committed; lives under `scripts/`, not the repo root.
+- The DoD sweep fixes real defects but must not silently rewrite another task's
+ scope — hand large items back as follow-ups with specifics.
+
+## Success Criteria
+
+- `node scripts/agent-wallet-smoke.mjs` runs end-to-end against devnet/testnet,
+ printing PASS/BLOCKED/FAIL per step, with simulate fallbacks and zero fake passes.
+- The DoD sweep punch-list is resolved: every new surface has all states designed,
+ is mobile-responsive + accessible, has no dead paths, and is console-clean
+ (against the known-noise baseline).
+- `npm run build`, `npm run typecheck`, `npm test` clean; changelog entries present
+ for all user-visible changes.
+- A completion report distinguishes live vs. credential/funding-blocked, with unblock
+ steps — no overclaiming.
+- Changelog entry (tag: infra). Run the **completionist** subagent on the epic's
+ changed files.
+
+<!-- AUTO:self-delete-on-complete -->
+
+---
+
+## ✅ On completion — delete this file
+
+This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
+
+```bash
+git rm "tasks/agent-wallet-trading/10-e2e-smoke-and-dod-sweep.md"
+```
+
+Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/agent-wallet-trading/README.md b/tasks/agent-wallet-trading/README.md
index 5467e3834..73ae7a6e6 100644
--- a/tasks/agent-wallet-trading/README.md
+++ b/tasks/agent-wallet-trading/README.md
@@ -63,6 +63,7 @@ generic pump.fun trade path are the only exception and must never be promoted.
| # | Gap | Evidence |
|---|-----|----------|
+| 00 | **`schema.sql` never declares the `meta`/`skills` columns every wallet write targets**, and indexes `wallet_address` before that column is added — a fresh DB 500s on the first provision and breaks task 01's backfill | `api/_lib/schema.sql:401-415` (no `meta`/`skills`), `:419-423` (index before `ADD`); `meta` only appears via `migrations/2026-04-29-onchain-unified.sql` which assumes it exists |
| 01 | No single "agent wallet" product surface; legacy agents predating auto-provision may have no wallet; no guaranteed `walletReady` invariant | `api/agents.js:150,258`; no backfill migration |
| 02 | Funding UX is owner-only on agent-detail; no onboarding deposit panel (QR + `solana:` deep-link + live "funds received" confirmation) reachable right after creation | `src/agent-detail.js:1771` (`bindWalletActions(isOwner)`); `pages/create-agent.html:1493` success screen has no fund step |
| 03 | No authenticated endpoint to trade pump.fun **from the agent's own wallet**; only the sniper worker signs from it | `api/pump/[action].js` buy path is user-signed (`:524` verify-after-sign); guardrails live only inside `workers/agent-sniper/executor.js:51` |
@@ -82,6 +83,7 @@ re-check `git status` before committing.
| # | Task | Wave | Blocks |
| -- | ----------------------------------------------------------------- | ---- | -------- |
+| 00 | Schema baseline: declare `meta`/`skills` columns + fix index order| 0 | 01 |
| 01 | Agent-wallet foundation: `walletReady` invariant + backfill + hub | 1 | 02,04,06 |
| 02 | Public/onboarding deposit panel (QR + copy + deep-link + live) | 1 | 10 |
| 03 | Authenticated "trade from agent wallet" endpoint + shared guards | 1 | 04 |
@@ -94,7 +96,7 @@ re-check `git status` before committing.
| 10 | End-to-end devnet smoke harness + Definition-of-Done sweep | 3 | — |
```
-01 ─┬─→ 02 ─┐
+00 ─→ 01 ─┬─→ 02 ─┐
├─→ 03 ─→ 04 ─┤
└─→ 06 ←─ 05 ─┼─→ 10 (e2e + DoD sweep)
07 ── independent │
diff --git a/tasks/irl-production/08-designed-states.md b/tasks/irl-production/08-designed-states.md
new file mode 100644
index 000000000..71f68ef63
--- /dev/null
+++ b/tasks/irl-production/08-designed-states.md
@@ -0,0 +1,60 @@
+# Task 08 — Designed states everywhere (no infinite spinners, no blank voids)
+
+**Phase:** 2 (UX / polish) · **Effort:** M · **Files:** `pages/irl.html`, `src/irl.js`, `src/shared/state-kit.js`
+
+## Why
+Every surface must have a designed loading, empty, and error state (CLAUDE.md
+Definition of Done). Several IRL surfaces today can get stuck on "Loading…" if a
+fetch fails, or show a bare void with no next step. These are the moments a user
+decides whether the product is trustworthy.
+
+## Read first (verify before fixing)
+- Shared state shells — `src/shared/state-kit.js`, `src/shared/async-state.js` (use these)
+- My Pins sheet — `pages/irl.html` `#irl-mypins-*` (~1701) + its loader in `src/irl.js`
+- Inspect card body skeleton — `pages/irl.html` `#irl-card-body` (~1731) + `loadAgentCard` in `src/irl.js`
+- Nearby badge — `pages/irl.html` `#irl-nearby-badge` (~1525) + update logic
+- Radar empty state — `pages/irl.html` `.irl-radar` / `.irl-radar-hint`
+- WebGL-unsupported fallback — the boot guard in `src/irl.js` + its markup
+
+## Scope — confirm, then fix
+
+1. **My Pins: loading → empty → error.** The "Loading…" placeholder must resolve to
+ a skeleton while fetching, a helpful empty state ("You haven't placed any agents
+ yet — turn on Camera AR and tap Pin here") when there are none, and a retryable
+ error state on fetch failure. It must never sit on "Loading…" forever.
+
+2. **Inspect card error.** If `/api/irl/agent-card` fails, replace the skeleton with
+ an in-sheet error + Retry (and still show the minimal known info: name + a link
+ to the agent). Never leave a permanent skeleton.
+
+3. **Nearby badge transitions.** Avoid flashing a green "0 nearby" before the first
+ proximity read returns; show a muted "locating…" until GPS + first read land,
+ then animate to the count. Hide gracefully when not in GPS mode.
+
+4. **Empty radar.** When GPS is ready but no agents are nearby, the radar should read
+ as intentionally empty ("No agents nearby — be the first to place one") via the
+ existing `.irl-radar-hint`, not a blank dial that looks broken.
+
+5. **Unsupported-device clarity.** The WebGL-unavailable / camera-unavailable states
+ should explain the likely cause and the recovery (enable WebGL, try another
+ browser) — designed cards, not bare toasts. (Camera-unsupported already routes to
+ a guidance sheet; bring the others to the same bar.)
+
+## Implementation guidance
+- Route all of these through `state-kit.js` so they share the skeleton/empty/error
+ visual language with the rest of the platform. Each error state has a real Retry
+ that re-runs the fetch.
+- Errors at boundaries: every `fetch` here gets a `.catch` that renders the error
+ state — never an uncaught rejection or a stuck spinner.
+
+## Out of scope
+Permission/onboarding flow (mostly shipped — see task 09 for copy); a11y (task 07).
+
+## Definition of done
+- [ ] Force each fetch to fail (DevTools offline / 500) and confirm every surface
+ shows a designed, retryable error — never an infinite spinner. Document the
+ surfaces tested.
+- [ ] Empty states are helpful and tell the user the next action.
+- [ ] No green "0 nearby" flash on load.
+- [ ] esbuild clean; `npm test` green; changelog entry ("IRL surfaces now show clear
+ loading, empty, and error states").
diff --git a/tasks/irl-production/09-onboarding-copy.md b/tasks/irl-production/09-onboarding-copy.md
new file mode 100644
index 000000000..2fe48f76e
--- /dev/null
+++ b/tasks/irl-production/09-onboarding-copy.md
@@ -0,0 +1,51 @@
+# Task 09 — First-run onboarding clarity and copy quality
+
+**Phase:** 2 (UX / polish) · **Effort:** S · **Files:** `pages/irl.html`, `src/irl.js`, `src/irl/onboarding.js`
+
+## Why
+A new user must instantly understand the core loop: **turn on Camera AR → walk/aim
+→ Pin here to anchor in real space**. Today the subtitle is vague and several
+status strings use abstract jargon ("anchor it", "rotated") or are mildly alarming.
+Copy must be professional and literal (per memory `public-copy-tone`): "3D AI
+agents", never sci-fi metaphors.
+
+## Read first (verify before fixing)
+- Subtitle + hero — `pages/irl.html` `#irl-subtitle` (~1581) "Turn on camera to place in your space"
+- Caption input + autofocus — `src/irl.js:1459-1461` (`setTimeout(... captionInput.focus(), 300)`)
+- Lock/GPS status strings — `src/irl.js:1003`, `1006`, `1312`, and the warn copy in `anchorGpsPin`
+- Onboarding permission copy — `src/irl/onboarding.js`
+
+## Scope — confirm, then fix
+
+1. **First-run guidance.** Make the path obvious for a brand-new user. When the
+ camera is off, the subtitle/hint should point to the next concrete step
+ ("Turn on Camera AR, then tap Pin here to anchor your agent in real space").
+ Once the camera is on but not pinned, nudge toward Pin here. A one-time,
+ dismissible coach hint is acceptable; keep it lightweight and non-blocking.
+
+2. **Caption autofocus.** Replace the fragile `setTimeout(…300)` focus with a focus
+ tied to the sheet's open transition (or `autofocus`), so the keyboard reliably
+ opens on iOS when the caption panel slides up.
+
+3. **Copy rewrite — literal, calm, actionable.** Revise at minimum:
+ - "Waiting for location to pin precisely…" → say what to do if it's slow.
+ - "Pinned to your view — enable location to anchor it for others" → "Your agent is
+ pinned on this device. Turn on location to place it at this real-world spot for
+ others." (or similar — plain, concrete).
+ - "Compass heading unavailable — others may see this agent rotated" → reassuring +
+ accurate, no alarm.
+ - Audit ALL user-facing IRL strings for jargon, sci-fi metaphor, and tone. Keep
+ it short and professional.
+
+4. **Success feedback.** Confirmations ("Pinned", "Camera off") should read as
+ intentional success, paired with the visual treatment from task 08/07.
+
+## Out of scope
+The permission *flow* mechanics (shipped); a11y rings (task 07); state shells (task 08).
+
+## Definition of done
+- [ ] A first-time user can complete pin-an-agent without external help (validate the
+ wording against the actual UI; document the flow).
+- [ ] Caption keyboard opens reliably on iOS (manual).
+- [ ] No abstract/jargony/alarming/sci-fi copy remains; tone matches platform voice.
+- [ ] esbuild clean; `npm test` green; changelog entry ("Clearer IRL onboarding and copy").
diff --git a/tasks/irl-production/10-mobile-responsive-polish.md b/tasks/irl-production/10-mobile-responsive-polish.md
new file mode 100644
index 000000000..729b0e566
--- /dev/null
+++ b/tasks/irl-production/10-mobile-responsive-polish.md
@@ -0,0 +1,52 @@
+# Task 10 — Mobile & responsive polish
+
+**Phase:** 2 (UX / polish) · **Effort:** S · **Files:** `pages/irl.html`, `src/irl.js`
+
+## Why
+IRL is a phone-first product. It must be flawless at 320px, on notched devices, in
+both orientations, and must not trigger iOS's input-zoom. Today there are gaps in
+safe-area handling, small-screen layout, and input sizing that would make a senior
+designer wince.
+
+## Read first (verify before fixing)
+- Viewport meta — `pages/irl.html` `<meta name="viewport">` (must allow safe-area + no forced zoom)
+- Joystick CSS + safe-area — `pages/irl.html` `.irl-joystick` / `#irl-joystick` (~216-234)
+- Bottom controls + secondary row layout — the control-row CSS
+- Caption textarea font-size — `pages/irl.html` (~1673) — iOS zooms inputs < 16px
+- Floating agent labels — `.irl-agent-label` (~990-1061) + `updateLabels()`
+- Calibrate readouts — `.irl-cal-*`
+
+## Scope — confirm, then fix
+
+1. **Safe-area insets in both orientations.** Every fixed control (joystick, bottom
+ controls, topbar, sheets) respects `env(safe-area-inset-*)` in portrait AND
+ landscape. Nothing hides under the notch, home indicator, or rounded corners.
+
+2. **320px layout.** At the narrowest common width, the secondary control row must
+ not squish illegibly or clip. Allow wrapping or a horizontal scroll affordance;
+ ensure all controls remain tappable (min 44×44 target).
+
+3. **iOS input-zoom.** Set the caption textarea (and any input) to `font-size: 16px`
+ on mobile to stop Safari auto-zooming on focus; scale down on desktop via media
+ query if desired.
+
+4. **Floating labels on small screens.** Ensure `text-overflow: ellipsis` and
+ sensible max-width so long agent names don't overflow or overlap neighboring
+ labels; keep hit areas from overlapping (coordinate with task 05).
+
+5. **Landscape joystick + gestures.** Joystick reachable and not under UI in
+ landscape; confirm two-finger calibrate gesture direction is correct when the
+ screen is rotated (coordinate with task 02's `screen.orientation.angle`).
+
+6. **Readout legibility.** Calibrate/height readouts get consistent line-height and
+ sizing so they're readable in both orientations.
+
+## Out of scope
+Camera-coupled FOV/orientation math (task 02); a11y focus/contrast (task 07).
+
+## Definition of done
+- [ ] Verified at 320px, a notched device profile, portrait + landscape (real device
+ or device emulation — document widths/devices tested).
+- [ ] No control under a safe-area; no input-zoom on iOS; no label overflow at 320px.
+- [ ] All tap targets ≥ 44px.
+- [ ] esbuild clean; `npm test` green; changelog entry if visibly improved.
diff --git a/tasks/irl-production/11-api-error-boundaries.md b/tasks/irl-production/11-api-error-boundaries.md
new file mode 100644
index 000000000..55466db95
--- /dev/null
+++ b/tasks/irl-production/11-api-error-boundaries.md
@@ -0,0 +1,52 @@
+# Task 11 — API error boundaries: zero 500s, graceful degradation
+
+**Phase:** 3 (backend) · **Effort:** M · **Files:** `api/irl/*.js`
+
+## Why
+Every endpoint boundary must handle malformed input, missing rows, missing tables,
+and unserializable payloads without throwing a 500 or leaking a stack trace. A
+production API returns a clean status and a useful body on every path.
+
+## Read first (verify before fixing — confirm each line still matches)
+- `api/irl/pins.js` — `handleCalibrate` null-row (~346); nearby `radius` parse (~489)
+- `api/irl/interactions.js` — fire-and-forget view_count `.catch(()=>{})` (~251);
+ `JSON.stringify(payload)::jsonb` insert (~242); pay de-dupe (~216-221)
+- `api/irl/interactions-stream.js` — `conn.send(...)` error swallow (~163)
+- `api/irl/agent-card.js` — `fetchReputation` null/missing-table path (~86-110, ~149)
+- `api/irl/agent-summary.js` — interaction_count / last_interaction_at + LEFT JOIN nulls (~48-78)
+
+## Scope — confirm, then fix
+
+1. **Null-row after mutation.** `handleCalibrate` (and any UPDATE…RETURNING path that
+ can match zero rows) must return `404` when no row comes back, not `{ pin: null }`.
+
+2. **JSON safety.** Wrap the interactions `JSON.stringify(payload)` insert so a
+ circular/unserializable payload returns `400`, never an uncaught 500. Validate
+ `clampPayload` output is always serializable.
+
+3. **Graceful schema degrade.** Where a table may not exist yet (reputation,
+ `irl_interactions`), the query must `.catch` into a safe default
+ (`available:false` / `0` / `null`) so a fresh or mid-migration DB never 500s.
+ Guard the downstream code against undefined rows (e.g. agent-card `buildCard`).
+
+4. **Input validation at the boundary.** `radius` (reject non-finite), pin `id`
+ format, and required body fields validated up front with a `400` + clear message.
+
+5. **SSE send failures surface, not vanish.** `conn.send` failures must be logged
+ (task 14 covers the logging contract) and the dead connection cleaned up, not
+ silently dropped.
+
+## Implementation guidance
+- Keep the existing `json(res, status, body)` helper and response shapes.
+- Internal code may trust itself; harden only the boundaries (network, DB, user input).
+- Add/extend tests under `tests/api/irl-*.test.js` for each new failure path (malformed
+ input → 400, missing row → 404, missing table → safe default). These tests run in
+ Node and ARE verifiable here.
+- **Do not edit `data/changelog.json`** — return your proposed changelog line in your
+ summary; the orchestrator consolidates it.
+
+## Definition of done
+- [ ] No endpoint can 500 on malformed input, missing row, or missing table — covered
+ by new/extended `tests/api/irl-*.test.js`.
+- [ ] No stack trace or internal detail in any client response (coordinate with task 13).
+- [ ] `npm test` green.
diff --git a/tasks/irl-production/12-resilience-fail-open.md b/tasks/irl-production/12-resilience-fail-open.md
new file mode 100644
index 000000000..c010f7a41
--- /dev/null
+++ b/tasks/irl-production/12-resilience-fail-open.md
@@ -0,0 +1,51 @@
+# Task 12 — Resilience: fail-open on dependency outages, no tight retry loops
+
+**Phase:** 3 (backend) · **Effort:** M · **Files:** `api/irl/pins.js`, `api/irl/interactions-stream.js`
+
+## Why
+IRL depends on Redis (rate limit), the DB (Neon), and the Guardian/watsonx
+moderation check. When a dependency degrades, the feature must degrade gracefully —
+never 500 the whole endpoint, never spin a tight retry loop that saturates Vercel
+concurrency, never block every request on a dead upstream.
+
+## Read first (verify before fixing)
+- Placement rate limit (`Promise.all([burst, hourly])`) — `api/irl/pins.js:~634-649`
+- Guardian/watsonx check (4s bound, per-request) — `api/irl/pins.js:~76-100`
+- SSE poller breaker + retry delay — `api/irl/interactions-stream.js:~120-196`
+- SSE `seen` dedupe set growth — `api/irl/interactions-stream.js:~176-181`
+
+## Scope — confirm, then fix
+
+1. **Rate-limiter fails open with a log.** Wrap the Redis token-bucket calls in
+ try/catch: on a Redis outage, log a warning and allow the request (fail open) —
+ the comment already says this is the intent, but confirm there's actually a
+ try/catch and a log, not an unhandled rejection that 500s the POST.
+
+2. **Guardian degraded-state cache.** A dead moderation upstream currently costs
+ every placement its full timeout. Cache the "degraded" verdict for ~60s so one
+ failure doesn't make every subsequent placement wait. Keep the per-request
+ timeout tight (~2s) and fail toward allowing placement (or your existing safe
+ default) with a log.
+
+3. **SSE breaker on persistent failure.** The poller must engage its breaker / back
+ off on ANY persistent error, not only quota errors — otherwise a DB outage turns
+ into a tight `POLL_MS_MIN` retry loop. After N consecutive failures, degrade to
+ heartbeat-only with exponential backoff; recover when the DB returns.
+
+4. **Bounded dedupe memory.** Ensure the SSE `seen` set is pruned (size or
+ time-based) so a long-lived instance under constant activity doesn't creep toward
+ unbounded memory.
+
+## Implementation guidance
+- Match the existing limiter/breaker patterns already used elsewhere in the repo
+ (see the forge/ratelimit health work in memory `redis-quota-incident`) for
+ consistency.
+- Where logic is pure (backoff schedule, breaker state machine, dedupe pruning),
+ extract it and unit-test it under `tests/api/`.
+- **Do not edit `data/changelog.json`** — return the proposed line in your summary.
+
+## Definition of done
+- [ ] Simulated Redis/DB/Guardian outage degrades gracefully (no 500, no tight loop,
+ no per-request multi-second stall) — covered by unit tests on the pure parts.
+- [ ] Breaker + backoff verified by test; dedupe pruning verified by test.
+- [ ] `npm test` green.
diff --git a/tasks/irl-production/13-security-validation.md b/tasks/irl-production/13-security-validation.md
new file mode 100644
index 000000000..a15949534
--- /dev/null
+++ b/tasks/irl-production/13-security-validation.md
@@ -0,0 +1,55 @@
+# Task 13 — Security & validation hardening
+
+**Phase:** 3 (backend) · **Effort:** M · **Files:** `api/irl/pins.js`, `api/irl/report.js`
+
+## Why
+The placement/report/calibrate endpoints accept untrusted input from anonymous
+devices. They must validate strictly, never leak server internals, enforce
+ownership and expiry, and resist abuse — all while preserving the deliberate
+location-privacy lockdown (no widening of nearby reads).
+
+## Read first (verify before fixing)
+- Outfit bake error response (`detail: err?.message`) — `api/irl/pins.js:~400`
+- Calibrate/outfit ownership + id handling — `api/irl/pins.js:~282-372`
+- Pin expiry on mutations — `api/irl/pins.js:~285, 372`
+- x402 endpoint allow-list parse — `api/irl/pins.js:~109-125`
+- Report `detail` sanitization — `api/irl/report.js:~70-73`
+- Report abuse caps (per-IP exists; per-pin?) — `api/irl/report.js`
+
+## Scope — confirm, then fix
+
+1. **No internal-detail disclosure.** The outfit-bake error must not echo
+ `err.message` to the client (it can leak paths/upstream errors). Log full detail
+ server-side; return a generic message. Sweep other endpoints for the same pattern.
+
+2. **Strict id validation.** Validate pin `id` is a UUID (or the exact expected
+ format) at the top of calibrate/outfit/delete paths — reject early with `400`.
+ (SQL is already parameterized; this stops oversized/garbage ids reaching logs.)
+
+3. **Ownership + expiry on mutations.** Calibrate, outfit, and delete must verify the
+ `device_token`/owner AND that the pin is not expired (`expires_at IS NULL OR
+ expires_at > NOW()`) before mutating. Confirm and add what's missing.
+
+4. **Report input sanitization.** Sanitize/escape the `detail` field (strip control
+ chars/null bytes, bound length) before storing, so the moderation console renders
+ it safely.
+
+5. **Report abuse caps.** In addition to per-IP limits, add a per-pin ceiling (e.g.
+ reject once a pin exceeds N reports in 24h) so a distributed report flood can't
+ hide a legitimate pin faster than intended. Keep the distinct-reporter dedup.
+
+6. **Config validation.** If `IRL_X402_ALLOWED_HOSTS` is empty/malformed, fail safe
+ (reject external x402 endpoints) rather than silently accepting a relative/blank
+ host. Validate the parsed allow-list.
+
+## Constraints
+- **Do not widen the nearby read, add a location feed, or re-add pin broadcast.** The
+ privacy lockdown stands.
+- **Do not edit `data/changelog.json`** — return the proposed line in your summary.
+
+## Definition of done
+- [ ] No client response leaks internal error detail (coordinate with task 11).
+- [ ] id/expiry/ownership/allow-list/report-detail validation covered by
+ `tests/api/irl-*.test.js`.
+- [ ] Per-pin report cap covered by a test.
+- [ ] `npm test` green.
diff --git a/tasks/irl-production/14-observability.md b/tasks/irl-production/14-observability.md
new file mode 100644
index 000000000..f63f7c737
--- /dev/null
+++ b/tasks/irl-production/14-observability.md
@@ -0,0 +1,50 @@
+# Task 14 — Observability: log the right things, alert on what matters
+
+**Phase:** 3 (backend) · **Effort:** S · **Files:** `api/irl/*.js`, `api/cron/irl-reap.js`, `multiplayer/src/rooms/IrlRoom.js`
+
+## Why
+"Zero error" requires *knowing* when something breaks in production. Today several
+IRL failure paths swallow errors silently and key moderation events leave no audit
+trail. Wire IRL into the platform's existing observability so operators see failures
+and moderation actions.
+
+## Read first (verify before fixing)
+- Existing ops/error pipeline — search the repo for `sendOpsAlert`, `[client-error]`,
+ and the Telegram alerts wiring (memory `observability-stack`); reuse it, don't invent.
+- Silent catches — `api/irl/interactions.js:~251`, `api/irl/interactions-stream.js:~163`
+- Moderation hide path — `api/irl/report.js:~129-140`
+- Reaper cron — `api/cron/irl-reap.js`
+- Realtime room — `multiplayer/src/rooms/IrlRoom.js`
+
+## Scope — confirm, then fix
+
+1. **No silent swallows.** Replace bare `.catch(() => {})` on meaningful operations
+ (view_count increment, SSE send, etc.) with a structured `console.error`/`warn`
+ that includes endpoint + context. Keep truly-ignorable best-effort calls cheap but
+ logged at `warn`.
+
+2. **Moderation audit + alert.** When a pin is auto-hidden after crossing the report
+ threshold, log a structured event AND fire an ops alert (`sendOpsAlert`) with the
+ pin id, report count, and timestamp, so the review team has visibility.
+
+3. **SSE + poller metrics.** Periodically log connection count, dispatch rate, error
+ count, and current delay for the interactions-stream poller, so a stuck poller is
+ diagnosable.
+
+4. **Reaper cron telemetry.** The IRL reaper should log how many pins it expired per
+ run (and alert on an anomalous spike or repeated failures).
+
+5. **Realtime room health.** Confirm `IrlRoom` logs join/leave/error at a useful
+ level without leaking PII (presence is anonymous — keep it that way).
+
+## Constraints
+- Reuse the existing alert/log pipeline and respect privacy (no precise coordinates,
+ no device identifiers in logs/alerts).
+- **Do not edit `data/changelog.json`** — return the proposed line (observability is
+ usually internal-only; include a line only if there's a user-visible effect).
+
+## Definition of done
+- [ ] No meaningful error path is silently swallowed; all log with context.
+- [ ] Pin auto-hide fires a structured log + ops alert.
+- [ ] Poller + reaper emit periodic health/telemetry lines.
+- [ ] Any pure helper (e.g. log-sampling) unit-tested; `npm test` green.
diff --git a/tasks/irl-production/15-deploy-verify-and-qa.md b/tasks/irl-production/15-deploy-verify-and-qa.md
new file mode 100644
index 000000000..923e7aeb5
--- /dev/null
+++ b/tasks/irl-production/15-deploy-verify-and-qa.md
@@ -0,0 +1,57 @@
+# Task 15 — Launch gate: deploy verification, real-device QA, console-clean audit
+
+**Phase:** 4 (launch gate) · **Effort:** M · **Run last.** · **Files:** verification + reports only
+
+## Why
+This is the gate that proves the whole program actually landed in production. Code
+that passes locally but 404s in prod (a known IRL risk — newer `/api/irl/*`
+endpoints have 404'd from a stale deploy predating the commit that added them) is
+NOT done. This task verifies the deployed reality and the real-device experience.
+
+## Read first
+- `tasks/irl-production/README.md` (constraints) and the summaries from tasks 01–14.
+- Known deploy traps: memory `vercel-deploy-pipeline`, `vercel-symlink-build-trap`,
+ `vercel-build-clobbers-api`, `irl-b2-agent-card` (stale-deploy 404s), and
+ `pump-action-shadows-dedicated-files`.
+
+## Scope
+
+1. **Automated gates (run and paste output):**
+ - `npm test` — full suite green.
+ - `npx esbuild src/irl.js --outfile=/dev/null` and the other changed client modules — clean.
+ - `npm run typecheck` — green (per memory `typecheck-ratchet`).
+ - `npm run build:pages` — validates the changelog and regenerates artifacts.
+ - Confirm no `api/irl/*.js` file was clobbered by an esbuild bundle
+ (`head -1` must not be `__defProp`/`createRequire`).
+
+2. **Deployed-endpoint verification.** After deploy, confirm all six endpoints
+ respond in production (not 404 from a stale deploy):
+ `/api/irl/pins`, `/api/irl/agent-card`, `/api/irl/agent-summary`,
+ `/api/irl/interactions`, `/api/irl/interactions-stream`, `/api/irl/report`.
+ Verify each has its `vercel.json` function entry AND route, and that the live
+ deployment is built from the commit that contains these changes (check the
+ deployments API / commit SHA). Document the prod status of each.
+
+3. **Real-device test matrix (manual — document results honestly):**
+ - **iOS Safari:** camera permission → Camera AR → Pin here (no GPS, then with
+ GPS) → pan: avatar stays anchored, visible only when aimed at → inspect an
+ agent → x402 pay path reachable → rotate device → background/foreground.
+ - **Android Chrome:** same, plus the WebXR "Place on floor" flow and AR↔XR toggling.
+ - Both: 320px layout, keyboard/screen-reader spot check, reduced-motion.
+
+4. **Console-clean audit.** On the live `/irl`, the console must be free of errors and
+ of warnings originating from our code. Distinguish real issues from known benign
+ noise (memory `console-audit-baseline`: insights 404, HMR WS, GPU-stall, rapier/
+ colyseus). Fix anything real; document the rest.
+
+5. **End-to-end smoke.** Place a pin, confirm it persists, appears within range on a
+ second device/session, can be inspected, reported, and is reaped on expiry.
+
+## Definition of done
+- [ ] All automated gates green (output pasted).
+- [ ] All six endpoints verified live in prod against the deploying commit SHA.
+- [ ] Real-device matrix exercised; results documented (including anything that
+ could not be verified and why).
+- [ ] Live console clean of real errors/warnings.
+- [ ] A short launch-readiness report: what shipped, what's verified, residual risks.
+- [ ] Consolidated changelog reviewed and live.
diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.js
index ccb95a622..8ff4ae6d9 100644
--- a/tests/animation-retarget.test.js
+++ b/tests/animation-retarget.test.js
@@ -31,6 +31,7 @@ import {
scaleClipSpeed,
MIN_COVERAGE,
} from '../src/animation-retarget.js';
+import { CANONICAL_REST } from '../src/animation-canonical-rest.js';
// Build a SkinnedMesh-rooted skeleton from a list of bone names so
// canonicalNodeMapFromObject finds it the way it would in a real GLB.
@@ -153,61 +154,76 @@ describe('retargetClip', () => {
});
describe('bind-rotation correction', () => {
- // Mixamo/FBX rigs bake the up-axis as a −90°X rest on Hips (with a +90°X on
- // the armature parent). A clip authored for an identity-Hips rest would wipe
- // that out and tip the avatar onto its back; the correction re-applies it.
- const HIPS_MINUS_90X = new Quaternion().setFromAxisAngle({ x: 1, y: 0, z: 0 }, -Math.PI / 2);
+ // A −90°X rest, the up-axis convention Mixamo/FBX bakes onto Hips.
+ const MINUS_90X = new Quaternion().setFromAxisAngle({ x: 1, y: 0, z: 0 }, -Math.PI / 2);
- it('round-trips a clip unchanged when the rig already matches the authoring rest', () => {
+ // Pose a synthetic rig in the canonical authoring rest (cz's rest pose), so it
+ // matches the convention the clip library was baked against.
+ function applyAuthoringRest(rig, names) {
+ for (const n of names) {
+ const b = rig.getObjectByName(n);
+ if (b && CANONICAL_REST[n]) b.quaternion.fromArray(CANONICAL_REST[n]);
+ }
+ }
+
+ it('round-trips byte-for-byte when the rig matches the canonical authoring rest', () => {
const clip = makeCanonicalClip();
- const rig = makeRig(CANONICAL_RIG); // every bone at identity rest
+ const rig = makeRig(CANONICAL_RIG);
+ applyAuthoringRest(rig, CANONICAL_RIG);
const map = canonicalNodeMapFromObject(rig);
const targetRest = canonicalRestMapFromObject(rig);
- const r = retargetClip(clip, map, { hipScale: 1, targetRest });
- const hipsQ = r.clip.tracks.find((t) => t.name === 'Hips.quaternion');
- expect(Array.from(hipsQ.values)).toEqual([0, 0, 0, 1, 0, 0, 0, 1]);
+ const corrected = retargetClip(clip, map, { hipScale: 1, targetRest }).clip;
+ const verbatim = retargetClip(clip, map, { hipScale: 1 }).clip; // no targetRest → no correction
+ // Every correction is identity (target rest == authoring rest) → skipped.
+ corrected.tracks.forEach((t, i) => {
+ expect(Array.from(t.values)).toEqual(Array.from(verbatim.tracks[i].values));
+ });
});
- it('re-applies a −90°X Hips rest the clip would otherwise overwrite', () => {
- const clip = makeCanonicalClip(); // Hips.quaternion is identity at every key
+ it('re-applies a Hips up-axis rest the clip would otherwise overwrite (stays upright)', () => {
+ const clip = makeCanonicalClip(); // Hips.quaternion identity at every key
const rig = makeRig(CANONICAL_RIG);
- rig.getObjectByName('Hips').quaternion.copy(HIPS_MINUS_90X);
+ applyAuthoringRest(rig, CANONICAL_RIG);
+ // Bake a Mixamo-style −90°X onto Hips: Tr = (−90X)·Sr ⇒ C = Tr·Sr⁻¹ = −90X.
+ const sr = new Quaternion().fromArray(CANONICAL_REST.Hips);
+ rig.getObjectByName('Hips').quaternion.copy(MINUS_90X.clone().multiply(sr));
const map = canonicalNodeMapFromObject(rig);
const targetRest = canonicalRestMapFromObject(rig);
- const r = retargetClip(clip, map, { hipScale: 1, targetRest });
+ const r = retargetClip(clip, map, { hipScale: 1, targetRest }).clip;
- // C · identity = C = the rig's Hips rest, so the body stands upright.
- const hipsQ = r.clip.tracks.find((t) => t.name === 'Hips.quaternion');
- expect(hipsQ.values[0]).toBeCloseTo(HIPS_MINUS_90X.x, 5);
- expect(hipsQ.values[3]).toBeCloseTo(HIPS_MINUS_90X.w, 5);
+ // C · identity = C = −90X exactly, restoring the rig's upright convention.
+ const hipsQ = r.tracks.find((t) => t.name === 'Hips.quaternion');
+ expect(hipsQ.values[0]).toBeCloseTo(MINUS_90X.x, 5);
+ expect(hipsQ.values[3]).toBeCloseTo(MINUS_90X.w, 5);
- // Root-motion keyframes are rotated by the same correction: (0,1,0) → (0,0,−1).
- const hipsP = r.clip.tracks.find((t) => t.name === 'Hips.position');
- expect(hipsP.values[0]).toBeCloseTo(0, 5);
- expect(hipsP.values[1]).toBeCloseTo(0, 5);
+ // Root-motion keyframes rotate by the same correction: (0,1,0) → (0,0,−1).
+ const hipsP = r.tracks.find((t) => t.name === 'Hips.position');
expect(hipsP.values[2]).toBeCloseTo(-1, 5);
});
- it('leaves limb bones verbatim even when the rig gives them a non-identity rest', () => {
+ it('corrects limb bones too — a T-pose (identity) arm rest is not copied verbatim', () => {
const clip = makeCanonicalClip();
- const rig = makeRig(CANONICAL_RIG);
- rig.getObjectByName('LeftArm').quaternion.copy(HIPS_MINUS_90X);
+ const rig = makeRig(CANONICAL_RIG); // identity rests ≠ cz's A-pose authoring rest
const map = canonicalNodeMapFromObject(rig);
const targetRest = canonicalRestMapFromObject(rig);
- const r = retargetClip(clip, map, { hipScale: 1, targetRest });
- const armQ = r.clip.tracks.find((t) => t.name === 'LeftArm.quaternion');
- // Only Hips carries the up-axis convention; limbs are copied as authored.
- expect(Array.from(armQ.values)).toEqual([0, 0, 0, 1, 0, 0, 0, 1]);
+ const corrected = retargetClip(clip, map, { hipScale: 1, targetRest }).clip;
+ const verbatim = retargetClip(clip, map, { hipScale: 1 }).clip;
+ const armC = corrected.tracks.find((t) => t.name === 'LeftArm.quaternion');
+ const armV = verbatim.tracks.find((t) => t.name === 'LeftArm.quaternion');
+ // cz rests its arms in an A-pose, so an identity-rest arm gets a real correction.
+ expect(Array.from(armC.values)).not.toEqual(Array.from(armV.values));
});
- it('hip scaling and rotation compose: position is both rotated and scaled', () => {
+ it('hip scaling and rotation compose on the position track', () => {
const clip = makeCanonicalClip();
const rig = makeRig(CANONICAL_RIG);
- rig.getObjectByName('Hips').quaternion.copy(HIPS_MINUS_90X);
+ applyAuthoringRest(rig, CANONICAL_RIG);
+ const sr = new Quaternion().fromArray(CANONICAL_REST.Hips);
+ rig.getObjectByName('Hips').quaternion.copy(MINUS_90X.clone().multiply(sr));
const map = canonicalNodeMapFromObject(rig);
const targetRest = canonicalRestMapFromObject(rig);
- const r = retargetClip(clip, map, { hipScale: 2, targetRest });
- const hipsP = r.clip.tracks.find((t) => t.name === 'Hips.position');
+ const r = retargetClip(clip, map, { hipScale: 2, targetRest }).clip;
+ const hipsP = r.tracks.find((t) => t.name === 'Hips.position');
// (0,1,0) rotated → (0,0,−1), then ×2 → (0,0,−2).
expect(hipsP.values[2]).toBeCloseTo(-2, 5);
});
diff --git a/tests/irl-proximity-band.test.js b/tests/irl-proximity-band.test.js
new file mode 100644
index 000000000..5ce9d1252
--- /dev/null
+++ b/tests/irl-proximity-band.test.js
@@ -0,0 +1,148 @@
+// GPS-edge hysteresis band for nearby-agent membership (src/irl/proximity-band.js).
+//
+// These tests pin the contract that kills edge flicker: an agent on the discovery
+// boundary, with consumer GPS jittering ±10 m, must NOT pop in and out. The policy is
+// pure (distance + a few flags in, one action out), so the whole enter/exit/debounce
+// band is proven here with no DOM, no Three.js, and no real clock — exactly the shape
+// loadNearbyPins() drives each 10 s poll.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ ENTER_RADIUS_M,
+ EXIT_RADIUS_M,
+ DROP_POLLS,
+ pinBandAction,
+} from '../src/irl/proximity-band.js';
+
+// Mirror of how loadNearbyPins() threads the per-pin debounce counter: feed a series
+// of (distance, listed) polls through the band and collect the actions, carrying the
+// rendered flag + oobPolls forward exactly as the real reconcile loop does. Returns
+// the action sequence plus whether the pin was ever disposed.
+function runPolls(initialRendered, polls, opts) {
+ let rendered = initialRendered;
+ let oobPolls = 0;
+ const actions = [];
+ for (const { distance, listed = true } of polls) {
+ const action = pinBandAction({ distance, rendered, listed, oobPolls }, opts);
+ actions.push(action);
+ if (action === 'spawn') { rendered = true; oobPolls = 0; }
+ else if (action === 'keep') { oobPolls = 0; }
+ else if (action === 'wait') { oobPolls += 1; }
+ else if (action === 'drop') { rendered = false; oobPolls = 0; }
+ // 'ignore' leaves an unrendered pin unrendered
+ }
+ return { actions, disposed: actions.includes('drop') };
+}
+
+describe('band constants', () => {
+ it('exit is strictly beyond enter so the band has width to absorb jitter', () => {
+ expect(EXIT_RADIUS_M).toBeGreaterThan(ENTER_RADIUS_M);
+ // The 15 m band must clear ±10 m noise at the 40 m edge without touching exit.
+ expect(EXIT_RADIUS_M - ENTER_RADIUS_M).toBeGreaterThanOrEqual(10);
+ });
+ it('drop takes more than one poll (debounce is real)', () => {
+ expect(DROP_POLLS).toBeGreaterThanOrEqual(2);
+ });
+});
+
+describe('enter gate (discovery)', () => {
+ it('spawns an unrendered, listed pin once within the enter radius', () => {
+ expect(pinBandAction({ distance: 39, rendered: false, listed: true })).toBe('spawn');
+ expect(pinBandAction({ distance: ENTER_RADIUS_M, rendered: false, listed: true })).toBe('spawn');
+ });
+ it('ignores an unrendered pin still outside the enter radius — no drift-in discovery', () => {
+ expect(pinBandAction({ distance: 41, rendered: false, listed: true })).toBe('ignore');
+ // A pin sitting in the 40–55 m hysteresis band is never DISCOVERED there; you
+ // only enter it by getting within 40 m, then it's held out to exit.
+ expect(pinBandAction({ distance: 50, rendered: false, listed: true })).toBe('ignore');
+ });
+ it('never spawns from a pin the server did not return', () => {
+ expect(pinBandAction({ distance: 10, rendered: false, listed: false })).toBe('ignore');
+ });
+});
+
+describe('keep band (rendered, in-band)', () => {
+ it('keeps a rendered pin anywhere inside the exit radius', () => {
+ expect(pinBandAction({ distance: 5, rendered: true, listed: true })).toBe('keep');
+ expect(pinBandAction({ distance: 45, rendered: true, listed: true })).toBe('keep');
+ expect(pinBandAction({ distance: EXIT_RADIUS_M, rendered: true, listed: true })).toBe('keep');
+ });
+ it('keeping resets the out-of-band debounce', () => {
+ // One bad poll (out-of-band) then back in-band must clear the counter so a later
+ // single bad poll can never accumulate into a drop.
+ const { actions, disposed } = runPolls(true, [
+ { distance: 58 }, // out → wait (oob 0→1)
+ { distance: 50 }, // back in → keep (oob reset)
+ { distance: 58 }, // out → wait (oob 0→1 again, NOT 2)
+ { distance: 50 }, // back in → keep
+ ]);
+ expect(actions).toEqual(['wait', 'keep', 'wait', 'keep']);
+ expect(disposed).toBe(false);
+ });
+});
+
+describe('±10 m GPS jitter at the boundary — the headline bug', () => {
+ it('a pin held at ~40 m with ±10 m noise never disposes/respawns', () => {
+ // 12 polls of a pin physically at 40 m, GPS noise pushing the client distance
+ // across 30–50 m. It is always listed (server read radius is the 60 m cap) and
+ // always inside the 55 m exit, so every poll is 'keep' — zero churn.
+ const noisy = [40, 50, 31, 47, 38, 49, 30, 45, 42, 50, 33, 48]
+ .map(distance => ({ distance, listed: true }));
+ const { actions, disposed } = runPolls(true, noisy);
+ expect(disposed).toBe(false);
+ expect(actions.every(a => a === 'keep')).toBe(true);
+ });
+
+ it('a brief one-poll excursion past exit does not evict', () => {
+ // Standing right at the edge, a single noisy fix briefly reads 57 m, then settles.
+ const { disposed } = runPolls(true, [
+ { distance: 52 }, { distance: 57 }, { distance: 51 }, { distance: 49 },
+ ]);
+ expect(disposed).toBe(false);
+ });
+});
+
+describe('debounced exit (genuine departure)', () => {
+ it('requires DROP_POLLS sustained out-of-band polls before dropping', () => {
+ // Walk away: client distance climbs past exit and stays there.
+ const { actions } = runPolls(true, [
+ { distance: 58 }, // wait (oob → 1)
+ { distance: 62 }, // drop (oob 1, +1 ≥ DROP_POLLS=2)
+ ]);
+ expect(actions).toEqual(['wait', 'drop']);
+ });
+
+ it('drops a deleted pin even at point-blank range (server stops listing it)', () => {
+ // Owner deletes / hides the agent: distance is tiny but the server no longer
+ // returns it, so it is out-of-band by membership, not distance — and clears.
+ const { actions, disposed } = runPolls(true, [
+ { distance: 4, listed: false }, // wait
+ { distance: 4, listed: false }, // drop
+ ]);
+ expect(actions).toEqual(['wait', 'drop']);
+ expect(disposed).toBe(true);
+ });
+
+ it('drops a pin that walked far past the server cap', () => {
+ const { disposed } = runPolls(true, [
+ { distance: 80, listed: false },
+ { distance: 90, listed: false },
+ ]);
+ expect(disposed).toBe(true);
+ });
+});
+
+describe('options override the band', () => {
+ it('honours custom enter/exit/dropPolls thresholds', () => {
+ const opts = { enter: 20, exit: 30, dropPolls: 3 };
+ expect(pinBandAction({ distance: 25, rendered: false, listed: true }, opts)).toBe('ignore');
+ expect(pinBandAction({ distance: 18, rendered: false, listed: true }, opts)).toBe('spawn');
+ expect(pinBandAction({ distance: 28, rendered: true, listed: true }, opts)).toBe('keep');
+ // Needs three sustained out-of-band polls now, not two.
+ const { actions } = runPolls(true, [
+ { distance: 35 }, { distance: 35 }, { distance: 35 },
+ ], opts);
+ expect(actions).toEqual(['wait', 'wait', 'drop']);
+ });
+});
diff --git a/tests/irl-room-session.test.js b/tests/irl-room-session.test.js
new file mode 100644
index 000000000..4893c38b1
--- /dev/null
+++ b/tests/irl-room-session.test.js
@@ -0,0 +1,110 @@
+// Room authoring session logic (src/irl/room-session.js).
+//
+// Pins the contract the R1 placement UI rides on: a room is established with the
+// right origin + frame, an aim (heading + distance) becomes a valid room-aware
+// POST body whose geometry agrees with room-anchor.js, and persisted rooms
+// revive only when every field is sound. Pure — no DOM, no network, no clock.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ ROOM_ID_RE,
+ makeRoomId,
+ establishRoom,
+ clampDistance,
+ roomPlacement,
+ serializeRoom,
+ reviveRoom,
+ DIST_DEFAULT_M,
+} from '../src/irl/room-session.js';
+import { agentWorldPosition, roomOriginWorld } from '../src/irl/room-anchor.js';
+
+const ORIGIN = { lat: 37.7749, lng: -122.4194 };
+const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;
+
+describe('makeRoomId', () => {
+ it('always produces an API-valid slug', () => {
+ for (const [loc, rand] of [['9q8yyk', 'a1b2c3'], ['Living Room!', 'XYZ'], ['', ''], ['很长', '###']]) {
+ expect(ROOM_ID_RE.test(makeRoomId(loc, rand))).toBe(true);
+ }
+ });
+ it('is stable for the same inputs and differs by rand', () => {
+ expect(makeRoomId('9q8yyk', 'aaa')).toBe(makeRoomId('9q8yyk', 'aaa'));
+ expect(makeRoomId('9q8yyk', 'aaa')).not.toBe(makeRoomId('9q8yyk', 'bbb'));
+ });
+});
+
+describe('establishRoom', () => {
+ it('uses a true-north frame when an absolute compass is available', () => {
+ const r = establishRoom({ ...ORIGIN, headingDeg: 137, hasAbsoluteCompass: true, locationKey: '9q8', rand: 'a1' });
+ expect(r.originYawDeg).toBe(0);
+ expect(r.absolute).toBe(true);
+ expect(r.originLat).toBe(ORIGIN.lat);
+ expect(ROOM_ID_RE.test(r.id)).toBe(true);
+ });
+ it('pins the frame to the current heading when only relative orientation exists', () => {
+ const r = establishRoom({ ...ORIGIN, headingDeg: 137, hasAbsoluteCompass: false, locationKey: '9q8', rand: 'a1' });
+ expect(r.originYawDeg).toBe(137);
+ expect(r.absolute).toBe(false);
+ });
+ it('throws without a GPS fix rather than planting a room at 0,0', () => {
+ expect(() => establishRoom({ lat: NaN, lng: NaN, locationKey: 'x', rand: 'y' })).toThrow();
+ });
+});
+
+describe('clampDistance', () => {
+ it('clamps to the slider range and defaults garbage', () => {
+ expect(clampDistance(0.1)).toBe(0.5);
+ expect(clampDistance(99)).toBe(8);
+ expect(clampDistance(2.5)).toBe(2.5);
+ expect(clampDistance('nope')).toBe(DIST_DEFAULT_M);
+ });
+});
+
+describe('roomPlacement', () => {
+ const room = establishRoom({ ...ORIGIN, hasAbsoluteCompass: true, locationKey: '9q8', rand: 'a1' });
+
+ it('produces a valid POST room block whose world position matches room-anchor', () => {
+ // Placer stands on the origin, aims due east (90°) at 3 m → couch to the right.
+ const body = roomPlacement({ room, viewerLat: ORIGIN.lat, viewerLng: ORIGIN.lng, bearingDeg: 90, distM: 3 });
+ expect(body.room.id).toBe(room.id);
+ expect(near(body.room.relEast, 3, 1e-6)).toBe(true);
+ expect(near(body.room.relNorth, 0, 1e-6)).toBe(true);
+ // The agent faces the placer (placed pointing east → faces west).
+ expect(body.heading).toBe(270);
+ // Re-projecting the stored block lands it to the right (+X) on the floor.
+ const originWorld = roomOriginWorld(ORIGIN.lat, ORIGIN.lng, room.originLat, room.originLng);
+ const w = agentWorldPosition({ originWorld, relEast: body.room.relEast, relNorth: body.room.relNorth });
+ expect(w.x).toBeGreaterThan(2.9);
+ expect(near(w.z, 0, 1e-6)).toBe(true);
+ });
+
+ it('folds in the placer walking away from the origin', () => {
+ // Placer has moved ~2 m north of the origin, then drops an agent 1 m east.
+ const moved = { lat: ORIGIN.lat + 2 / 110540, lng: ORIGIN.lng };
+ const body = roomPlacement({ room, viewerLat: moved.lat, viewerLng: moved.lng, bearingDeg: 90, distM: 1 });
+ expect(near(body.room.relEast, 1, 1e-3)).toBe(true); // 1 m east of origin
+ expect(near(body.room.relNorth, 2, 1e-2)).toBe(true); // + the 2 m they walked north
+ });
+
+ it('clamps distance and rejects an invalid room', () => {
+ const body = roomPlacement({ room, viewerLat: ORIGIN.lat, viewerLng: ORIGIN.lng, bearingDeg: 0, distM: 999 });
+ expect(near(body.room.relNorth, 8, 1e-6)).toBe(true); // clamped to DIST_MAX_M
+ expect(() => roomPlacement({ room: { id: 'Bad Id!' }, viewerLat: 0, viewerLng: 0, bearingDeg: 0, distM: 1 })).toThrow();
+ });
+});
+
+describe('serialize / revive round-trip', () => {
+ it('revives a sound room and rejects malformed ones', () => {
+ const r = establishRoom({ ...ORIGIN, hasAbsoluteCompass: false, headingDeg: 42, locationKey: '9q8', rand: 'a1', now: 1000 });
+ const back = reviveRoom(serializeRoom(r));
+ expect(back.id).toBe(r.id);
+ expect(back.originLat).toBe(ORIGIN.lat);
+ expect(back.originYawDeg).toBe(42);
+ expect(back.absolute).toBe(false);
+ // Garbage / null-island / bad-id all reject to null.
+ expect(reviveRoom('not json')).toBeNull();
+ expect(reviveRoom(JSON.stringify({ id: 'ok', originLat: 0, originLng: 0 }))).toBeNull();
+ expect(reviveRoom(JSON.stringify({ id: 'Bad Id', originLat: 1, originLng: 1 }))).toBeNull();
+ });
+});
diff --git a/tests/irl-sensor-robustness.test.js b/tests/irl-sensor-robustness.test.js
new file mode 100644
index 000000000..e982f56be
--- /dev/null
+++ b/tests/irl-sensor-robustness.test.js
@@ -0,0 +1,177 @@
+// Sensor-fusion robustness for the /irl world-lock camera (src/irl/sensor-fusion.js).
+//
+// The contract these tests pin is the single most important AR reliability surface:
+// no device-orientation reading — null, NaN, uncalibrated, or a 359°→1° compass
+// wrap — may ever reach `cameraYaw`/`cameraPitch` in a form that snaps, spins,
+// freezes, or vanishes the avatar. Pure math, no DOM / Three.js / sensors / clock.
+
+import { describe, it, expect } from 'vitest';
+
+import {
+ COMPASS_STALE_MS,
+ shortestAngleLerp,
+ isFiniteReading,
+ isCompassFresh,
+ shouldUseAbsoluteYaw,
+ resolveLockYaw,
+ clampPitch,
+} from '../src/irl/sensor-fusion.js';
+
+const DEG = Math.PI / 180;
+const PITCH_MIN = -0.5;
+const PITCH_MAX = 0.65;
+
+describe('isFiniteReading', () => {
+ it('accepts two finite Euler angles', () => {
+ expect(isFiniteReading(120, 45)).toBe(true);
+ expect(isFiniteReading(0, 0)).toBe(true);
+ expect(isFiniteReading(-359.9, -90)).toBe(true);
+ });
+
+ it('rejects null / undefined (the old `?? 0` only caught these)', () => {
+ expect(isFiniteReading(null, 45)).toBe(false);
+ expect(isFiniteReading(120, undefined)).toBe(false);
+ expect(isFiniteReading(undefined, undefined)).toBe(false);
+ });
+
+ it('rejects NaN and ±Infinity (the bug the old guard let through)', () => {
+ expect(isFiniteReading(NaN, 45)).toBe(false);
+ expect(isFiniteReading(120, NaN)).toBe(false);
+ expect(isFiniteReading(Infinity, 45)).toBe(false);
+ expect(isFiniteReading(120, -Infinity)).toBe(false);
+ });
+});
+
+describe('isCompassFresh', () => {
+ it('is fresh inside the staleness window', () => {
+ const now = 10_000;
+ expect(isCompassFresh(now - 100, now)).toBe(true);
+ expect(isCompassFresh(now - COMPASS_STALE_MS + 1, now)).toBe(true);
+ });
+
+ it('goes stale past the window (a dead magnetometer keeps its last heading)', () => {
+ const now = 10_000;
+ expect(isCompassFresh(now - COMPASS_STALE_MS - 1, now)).toBe(false);
+ expect(isCompassFresh(now - 60_000, now)).toBe(false);
+ });
+
+ it('is never fresh before the first sample (lastGoodAt = 0 / non-finite)', () => {
+ // The sentinel is 0; with a real monotonic clock `now` is far larger, so the
+ // gap exceeds the window and the absolute path is correctly skipped at boot.
+ expect(isCompassFresh(0, 50_000)).toBe(false);
+ expect(isCompassFresh(NaN, 50_000)).toBe(false);
+ });
+
+ it('honors a custom staleness budget', () => {
+ expect(isCompassFresh(900, 1000, 50)).toBe(false);
+ expect(isCompassFresh(960, 1000, 50)).toBe(true);
+ });
+});
+
+describe('shouldUseAbsoluteYaw', () => {
+ it('requires GPS anchor AND a fresh, present compass', () => {
+ expect(shouldUseAbsoluteYaw({ gpsModeActive: true, compassHeading: 90, compassFresh: true })).toBe(true);
+ });
+
+ it('stays relative without a GPS world-anchor (avatar would jump off-frame)', () => {
+ expect(shouldUseAbsoluteYaw({ gpsModeActive: false, compassHeading: 90, compassFresh: true })).toBe(false);
+ });
+
+ it('stays relative with no compass or a stale one', () => {
+ expect(shouldUseAbsoluteYaw({ gpsModeActive: true, compassHeading: null, compassFresh: true })).toBe(false);
+ expect(shouldUseAbsoluteYaw({ gpsModeActive: true, compassHeading: undefined, compassFresh: true })).toBe(false);
+ expect(shouldUseAbsoluteYaw({ gpsModeActive: true, compassHeading: 90, compassFresh: false })).toBe(false);
+ });
+
+ it('treats heading 0 (due north) as a real bearing, not absent', () => {
+ expect(shouldUseAbsoluteYaw({ gpsModeActive: true, compassHeading: 0, compassFresh: true })).toBe(true);
+ });
+});
+
+describe('shortestAngleLerp', () => {
+ it('moves along the shortest arc across the π/−π seam', () => {
+ // from just under +π to just over −π is a tiny step, not a ~2π sweep.
+ const from = Math.PI - 0.05;
+ const to = -Math.PI + 0.05;
+ const out = shortestAngleLerp(from, to, 0.5);
+ expect(Math.abs(out - from)).toBeLessThan(0.06);
+ });
+
+ it('eases a fraction of the way at t<1 and lands exactly at t=1', () => {
+ expect(shortestAngleLerp(0, 1, 0)).toBeCloseTo(0, 10);
+ expect(shortestAngleLerp(0, 1, 1)).toBeCloseTo(1, 10);
+ expect(shortestAngleLerp(0, 1, 0.5)).toBeCloseTo(0.5, 10);
+ });
+});
+
+describe('resolveLockYaw — relative path', () => {
+ const base = { useAbsolute: false, prevYaw: 0, baseAlpha: 10, baseYaw: 0, compassHeading: null };
+
+ it('integrates alpha deltas from the lock baseline', () => {
+ const out = resolveLockYaw({ ...base, alpha: 40 }); // +30° from baseline
+ expect(out).toBeCloseTo(30 * DEG, 9);
+ });
+
+ it('wraps the alpha delta across the 0/360 boundary (no 340° jump)', () => {
+ // baseline 10°, reading 350° is a 20° turn the OTHER way, not +340°.
+ const out = resolveLockYaw({ ...base, alpha: 350 });
+ expect(out).toBeCloseTo(-20 * DEG, 9);
+ });
+
+ it('is finite for every in-range input', () => {
+ for (let alpha = 0; alpha < 360; alpha += 23) {
+ expect(Number.isFinite(resolveLockYaw({ ...base, alpha }))).toBe(true);
+ }
+ });
+});
+
+describe('resolveLockYaw — absolute path (the 359°→1° spin guard)', () => {
+ const compassToYaw = (deg) => -deg * DEG;
+
+ it('crossing 359°→1° is a small step, never a ~360° spin', () => {
+ const prevYaw = compassToYaw(359);
+ const out = resolveLockYaw({
+ useAbsolute: true, prevYaw, alpha: 0, baseAlpha: 0, baseYaw: 0,
+ compassHeading: 1, absoluteSmooth: 0.4,
+ });
+ // The real heading moved 2°; the yaw step must be a fraction of that, not 2π.
+ expect(Math.abs(out - prevYaw)).toBeLessThan(0.1);
+ expect(Math.abs(out - prevYaw)).toBeGreaterThan(0);
+ });
+
+ it('converges onto the target bearing (mod 2π) over repeated frames', () => {
+ let yaw = compassToYaw(350);
+ for (let i = 0; i < 40; i++) {
+ yaw = resolveLockYaw({
+ useAbsolute: true, prevYaw: yaw, alpha: 0, baseAlpha: 0, baseYaw: 0,
+ compassHeading: 5, absoluteSmooth: 0.4,
+ });
+ }
+ // Compare orientations modulo 2π: sin/cos must match the target bearing.
+ const target = compassToYaw(5);
+ expect(Math.sin(yaw)).toBeCloseTo(Math.sin(target), 4);
+ expect(Math.cos(yaw)).toBeCloseTo(Math.cos(target), 4);
+ });
+
+ it('a hard assignment (smooth=1) lands exactly on the bearing', () => {
+ const out = resolveLockYaw({
+ useAbsolute: true, prevYaw: 1.23, alpha: 0, baseAlpha: 0, baseYaw: 0,
+ compassHeading: 90, absoluteSmooth: 1,
+ });
+ expect(out).toBeCloseTo(compassToYaw(90), 9);
+ });
+});
+
+describe('clampPitch', () => {
+ it('clamps into [min, max]', () => {
+ expect(clampPitch(2, PITCH_MIN, PITCH_MAX)).toBe(PITCH_MAX);
+ expect(clampPitch(-2, PITCH_MIN, PITCH_MAX)).toBe(PITCH_MIN);
+ expect(clampPitch(0.3, PITCH_MIN, PITCH_MAX)).toBe(0.3);
+ });
+
+ it('collapses a non-finite pitch to a safe in-range 0 (never NaN)', () => {
+ expect(clampPitch(NaN, PITCH_MIN, PITCH_MAX)).toBe(0);
+ expect(clampPitch(Infinity, PITCH_MIN, PITCH_MAX)).toBe(0);
+ expect(Number.isFinite(clampPitch(NaN, PITCH_MIN, PITCH_MAX))).toBe(true);
+ });
+});