Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
IRL: room ghost mode, launch readiness, next-gen trading task specs
nirholas466ce4f20a18
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6d04cb79b..659801005 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -26,10 +26,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **IRL teaches you how to find agents — and an empty area now feels alive** — IRL has no map and no list on purpose: you find agents by walking up to them and looking through your camera. The first time you open it, a short card now explains that idea — agents are hidden in the world around you, dropping your own lets someone else stumble on it later, and we never show a roster of where agents are, not even to you. You can reopen that explainer any time from the small "?" in the corner. And when you're somewhere quiet with nobody pinned yet, instead of a blank screen you'll see a gentle "Look around 👀 · or be the first to pin here" prompt with a one-tap way to place your own agent — so an empty spot reads as "keep exploring," not "this is broken." The moment a real agent comes into range, the prompt fades away on its own. (`/irl`) `[improvement]`- **One API, many services: the three.ws API gateway** — We bundled a stack of popular third-party APIs behind a single three.ws API so you can reach them all with one integration, one key, and one bill. The first providers are live at /api/v1/x — CoinGecko (live prices and ranked market data), DefiLlama (protocol TVL across all of DeFi), and any OpenAI-compatible LLM — with more landing over the coming releases. Discover everything with one call to GET /api/v1, which returns the full catalog: every provider, endpoint, parameter, and price. You can pay three ways, your choice per call: bring your own upstream key (we just route it, no markup), use a three.ws API key on your plan, or pay-per-call in USDC with no account at all. Every response uses one consistent shape with standard rate-limit headers, and the platform's own capabilities — text sentiment, market and narrative intelligence, and verified agent-card lookups — live under the same /api/v1 surface. `[feature, sdk]`- **Paid market-intel never charges you for unavailable data** — The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal. `[fix]`+- **Pinning your agent holds up when GPS gets flaky** — Anchoring an agent to a real spot now survives the rough edges of phone GPS. If your location drops for a moment — stepping indoors, into a garage, under heavy cover — IRL quietly re-acquires it on its own instead of going dark until you reload. When you pin before your phone has its first fix, it waits on a clear "Getting your location…" note and only drops the agent once a real position lands, so an agent can never be saved at the wrong place. The moment that precise fix arrives, your agent eases into its anchored spot instead of jumping. And when GPS is only roughly sure where you are, we say so — your pin is labelled an approximate spot with the accuracy in metres rather than pretending it's pinpoint. (`/irl`) `[fix]`+- **Place AI agents at fixed spots around a real room** — IRL has a new way to author a scene: stand where you are, aim your phone at a real spot — the couch, the doorway, the empty chair across the table — set how far away it should sit, and tap Place to drop an agent right there. Drop several around you and each one stays locked to its real-world spot: turn away and it's gone, turn back and it slides into frame exactly where you left it, and the wall you never aimed at stays empty. The whole group is anchored as one shared room, so the layout holds its shape no matter how your GPS drifts — agents you placed metres apart stay metres apart on the right sides — and the next person who opens IRL at that spot sees the same arrangement you built. If the room ever lands slightly off, one drag nudges the entire cluster onto its true spot at once instead of fixing each agent by hand. Every part of the flow works by keyboard and reads its state aloud, and when your compass isn't calibrated we tell you honestly that others may see the room rotated rather than pretending it's perfect. (`/irl`) `[feature]`- **Platform-wide API security hardening** — We completed a full security audit of the API and tightened it across the board. Server errors no longer echo internal details back to callers — they return a short reference code you can quote to support, while the real diagnostics stay server-side (this also closes a path where a backend service key could surface in an error message). Account-changing actions made from the website — updating preferences, managing webhooks and payout wallets, marking notifications read, scheduling posts, setting skill prices — now carry cross-site request-forgery protection, so a malicious page can't act on your behalf. Sign-in, wallet-linking, GitHub connect and sensitive admin actions gained rate limits, and image-analysis requests are now screened so a supplied URL can't be used to probe internal systems. API access via developer keys is unaffected. `[security]`- **Premium avatar cosmetics are now buyable right in the character creator** — Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog. (`/create`) `[feature, fix]`- **See your net take when you price a skill** — The Skill Pricing panel on the Monetize dashboard now shows exactly what you keep on every payment. As you type a per-call price, a line below the field updates live — "You receive $X.XX after 2.5% fee" — so the platform's cut is never a surprise at payout time. The same net figure appears in the Add Pricing dialog, and the panel header states the current platform fee rate, which is read from the live billing config rather than hardcoded. (`/dashboard/monetize`) `[feature, improvement]`- **Shared agent links now unfurl with the agent's own avatar** — When you paste a link to an agent on X, Discord, Slack, Telegram or iMessage, the preview card now shows that agent's actual avatar, name and description instead of a generic three.ws image — so every shared link is visual proof of the collectible. Bots that don't run JavaScript get the right image and text rendered on the server, and agents without an avatar yet fall back to a clean branded card with their initial. We also fixed the canonical and share URLs on agent pages to point at the real /agents/<id> address. `[feature, improvement]`+- **Smoother switch between camera AR and Place on floor** — On phones that can anchor an agent to your real floor, flipping between plain Camera AR and the Place on floor flow is now seamless. Before, tapping the two in quick succession could fight over the camera and leave you on a black screen with the camera light stuck on; now each switch waits for the previous one to finish releasing the camera, so it never double-grabs it. Leaving a floor session drops you straight back into the live camera view you came from — passthrough resumes instantly instead of flashing a dark frame — and taps on the screen behind the floor-anchor panel no longer slip through to open the wrong thing. If a floor session can't start, the scene keeps running and you get the calm "use Pin here instead" card rather than a frozen view. (`/irl`) `[fix]`- **Tapping an agent in AR now lands every time** — Inspecting an agent in IRL AR is a tap — and we made that tap far harder to miss. There's now a finger-sized catch zone around each agent's floating name, so a tap that lands just beside a small or distant agent still opens its card instead of doing nothing. When several agents overlap on screen, your tap resolves to the one in front of you, and it never selects an agent that's behind you or off-screen. We also kept agents from vanishing when you bring your phone right up to one to look closely. Inspecting works whether the agent is centered, near the edge of the frame, close, or far. (`/irl`) `[improvement]`- **Token Oracle follow / unfollow is working again** — Subscribing an agent to a token's oracle alerts — and unsubscribing — was silently failing for everyone; only the status check worked. Both now go through correctly, so you can opt an agent into (and out of) score-based alerts as intended. `[fix]`- **Unity & Unreal avatar loading documented with code that actually works** — The developer hub's Unity and Unreal cards used to show sample code for an SDK that doesn't exist yet. They now show the real, working way to load a three.ws avatar today — your avatar's GLB endpoint loaded at runtime with glTFast (Unity) or glTFRuntime (Unreal), both standard glTF importers — alongside an honest note that a native package is still on the roadmap. (`/dashboard/developers`) `[docs, improvement]`diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 65c7a04bc..996a69e45 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -502,7 +502,7 @@ async function handleCalibrate(res, { id, session, body, deviceToken = null }) {const [pin] = await sql`SELECT id, user_id, device_token, lat, lng, heading, anchor_yaw_deg, anchor_height_m,- expires_at, hidden_at+ room_id, rel_east_m, rel_north_m, expires_at, hidden_atFROM irl_pinsWHERE id = ${id}`;@@ -551,6 +551,24 @@ async function handleCalibrate(res, { id, session, body, deviceToken = null }) {}}+ // New room-frame offset — optional; only meaningful for a room pin, where the+ // render path (pinWorldPos) resolves position from rel_east_m/rel_north_m, NOT the+ // absolute lat/lng. A WebXR "refine on floor" re-places one agent by sending its+ // fresh offset; without persisting it the sharpened spot would snap back on the+ // next viewer re-fetch. Bounded by the SAME ground-move ceiling against the stored+ // offset, so refine sharpens a placement and never slides it across the room. A+ // non-room pin (no room_id) ignores rel — its absolute lat/lng above is authoritative.+ let newRelEast = null, newRelNorth = null;+ if (pin.room_id && Number.isFinite(cal.relEast) && Number.isFinite(cal.relNorth)) {+ const baseE = Number.isFinite(pin.rel_east_m) ? pin.rel_east_m : 0;+ const baseN = Number.isFinite(pin.rel_north_m) ? pin.rel_north_m : 0;+ if (Math.hypot(cal.relEast - baseE, cal.relNorth - baseN) > CAL_MAX_MOVE_M) {+ return json(res, 422, { error: 'calibration move too large', max_m: CAL_MAX_MOVE_M });+ }+ newRelEast = Math.max(-REL_MAX_M, Math.min(REL_MAX_M, cal.relEast));+ newRelNorth = Math.max(-REL_MAX_M, Math.min(REL_MAX_M, cal.relNorth));+ }+// Persist. heading stays in sync with anchor_yaw_deg so legacy clients (which// only read `heading`) still render the corrected bearing.const headingToStore = newYaw != null ? Math.round(newYaw) : null;@@ -568,11 +586,14 @@ async function handleCalibrate(res, { id, session, body, deviceToken = null }) {anchor_yaw_deg = COALESCE(${newYaw}, anchor_yaw_deg),heading = COALESCE(${headingToStore}, heading),anchor_height_m = COALESCE(${newHeight}, anchor_height_m),+ rel_east_m = COALESCE(${newRelEast}, rel_east_m),+ rel_north_m = COALESCE(${newRelNorth}, rel_north_m),anchor_quat = CASE WHEN ${clearQuat} THEN NULL ELSE anchor_quat ENDWHERE id = ${id}AND hidden_at IS NULLAND (expires_at IS NULL OR expires_at > NOW())- RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, anchor_quat, gps_accuracy_m+ RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m,+ rel_east_m, rel_north_m, anchor_quat, gps_accuracy_m`;// A lapse between the SELECT above and this write (e.g. expiry / a reaping cron)// leaves no row — surface that as not-found instead of returning { pin: null }.diff --git a/data/changelog.json b/data/changelog.jsonindex 278a04ee7..feed09db9 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,33 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-19",+ "title": "Pinning your agent holds up when GPS gets flaky",+ "summary": "Anchoring an agent to a real spot now survives the rough edges of phone GPS. If your location drops for a moment — stepping indoors, into a garage, under heavy cover — IRL quietly re-acquires it on its own instead of going dark until you reload. When you pin before your phone has its first fix, it waits on a clear \"Getting your location…\" note and only drops the agent once a real position lands, so an agent can never be saved at the wrong place. The moment that precise fix arrives, your agent eases into its anchored spot instead of jumping. And when GPS is only roughly sure where you are, we say so — your pin is labelled an approximate spot with the accuracy in metres rather than pretending it's pinpoint.",+ "tags": [+ "fix"+ ],+ "link": "/irl"+ },+ {+ "date": "2026-06-19",+ "title": "Smoother switch between camera AR and Place on floor",+ "summary": "On phones that can anchor an agent to your real floor, flipping between plain Camera AR and the Place on floor flow is now seamless. Before, tapping the two in quick succession could fight over the camera and leave you on a black screen with the camera light stuck on; now each switch waits for the previous one to finish releasing the camera, so it never double-grabs it. Leaving a floor session drops you straight back into the live camera view you came from — passthrough resumes instantly instead of flashing a dark frame — and taps on the screen behind the floor-anchor panel no longer slip through to open the wrong thing. If a floor session can't start, the scene keeps running and you get the calm \"use Pin here instead\" card rather than a frozen view.",+ "tags": [+ "fix"+ ],+ "link": "/irl"+ },+ {+ "date": "2026-06-19",+ "title": "Place AI agents at fixed spots around a real room",+ "summary": "IRL has a new way to author a scene: stand where you are, aim your phone at a real spot — the couch, the doorway, the empty chair across the table — set how far away it should sit, and tap Place to drop an agent right there. Drop several around you and each one stays locked to its real-world spot: turn away and it's gone, turn back and it slides into frame exactly where you left it, and the wall you never aimed at stays empty. The whole group is anchored as one shared room, so the layout holds its shape no matter how your GPS drifts — agents you placed metres apart stay metres apart on the right sides — and the next person who opens IRL at that spot sees the same arrangement you built. If the room ever lands slightly off, one drag nudges the entire cluster onto its true spot at once instead of fixing each agent by hand. Every part of the flow works by keyboard and reads its state aloud, and when your compass isn't calibrated we tell you honestly that others may see the room rotated rather than pretending it's perfect.",+ "tags": [+ "feature"+ ],+ "link": "/irl"+ },{"date": "2026-06-19","title": "IRL is fully keyboard- and screen-reader-accessible",diff --git a/pages/irl.html b/pages/irl.htmlindex a187a1b3f..432fbef4c 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -2094,6 +2094,8 @@<div class="irl-sheet-actions"><button id="irl-sheet-pay" class="irl-sheet-btn irl-sheet-btn-primary" type="button" hidden>Pay via x402</button><button id="irl-sheet-calibrate" class="irl-sheet-btn" type="button" hidden>Calibrate position</button>+ <button id="irl-sheet-align-room" class="irl-sheet-btn" type="button" hidden>Align this room</button>+ <button id="irl-sheet-refine" class="irl-sheet-btn" type="button" hidden>Refine on floor</button><button id="irl-sheet-view" class="irl-sheet-btn" type="button">View profile</button></div><!-- Leave a message — POSTs an interaction the owner sees in their dashboard feed -->@@ -2190,6 +2192,35 @@/* Honest accuracy line inside the inspect sheet (A3). */.irl-sheet-accuracy { margin: 0 0 12px; font-size: 12px; line-height: 1.5; color: #8a94a6; }.irl-sheet-accuracy.is-low { color: #fbbf73; }+ /* Room align (R2) reuses the calibrate panel; a whole-room slide/twist has no+ per-agent floor-height step, so hide it and show the room-scale hint instead. */+ body.is-room-cal #irl-calibrate-panel .irl-cal-height { display: none; }+ body.is-room-cal #irl-calibrate-panel .irl-cal-hint::after {+ content: ' The whole cluster moves together — its internal layout stays exact.';+ color: #7c8aa0;+ }+ /* Relative-frame one-tap alignment prompt (R2) — a room placed without a compass+ may render rotated for another viewer; this offers a single corrective tap. */+ #irl-room-align-prompt {+ position: fixed; left: 50%; bottom: calc(96px + env(safe-area-inset-bottom, 0px));+ transform: translate(-50%, 12px); z-index: 58; width: min(420px, calc(100vw - 28px));+ background: rgba(12,14,21,0.96); border: 1px solid rgba(124,92,255,0.45);+ border-radius: 14px; box-shadow: 0 12px 40px rgba(0,0,0,0.5);+ padding: 13px 15px; opacity: 0; pointer-events: none;+ transition: opacity .22s ease, transform .22s ease;+ }+ #irl-room-align-prompt.is-shown { opacity: 1; pointer-events: auto; transform: translate(-50%, 0); }+ #irl-room-align-prompt p { margin: 0 0 10px; font-size: 12.5px; line-height: 1.5; color: #cdd6e4; }+ #irl-room-align-prompt .irl-ra-actions { display: flex; gap: 9px; }+ #irl-room-align-prompt button { flex: 1; padding: 10px 12px; border-radius: 11px; font: 600 13.5px inherit; cursor: pointer; transition: background .15s, border-color .15s; }+ #irl-room-align-prompt .irl-ra-align { border: 1px solid rgba(124,92,255,0.55); background: rgba(124,92,255,0.22); color: #d6cbff; }+ #irl-room-align-prompt .irl-ra-align:hover { background: rgba(124,92,255,0.34); }+ #irl-room-align-prompt .irl-ra-dismiss { border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.05); color: #aeb6c4; flex: 0 0 96px; }+ #irl-room-align-prompt .irl-ra-dismiss:hover { background: rgba(255,255,255,0.10); color: #fff; }+ #irl-room-align-prompt button:focus-visible { outline: 2px solid #9d7bff; outline-offset: 2px; }+ @media (prefers-reduced-motion: reduce) {+ #irl-room-align-prompt { transition: opacity .01s; }+ }</style><div id="irl-calibrate-panel" role="dialog" aria-modal="false" aria-label="Calibrate agent position"><div class="irl-sheet-handle" aria-hidden="true"></div>@@ -2212,6 +2243,15 @@</div></div><div id="irl-cal-denied" role="alertdialog" aria-modal="false" aria-label="Calibration locked" hidden></div>+<!-- R2 relative-frame one-tap alignment prompt — shown for a nearby room placed+ without an absolute compass that may render rotated for this viewer. -->+<div id="irl-room-align-prompt" role="dialog" aria-modal="false" aria-label="Align this room to your view" hidden>+ <p>This room was placed without a compass, so it may appear rotated. Face the room’s front and tap Align to match it to your view.</p>+ <div class="irl-ra-actions">+ <button type="button" class="irl-ra-align" data-ra-action="align">Align</button>+ <button type="button" class="irl-ra-dismiss" data-ra-action="dismiss">Dismiss</button>+ </div>+</div><!-- E1 first-run permission + onboarding overlay. Cards (prompt / granted /denied-with-recovery / unsupported) are rendered by src/irl/onboarding.js. -->diff --git a/public/changelog.json b/public/changelog.jsonindex b6c6b1eef..80871c15a 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T09:48:35.457Z",+ "generated_at": "2026-06-19T09:56:26.437Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -211,6 +211,26 @@"fix"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Pinning your agent holds up when GPS gets flaky",+ "summary": "Anchoring an agent to a real spot now survives the rough edges of phone GPS. If your location drops for a moment — stepping indoors, into a garage, under heavy cover — IRL quietly re-acquires it on its own instead of going dark until you reload. When you pin before your phone has its first fix, it waits on a clear \"Getting your location…\" note and only drops the agent once a real position lands, so an agent can never be saved at the wrong place. The moment that precise fix arrives, your agent eases into its anchored spot instead of jumping. And when GPS is only roughly sure where you are, we say so — your pin is labelled an approximate spot with the accuracy in metres rather than pretending it's pinpoint.",+ "link": "/irl",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Place AI agents at fixed spots around a real room",+ "summary": "IRL has a new way to author a scene: stand where you are, aim your phone at a real spot — the couch, the doorway, the empty chair across the table — set how far away it should sit, and tap Place to drop an agent right there. Drop several around you and each one stays locked to its real-world spot: turn away and it's gone, turn back and it slides into frame exactly where you left it, and the wall you never aimed at stays empty. The whole group is anchored as one shared room, so the layout holds its shape no matter how your GPS drifts — agents you placed metres apart stay metres apart on the right sides — and the next person who opens IRL at that spot sees the same arrangement you built. If the room ever lands slightly off, one drag nudges the entire cluster onto its true spot at once instead of fixing each agent by hand. Every part of the flow works by keyboard and reads its state aloud, and when your compass isn't calibrated we tell you honestly that others may see the room rotated rather than pretending it's perfect.",+ "link": "/irl",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","type": "update",@@ -254,6 +274,16 @@"improvement"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Smoother switch between camera AR and Place on floor",+ "summary": "On phones that can anchor an agent to your real floor, flipping between plain Camera AR and the Place on floor flow is now seamless. Before, tapping the two in quick succession could fight over the camera and leave you on a black screen with the camera light stuck on; now each switch waits for the previous one to finish releasing the camera, so it never double-grabs it. Leaving a floor session drops you straight back into the live camera view you came from — passthrough resumes instantly instead of flashing a dark frame — and taps on the screen behind the floor-anchor panel no longer slip through to open the wrong thing. If a floor session can't start, the scene keeps running and you get the calm \"use Pin here instead\" card rather than a frozen view.",+ "link": "/irl",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 664b74977..249880c81 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -166,6 +166,22 @@<category>fix</category><description>The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal.</description></item>+ <item>+ <title>Pinning your agent holds up when GPS gets flaky</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-19:Pinning your agent holds up when GPS gets flaky</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Anchoring an agent to a real spot now survives the rough edges of phone GPS. If your location drops for a moment — stepping indoors, into a garage, under heavy cover — IRL quietly re-acquires it on its own instead of going dark until you reload. When you pin before your phone has its first fix, it waits on a clear "Getting your location…" note and only drops the agent once a real position lands, so an agent can never be saved at the wrong place. The moment that precise fix arrives, your agent eases into its anchored spot instead of jumping. And when GPS is only roughly sure where you are, we say so — your pin is labelled an approximate spot with the accuracy in metres rather than pretending it's pinpoint.</description>+ </item>+ <item>+ <title>Place AI agents at fixed spots around a real room</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-19:Place AI agents at fixed spots around a real room</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>IRL has a new way to author a scene: stand where you are, aim your phone at a real spot — the couch, the doorway, the empty chair across the table — set how far away it should sit, and tap Place to drop an agent right there. Drop several around you and each one stays locked to its real-world spot: turn away and it's gone, turn back and it slides into frame exactly where you left it, and the wall you never aimed at stays empty. The whole group is anchored as one shared room, so the layout holds its shape no matter how your GPS drifts — agents you placed metres apart stay metres apart on the right sides — and the next person who opens IRL at that spot sees the same arrangement you built. If the room ever lands slightly off, one drag nudges the entire cluster onto its true spot at once instead of fixing each agent by hand. Every part of the flow works by keyboard and reads its state aloud, and when your compass isn't calibrated we tell you honestly that others may see the room rotated rather than pretending it's perfect.</description>+ </item><item><title>Platform-wide API security hardening</title><link>https://three.ws/changelog</link>@@ -198,6 +214,14 @@<category>feature</category><description>When you paste a link to an agent on X, Discord, Slack, Telegram or iMessage, the preview card now shows that agent's actual avatar, name and description instead of a generic three.ws image — so every shared link is visual proof of the collectible. Bots that don't run JavaScript get the right image and text rendered on the server, and agents without an avatar yet fall back to a clean branded card with their initial. We also fixed the canonical and share URLs on agent pages to point at the real /agents/<id> address.</description></item>+ <item>+ <title>Smoother switch between camera AR and Place on floor</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-19:Smoother switch between camera AR and Place on floor</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>On phones that can anchor an agent to your real floor, flipping between plain Camera AR and the Place on floor flow is now seamless. Before, tapping the two in quick succession could fight over the camera and leave you on a black screen with the camera light stuck on; now each switch waits for the previous one to finish releasing the camera, so it never double-grabs it. Leaving a floor session drops you straight back into the live camera view you came from — passthrough resumes instantly instead of flashing a dark frame — and taps on the screen behind the floor-anchor panel no longer slip through to open the wrong thing. If a floor session can't start, the scene keeps running and you get the calm "use Pin here instead" card rather than a frozen view.</description>+ </item><item><title>Tapping an agent in AR now lands every time</title><link>https://three.ws/irl</link>diff --git a/public/features.json b/public/features.jsonindex 98454b0e0..5fb87a851 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T09:48:35.312Z",+ "generated_at": "2026-06-19T09:56:26.345Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/irl.js b/src/irl.jsindex 512505773..b512253e1 100644--- a/src/irl.js+++ b/src/irl.js@@ -57,6 +57,7 @@ import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';import { roomOriginWorld, agentWorldPosition, localToGeo, calibrateRoomOrigin } from './irl/room-anchor.js';import { anchorPoseToPin, yawDegFromQuat } from './irl/floor-anchor.js';import { initRoomMode } from './irl/room-mode.js';+import { createRoomGhost } from './irl/room-ghost.js';import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch, screenPitchDeg } from './irl/sensor-fusion.js';import { deriveVerticalFovDeg, DEFAULT_DIAG_FOV_DEG } from './irl/camera-fov.js';import { pinBandAction } from './irl/proximity-band.js';@@ -660,9 +661,20 @@ const raycaster = new Raycaster();const pointerNDC = new Vector2();let tapDownX = 0, tapDownY = 0;-canvas.addEventListener('pointerdown', e => { tapDownX = e.clientX; tapDownY = e.clientY; armLongPress(e); });+canvas.addEventListener('pointerdown', e => {+ // The WebXR floor-anchor session (and its failed-start error card) layers a modal+ // overlay over the canvas; don't arm a long-press behind it.+ if (xrOverlay && !xrOverlay.hidden) return;+ tapDownX = e.clientX; tapDownY = e.clientY; armLongPress(e);+});canvas.addEventListener('pointerup', e => {cancelLongPress();+ // While the WebXR floor-anchor overlay is up, the immersive session owns taps —+ // its 'select' places the anchor — and on a failed start the error card is modal.+ // Either way the 2D pin/place raycast behind it must not also fire (dead taps,+ // stray sheets). The overlay is display:none whenever AR/gyro mode is active, so+ // this only gates during an actual XR session or its error state.+ if (xrOverlay && !xrOverlay.hidden) return;// While calibrating, taps belong to the nudge gesture — never re-open a sheet.if (calibrateActive) return;if (Math.hypot(e.clientX - tapDownX, e.clientY - tapDownY) > TAP_THRESHOLD) return;@@ -1737,11 +1749,18 @@ function onGPSPosition(pos) {// The agent being calibrated is driven by the nudge gesture this frame, not// by GPS — re-apply its working pose against the (possibly shifted) origin.if (calibrateActive && _cal && _cal.pin === p) { applyCalToGroup(); updatePinRing(p); continue; }+ // A room being aligned is driven by the room-cal gesture against a temporary+ // origin; skip the default reproject so it isn't double-corrected. The whole+ // cluster is re-applied once below so it still tracks the blended viewer origin.+ if (calibrateActive && _roomCal && _roomCal.pins.includes(p)) continue;const wp = pinWorldPos(p);p.group.position.set(wp.x, wp.y, wp.z);p.distance_m = Math.round(Math.hypot(wp.x, wp.z));updatePinRing(p);}+ // Re-apply the active room-cal cluster against the freshly blended origin so the+ // rig holds its real-world spot as the viewer's GPS settles mid-alignment.+ if (calibrateActive && _roomCal) applyRoomCalToGroups();// Re-anchor live presence ghosts against the shifted origin too, so a co-viewer's// orb holds its real-world bearing as the user walks (same treatment as pins).@@ -1950,23 +1969,63 @@ async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {// it renders world-locked at once via the room frame (pinWorldPos). Returns the// same { ok, id, message } shape the UI surfaces.async function placeRoomAgent(body) {+ const room = body?.room;+ if (!room || !room.id) return { ok: false, message: 'Could not anchor the room — try again.' };+ const heading = ((Math.round(body.heading) % 360) + 360) % 360;+ // Gyro placement has no measured floor depth and no surface quaternion: the agent+ // stands on the viewer's own ground plane (heightM 0) facing the compass heading.+ // 'gyro-gps' vs ':rel' carries the absolute-vs-page-relative bearing distinction A3+ // down-weights. The WebXR path (postRoomPin via persistFloorAnchor) supplies a+ // richer anchor — real floor height + surface quat + 'webxr' source.+ const anchor = {+ heightM: 0, yawDeg: heading,+ gpsAccuracyM: gpsState.accuracy, altitudeM: gpsState.altitude,+ source: body.absolute ? 'gyro-gps' : 'gyro-gps:rel',+ };+ return postRoomPin({+ lat: body.lat, lng: body.lng, heading,+ room: {+ id: room.id,+ originLat: room.originLat, originLng: room.originLng,+ originYawDeg: room.originYawDeg || 0,+ relEast: room.relEast, relNorth: room.relNorth,+ },+ anchor,+ });+}++// Shared POST for a room-anchored agent — the one network+spawn path behind both+// the gyro aim flow (R1, slider + compass) and the WebXR floor flow (R3, on-device+// hit-test). The caller hands the computed absolute lat/lng (the GPS index), the+// agent heading, the shared room block (origin + exact rel offset), and the A2+// anchor pose, whose `source` / `quat` / `heightM` ride straight through so a+// WebXR placement persists with centimetre precision while a gyro one degrades+// honestly. On success we spawn locally so the agent is world-locked at once via+// the shared frame (pinWorldPos), and bump the room badge through the room-mode API.+async function postRoomPin({ lat, lng, heading, room, anchor }) {try {- const room = body?.room;if (!room || !room.id) return { ok: false, message: 'Could not anchor the room — try again.' };- const heading = ((Math.round(body.heading) % 360) + 360) % 360;- const source = body.absolute ? 'gyro-gps' : 'gyro-gps:rel';+ const h = ((Math.round(heading) % 360) + 360) % 360;+ const quat = Array.isArray(anchor?.quat) && anchor.quat.length === 4 ? anchor.quat : null;const r = await fetch('/api/irl/pins', {method: 'POST',credentials: 'include',headers: deviceHeaders({ 'Content-Type': 'application/json' }),body: JSON.stringify({- lat: body.lat, lng: body.lng, heading,+ lat, lng, heading: h,caption: null,avatarUrl: resolveAvatarUrl(_currentAvatarId),avatarName: nameEl.textContent,deviceToken: _deviceToken,agentId: _currentAgentId || null,- anchor: { heightM: 0, yawDeg: heading, gpsAccuracyM: gpsState.accuracy, altitudeM: gpsState.altitude, source },+ anchor: {+ heightM: anchor?.heightM ?? 0,+ yawDeg: anchor?.yawDeg ?? h,+ quat,+ gpsAccuracyM: anchor?.gpsAccuracyM ?? gpsState.accuracy,+ altitudeM: anchor?.altitudeM ?? gpsState.altitude,+ source: anchor?.source || 'gyro-gps',+ },room: {id: room.id,originLat: room.originLat, originLng: room.originLng,@@ -1988,8 +2047,11 @@ async function placeRoomAgent(body) {// matching the nearby projection so pinRoom()/pinWorldPos() render it correctly.const pin = {id: data.pin.id,- lat: body.lat, lng: body.lng,- heading, anchor_yaw_deg: heading, anchor_height_m: 0,+ lat, lng,+ heading: h, anchor_yaw_deg: anchor?.yawDeg ?? h,+ anchor_height_m: anchor?.heightM ?? 0,+ anchor_quat: quat,+ anchor_source: anchor?.source || 'gyro-gps',room_id: room.id, rel_east_m: room.relEast, rel_north_m: room.relNorth,origin_lat: room.originLat, origin_lng: room.originLng, origin_yaw_deg: room.originYawDeg || 0,avatar_url: resolveAvatarUrl(_currentAvatarId), avatar_name: nameEl.textContent,@@ -2350,6 +2412,16 @@ document.addEventListener('visibilitychange', () => {});let xrSession = null;+// The room-authoring API (src/irl/room-mode.js), captured from initRoomMode below.+// The WebXR floor path reads it to anchor a hit into the active room (or establish+// one) and to bump the room badge — so on-device precision and the gyro slider flow+// always share one room. Assigned at init; only referenced after a user gesture.+let roomModeApi = null;+// The room pin currently being sharpened by a WebXR "Refine on floor" session, or+// null for a normal placement. onFloorAnchored routes the tap to refine when set;+// enterFloorPlacement clears it so a plain "Place on floor" never re-targets a stale+// pin. Bounds-checked server-side — refine only sharpens this one agent's offset.+let _refinePin = null;// A floor anchor placed before the first GPS fix is held here and persisted the// instant onGPSPosition() lands real coordinates (mirrors _pendingGpsLock for the// gyro path). The in-session XRAnchor already glues the agent; this rescues its@@ -2553,6 +2625,15 @@ function onFloorAnchored(pose, meta = {}) {// tap takes (the in-scene pulse + haptic fire from WebXRSession). It rides every// downstream copy change until the session resets.setXrConfirmed(true);+ // Refine-on-floor (R3): the tap re-places ONE existing room agent rather than+ // dropping a new one. Consume the target latch and PATCH the single agent's offset+ // — bypassing the new-pin persist gate entirely (the agent already exists).+ if (_refinePin) {+ const target = _refinePin;+ _refinePin = null;+ refineFloorAnchored(target, pose);+ return;+ }// The gate decides: with a live fix it persists now; during GPS warm-up it// holds the pose (degraded flag rides along) and onGPSPosition drains it once.const outcome = floorPersist.place({ pose, degraded }, gpsState.ready);@@ -2566,41 +2647,63 @@ function onFloorAnchored(pose, meta = {}) {// outcome === 'persisted' → persistFloorAnchor set the resting hint already.}-// Convert the anchored local-space pose to a GPS pin and persist it (A2) — the-// durable, shareable record beyond the in-session XRAnchor. Horizontal offset →-// lat/lng uses the same metre-per-degree math as the gyro Pin path (local −Z =-// north, +X = east); height + yaw + GPS-fit trust ride along in the anchor object.-// Split out so onGPSPosition() can replay a pose captured before the first fix.-// `degraded` (no real XRAnchor) only changes the in-session honesty copy — the-// durable GPS pin is just coordinates, so it saves the same either way.+// Persist a WebXR floor placement as a shared ROOM pin (R3). The hit-test gives a+// metres-from-eye-level local pose; we fold the placer's GPS offset from the room+// origin into it and store the EXACT room-frame offset (relEast/relNorth) + the real+// floor height + the surface quaternion, tagged `anchor_source: 'webxr'`. The agent+// then renders for every viewer through the same shared frame as a gyro placement —+// WebXR only improved WHERE it was captured. If the user reached "Place on floor"+// without entering room mode, we establish a room at the current fix first, so a+// WebXR drop is never a one-off standalone pin. Split out so onGPSPosition() can+// replay a pose captured before the first fix; the gate guarantees gpsState.ready.+// `degraded` (no real XRAnchor) only changes the in-session honesty copy.function persistFloorAnchor(pose, degraded = false) {const { position, quaternion } = pose;- // Pure, unit-tested conversion (src/irl/floor-anchor.js): horizontal offset →- // lat/lng via room-anchor's single projection, quaternion → normalised yaw.- const pin = anchorPoseToPin({- originLat: gpsState.lat,- originLng: gpsState.lng,- x: position.x,- y: position.y,- z: position.z,- quat: [quaternion.x, quaternion.y, quaternion.z, quaternion.w],+ const quat = [quaternion.x, quaternion.y, quaternion.z, quaternion.w];++ // Establish (or reuse) the shared room this precise placement anchors into. The+ // compass frame matches the gyro path's getHeading dep: true compass when present,+ // else camera-yaw, with prefersAbsOrientation deciding the true-north frame.+ const headingDeg = lastCompassHeading != null+ ? lastCompassHeading+ : ((-(cameraYaw * 180 / Math.PI)) % 360 + 360) % 360;+ const room = roomModeApi?.ensureRoom({+ lat: gpsState.lat, lng: gpsState.lng,+ headingDeg, absolute: !!prefersAbsOrientation,+ });+ if (!room) {+ // Behind the persist gate gpsState.ready is true, so this is defensive only:+ // never strand the tap — the in-session anchor still holds the agent.+ setXrResting('Placed — couldn’t lock your location to save it; move to a clearer sky and retry');+ return;+ }++ // Pure, unit-tested conversion (src/irl/floor-anchor.js): XR hit pose → exact+ // offset in the room frame + the absolute lat/lng GPS index + heading from the quat.+ const placement = roomPlacementFromHit({+ originLat: room.originLat, originLng: room.originLng, originYawDeg: room.originYawDeg || 0,+ viewerLat: gpsState.lat, viewerLng: gpsState.lng,+ x: position.x, y: position.y, z: position.z, quat,});- gpsPin = { lat: pin.lat, lng: pin.lng };- gpsModeActive = true;setXrResting(placementHint(degraded));- savePin(pin.lat, pin.lng, pin.heading, '', {- heightM: pin.heightM, // floor height relative to the eye-level session origin (negative = below)- yawDeg: pin.heading,- quat: pin.quat,- source: pin.source,+ postRoomPin({+ lat: placement.lat, lng: placement.lng, heading: placement.relYawDeg,+ room: {+ id: room.id, originLat: room.originLat, originLng: room.originLng,+ originYawDeg: room.originYawDeg || 0,+ relEast: placement.relEast, relNorth: placement.relNorth,+ },+ anchor: {+ heightM: placement.heightM, yawDeg: placement.relYawDeg, quat: placement.quat,+ gpsAccuracyM: gpsState.accuracy, altitudeM: gpsState.altitude, source: 'webxr',+ },}).then(result => {- if (result?.ok && gpsPin) {- gpsPin.id = result.id;- revealMyPinsBtn();+ if (result?.ok) {+ roomModeApi?.notePlacement();setXrResting(result.permanent- ? 'Saved — your agent is here for everyone nearby'- : 'Saved — people nearby can see your agent for 7 days');+ ? 'Saved on the floor — your agent is here for everyone nearby'+ : 'Saved on the floor — people nearby can see your agent for 7 days');} else {// Surface the moderation/cap/rate reason; the in-session anchor still holds.setXrResting(result?.message || 'Placed — couldn’t save the pin yet, retry on exit');@@ -2608,6 +2711,72 @@ function persistFloorAnchor(pose, degraded = false) {});}+// Re-place ONE existing room agent from a fresh WebXR hit (R3 "refine on floor").+// Converts the hit to the SAME room's frame (the agent's stored origin, never a new+// one) and PATCHes only this agent's rel offset + floor height + facing — the shared+// origin is untouched, so the cluster stays put and only the local view sharpens.+// Bounds are enforced server-side; an over-large move is rejected with the existing+// 422 copy. The session stays open on the sharpened agent; the user exits when ready.+function refineFloorAnchored(pin, pose) {+ if (!gpsState.ready) { setXrResting('Waiting for your location to refine — hold still a moment'); return; }+ const room = pinRoom(pin);+ if (!room) { setXrResting('This agent isn\u2019t in a room — exit and use Calibrate instead'); return; }+ const { position, quaternion } = pose;+ const placement = roomPlacementFromHit({+ originLat: room.originLat, originLng: room.originLng, originYawDeg: room.originYawDeg,+ viewerLat: gpsState.lat, viewerLng: gpsState.lng,+ x: position.x, y: position.y, z: position.z,+ quat: [quaternion.x, quaternion.y, quaternion.z, quaternion.w],+ });+ setXrResting('Sharpening this agent\u2019s spot\u2026');+ const body = { id: pin.id, deviceToken: _deviceToken, calibrate: {+ lat: placement.lat, lng: placement.lng,+ anchorYawDeg: placement.relYawDeg, anchorHeightM: placement.heightM,+ relEast: placement.relEast, relNorth: placement.relNorth,+ } };+ fetch('/api/irl/pins', {+ method: 'PATCH', credentials: 'include',+ headers: deviceHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify(body),+ }).then(async (r) => {+ if (!r.ok) {+ const msg = r.status === 403 ? 'Only the owner can refine this agent.'+ : r.status === 422 ? 'That\u2019s too far from the agent\u2019s spot — refine sharpens a placement, it doesn\u2019t move it across the room.'+ : r.status === 404 ? 'This agent is no longer here.'+ : 'Couldn\u2019t save the refined spot — try again.';+ setXrResting(msg);+ return;+ }+ // Commit the sharpened offset onto the live pin so it re-renders at once and+ // every nearby viewer picks it up on their next proximity poll (~10 s).+ pin.rel_east_m = placement.relEast;+ pin.rel_north_m = placement.relNorth;+ pin.lat = placement.lat; pin.lng = placement.lng;+ pin.anchor_height_m = placement.heightM;+ pin.anchor_yaw_deg = placement.relYawDeg; pin.heading = Math.round(placement.relYawDeg);+ pin.anchor_quat = placement.quat;+ if (pin.group && gpsState.ready) {+ const wp = pinWorldPos(pin);+ pin.group.position.set(wp.x, wp.y, wp.z);+ pin.group.rotation.y = pinYawRad(pin);+ if (pin.baseYaw != null) pin.baseYaw = pin.group.rotation.y;+ }+ setXrResting('Refined — saved here; nearby viewers update within ~10s. Tap exit when you\u2019re done.');+ try { navigator.vibrate?.(12); } catch {}+ loadNearbyPins();+ }).catch(() => {+ setXrResting('Couldn\u2019t reach the server — exit and try again.');+ });+}++// Enter a WebXR floor session aimed at refining ONE existing room agent. Latches the+// target so the next tap routes to refineFloorAnchored, then reuses the same hit-test+// session as placement. WebXR-only and owner-only — gated where the entry is offered.+function enterRefineOnFloor(pin) {+ if (_placementCapability !== 'webxr' || !pin) return;+ _refinePin = pin;+ enterFloorAnchor();+}+// ── iOS AR Quick Look (capability 'quicklook') ─────────────────────────────//// ARKit Quick Look needs a USDZ. Prefer the server-hosted companion the avatar@@ -2652,6 +2821,10 @@ async function enterQuickLookPlacement() {// in-canvas hit-test session. ('pin' devices never reach here — the button stays// hidden and the Pin path is the placement.)function enterFloorPlacement() {+ // A plain "Place on floor" drops a NEW agent — clear any refine target a prior,+ // exited-without-tapping refine session left latched, so this never re-places an+ // old agent instead of creating one.+ _refinePin = null;if (_placementCapability === 'quicklook') return enterQuickLookPlacement();return enterFloorAnchor();}@@ -3317,6 +3490,10 @@ async function loadNearbyPins() {updateNearbyBadge();+ // R2: offer the one-tap align for any nearby relative-frame room this viewer+ // doesn't own (a room placed without a compass that may render rotated here).+ maybePromptRoomAlign();+// Flash pin label if ?highlight= matchesif (highlightPinId) {flashPinLabel(nearbyPins.find(p => p.id === highlightPinId));@@ -4638,6 +4815,34 @@ function openPinSheet(pin) {: null;}+ // Refine on floor (R3) — the precision layer. On a WebXR device, the owner can+ // re-place their OWN room agent with a real on-device hit-test (feet on the actual+ // floor) instead of the drag nudge. Only shown for an own ROOM pin on a WebXR+ // device; iOS/unsupported keep Calibrate (the button stays absent, never a dead+ // end). It sharpens this one agent without touching the shared origin.+ const refineBtn = document.getElementById('irl-sheet-refine');+ if (refineBtn) {+ const canRefine = _placementCapability === 'webxr' && isOwnPin(pin) && !!pinRoom(pin);+ refineBtn.hidden = !canRefine;+ refineBtn.onclick = canRefine+ ? () => { closeInspectSheet(); enterRefineOnFloor(pin); }+ : null;+ }++ // Align this room (R2) — the headline one-gesture tool. Shown when this agent+ // belongs to a multi-agent room THIS device owns entirely: align the whole+ // cluster in one move instead of nudging each agent. The server re-checks+ // ownership across every pin in the room.+ const alignBtn = document.getElementById('irl-sheet-align-room');+ if (alignBtn) {+ const rid = alignableRoomId(pin);+ const count = rid ? nearbyPins.filter(p => p.room_id === rid && p.group).length : 0;+ const show = !!rid && count >= 2;+ alignBtn.hidden = !show;+ alignBtn.textContent = show ? `Align this room (${count})` : 'Align this room';+ alignBtn.onclick = show ? () => { closeInspectSheet(); enterRoomCalibrate(rid); } : null;+ }+// Report (D4) — community moderation. Pointless on your own pin (the server// no-ops owner self-reports), so it's shown only on someone else's placement.const reportBtn = document.getElementById('irl-sheet-report');@@ -5801,7 +6006,8 @@ function tick() {// nudge keep the UX truthful and correctable. No coin is involved anywhere here.let calibrateActive = false;-let _cal = null; // active calibration session, or null+let _cal = null; // active per-pin calibration session, or null+let _roomCal = null; // active one-gesture room-calibrate session, or null// Pin ids this device placed — gates the client-side calibrate affordance and the// gold "your agent" label. The server re-checks ownership on every PATCH, so this@@ -5810,6 +6016,20 @@ const _myPinIds = new Set();function isOwnPin(pin) {return _myPinIds.has(pin.id) || (gpsPin?.id != null && pin.id === gpsPin.id);}+// Room ownership: the server's is_mine (authoritative across sessions/reloads) or+// a pin this device placed this session. Used to gate the whole-room align.+function isOwnRoomPin(pin) {+ return pin?.is_mine === true || isOwnPin(pin);+}+// The room id the given pin belongs to, IF this device owns every rendered agent+// in it (so a whole-room align can never move a stranger's agent). Null otherwise.+function alignableRoomId(pin) {+ const rid = pin?.room_id;+ if (!rid) return null;+ const inRoom = nearbyPins.filter(p => p.room_id === rid && p.group);+ if (!inRoom.length) return null;+ return inRoom.every(isOwnRoomPin) ? rid : null;+}// — Long-press to enter calibrate —let _lpTimer = null, _lpPin = null, _lpX = 0, _lpY = 0, _lpPointerId = -1;@@ -5884,6 +6104,7 @@ function enterCalibrate(pin, seed = null) {}function exitCalibrate(revert) {+ if (_roomCal) return exitRoomCalibrate(revert);document.getElementById('irl-calibrate-panel')?.classList.remove('is-open');document.body.classList.remove('is-calibrating');if (_cal) {@@ -5984,17 +6205,39 @@ function calPointerDown(e) {_calPtrs.set(e.pointerId, { x: e.clientX, y: e.clientY });try { canvas.setPointerCapture?.(e.pointerId); } catch {}if (_calPtrs.size >= 2) {- _calTwistStart = { angle: _twoFingerAngle(), yaw: _cal.yaw };+ _calTwistStart = { angle: _twoFingerAngle(), yaw: _roomCal ? _roomCal.dYaw : _cal.yaw };_calGroundStart = null;} else {const gp = _groundPointXY(e.clientX, e.clientY);_calGroundStart = gp ? { x: gp.x, z: gp.z } : null;- _calDragStart = { lat: _cal.lat, lng: _cal.lng };+ _calDragStart = _roomCal ? { dEast: _roomCal.dEast, dNorth: _roomCal.dNorth } : { lat: _cal.lat, lng: _cal.lng };}}function calPointerMove(e) {if (!calibrateActive || !_calPtrs.has(e.pointerId)) return;_calPtrs.set(e.pointerId, { x: e.clientX, y: e.clientY });+ // Room align: the whole cluster slides (drag) / rotates about its origin (twist).+ if (_roomCal) {+ if (_calPtrs.size >= 2) {+ if (!_calTwistStart) _calTwistStart = { angle: _twoFingerAngle(), yaw: _roomCal.dYaw };+ let dDeg = (_twoFingerAngle() - _calTwistStart.angle) * 180 / Math.PI;+ dDeg = Math.max(-45, Math.min(45, dDeg));+ _roomCal.dYaw = _calTwistStart.yaw + dDeg;+ applyRoomCalToGroups(); updateRoomCalReadout();+ return;+ }+ if (!_calGroundStart || !_calDragStart) {+ const gp0 = _groundPointXY(e.clientX, e.clientY);+ if (gp0) { _calGroundStart = { x: gp0.x, z: gp0.z }; _calDragStart = { dEast: _roomCal.dEast, dNorth: _roomCal.dNorth }; }+ return;+ }+ const gpr = _groundPointXY(e.clientX, e.clientY);+ if (!gpr) return;+ _roomCal.dEast = _calDragStart.dEast + (gpr.x - _calGroundStart.x);+ _roomCal.dNorth = _calDragStart.dNorth - (gpr.z - _calGroundStart.z); // north = −Z+ applyRoomCalToGroups(); updateRoomCalReadout();+ return;+ }if (_calPtrs.size >= 2) {// Two-finger twist → yaw nudge. Live feedback lets the owner aim it; clamp ±45°.if (!_calTwistStart) _calTwistStart = { angle: _twoFingerAngle(), yaw: _cal.yaw };@@ -6025,19 +6268,32 @@ function calPointerUp(e) {try { canvas.releasePointerCapture?.(e.pointerId); } catch {}if (_calPtrs.size < 2) _calTwistStart = null;if (_calPtrs.size === 0) { _calGroundStart = null; _calDragStart = null; }- else { _calGroundStart = null; _calDragStart = { lat: _cal.lat, lng: _cal.lng }; } // rebase, avoid a jump+ else { // rebase the remaining finger so lifting one doesn't jump the rig+ _calGroundStart = null;+ _calDragStart = _roomCal ? { dEast: _roomCal.dEast, dNorth: _roomCal.dNorth } : { lat: _cal.lat, lng: _cal.lng };+ }}// — Save / errors —async function saveCalibrate() {+ if (_roomCal) return saveRoomCalibrate();if (!_cal) return;const saveBtn = document.getElementById('irl-cal-save');const errEl = document.getElementById('irl-cal-error');if (errEl) { errEl.hidden = true; errEl.replaceChildren(); }if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Saving…'; }const pin = _cal.pin;+ // For a ROOM pin the render path resolves position from rel_east_m/rel_north_m+ // (not the absolute lat/lng), so a drag that moved only lat/lng would snap back on+ // the next viewer re-fetch. Re-derive the agent's exact room-frame offset from the+ // calibrated coordinate and send it too, so the per-agent nudge sticks for everyone.+ const _room = pinRoom(pin);+ const _rel = _room+ ? roomRelFromGeo({ originLat: _room.originLat, originLng: _room.originLng, originYawDeg: _room.originYawDeg, lat: _cal.lat, lng: _cal.lng })+ : null;const body = { id: pin.id, deviceToken: _deviceToken, calibrate: {- lat: _cal.lat, lng: _cal.lng, anchorYawDeg: _cal.yaw, anchorHeightM: _cal.height } };+ lat: _cal.lat, lng: _cal.lng, anchorYawDeg: _cal.yaw, anchorHeightM: _cal.height,+ ...(_rel ? { relEast: _rel.relEast, relNorth: _rel.relNorth } : {}) } };try {const r = await fetch('/api/irl/pins', {method: 'PATCH', credentials: 'include',@@ -6055,6 +6311,7 @@ async function saveCalibrate() {pin.lat = _cal.lat; pin.lng = _cal.lng;pin.anchor_yaw_deg = _cal.yaw; pin.heading = Math.round(_cal.yaw);pin.anchor_height_m = _cal.height;+ if (_rel) { pin.rel_east_m = _rel.relEast; pin.rel_north_m = _rel.relNorth; }// The manual yaw nudge supersedes the captured surface quaternion; drop it so// pinYawRad (task 02) reads the corrected anchor_yaw_deg, matching the server// (handleCalibrate clears anchor_quat on a yaw change). Without this the live@@ -6081,6 +6338,236 @@ async function saveCalibrate() {}}+// ── One-gesture ROOM calibrate (R2) ─────────────────────────────────────────+// The headline alignment tool. Every agent in a room is rigidly tied to one+// shared origin, so instead of nudging each agent (A3) the owner grabs the WHOLE+// cluster and slides / twists it onto its true real-world spot once — moving+// every agent together with the internal layout intact. The gesture mirrors the+// per-pin calibrate (reusing _calPtrs / _groundPointXY) but is applied to the+// room ORIGIN (roomOriginWorld) and re-renders the cluster live; the save is the+// owner-gated, bounds-checked room-scoped PATCH (handleCalibrateRoom), which+// re-derives each agent's absolute lat/lng from its unchanged room-frame offset.++function enterRoomCalibrate(roomId) {+ const panel = document.getElementById('irl-calibrate-panel');+ const pins = nearbyPins.filter(p => p.room_id === roomId && p.group);+ if (!panel || !pins.length) return;+ if (!pins.every(isOwnRoomPin)) { showCalibrateDenied(); return; }+ if (!gpsState.ready) { setStatus('Waiting for a GPS fix before aligning the room…', { warn: true }); return; }+ document.getElementById('irl-sheet')?.classList.remove('is-open');+ const base = pins[0];+ _roomCal = {+ roomId, pins,+ originLat: Number(base.origin_lat), originLng: Number(base.origin_lng),+ originYawDeg: Number(base.origin_yaw_deg) || 0,+ dEast: 0, dNorth: 0, dYaw: 0,+ };+ for (const p of pins) {+ const yaw0 = Number.isFinite(p.anchor_yaw_deg) ? p.anchor_yaw_deg : (p.heading ?? 0);+ p._roomCalBaseYaw = ((yaw0 % 360) + 360) % 360;+ p.labelEl?.classList.add('is-calibrating');+ }+ calibrateActive = true;+ document.body.classList.add('is-calibrating', 'is-room-cal');+ const titleEl = document.getElementById('irl-cal-title');+ if (titleEl) titleEl.textContent = `Align ${pins.length} agent${pins.length === 1 ? '' : 's'} in this room`;+ const errEl = document.getElementById('irl-cal-error');+ if (errEl) { errEl.hidden = true; errEl.replaceChildren(); }+ const saveBtn = document.getElementById('irl-cal-save');+ if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save room position'; }+ updateRoomCalReadout(); updateRoomCalAccuracy();+ panel.classList.add('is-open');+ setStatus('Drag to slide the whole room · twist with two fingers to rotate');+ _calPtrs.clear(); _calTwistStart = null; _calGroundStart = null; _calDragStart = null;+}++function exitRoomCalibrate(revert) {+ document.getElementById('irl-calibrate-panel')?.classList.remove('is-open');+ document.body.classList.remove('is-calibrating', 'is-room-cal');+ if (_roomCal) {+ if (revert) { _roomCal.dEast = 0; _roomCal.dNorth = 0; _roomCal.dYaw = 0; applyRoomCalToGroups(); }+ for (const p of _roomCal.pins) { p.labelEl?.classList.remove('is-calibrating'); delete p._roomCalBaseYaw; }+ }+ _roomCal = null;+ calibrateActive = false;+ _calPtrs.clear(); _calTwistStart = null; _calGroundStart = null; _calDragStart = null;+ const saveBtn = document.getElementById('irl-cal-save');+ if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save position'; }+ const titleEl = document.getElementById('irl-cal-title');+ if (titleEl) titleEl.textContent = 'Calibrate position';+}++// Clamp the working alignment to a small correction — slide a few metres / twist,+// never relocate. Matches the server ceilings (±5 m translation magnitude, ±45°).+function clampRoomCal() {+ if (!_roomCal) return;+ const m = Math.hypot(_roomCal.dEast, _roomCal.dNorth);+ if (m > 5) { const s = 5 / m; _roomCal.dEast *= s; _roomCal.dNorth *= s; }+ _roomCal.dYaw = Math.max(-45, Math.min(45, _roomCal.dYaw));+}++// Apply the working alignment to every group in the cluster so the whole room+// moves rigidly and live. Reuses the pure room-anchor math against a temporary+// origin (current origin + the drag) and frame yaw (+ the twist).+function applyRoomCalToGroups() {+ if (!_roomCal) return;+ clampRoomCal();+ const moved = localToGeo(_roomCal.originLat, _roomCal.originLng, _roomCal.dEast, _roomCal.dNorth);+ const yaw = ((_roomCal.originYawDeg + _roomCal.dYaw) % 360 + 360) % 360;+ const originWorld = roomOriginWorld(gpsState.lat, gpsState.lng, moved.lat, moved.lng);+ for (const p of _roomCal.pins) {+ if (!p.group) continue;+ const wp = agentWorldPosition({+ originWorld,+ relEast: Number(p.rel_east_m) || 0,+ relNorth: Number(p.rel_north_m) || 0,+ heightM: pinHeightM(p),+ originYawDeg: yaw,+ });+ p.group.position.set(wp.x, wp.y, wp.z);+ const fy = -(((p._roomCalBaseYaw || 0) + _roomCal.dYaw) * Math.PI / 180);+ p.group.rotation.y = fy;+ p.baseYaw = fy; // keep the camera-aware rest target in sync+ updatePinRing(p);+ }+}++function updateRoomCalReadout() {+ const el = document.getElementById('irl-cal-readout');+ if (!el || !_roomCal) return;+ clampRoomCal();+ const ns = _roomCal.dNorth >= 0 ? 'N' : 'S', ew = _roomCal.dEast >= 0 ? 'E' : 'W';+ const dy = _roomCal.dYaw;+ el.textContent = `${Math.abs(_roomCal.dNorth).toFixed(1)} m ${ns} · ${Math.abs(_roomCal.dEast).toFixed(1)} m ${ew} · ${dy >= 0 ? '+' : ''}${dy.toFixed(0)}°`;+}++// Honest room-level confidence: anchor the cluster to the LOOSEST origin-GPS+// accuracy across its agents, so the owner understands "this room is anchored to+// about ±N m — align it if it's off." Never imply centimetre precision.+function updateRoomCalAccuracy() {+ const el = document.getElementById('irl-cal-accuracy');+ if (!el || !_roomCal) return;+ let acc = null;+ for (const p of _roomCal.pins) {+ const a = Number.isFinite(p.gps_accuracy_m) ? p.gps_accuracy_m : null;+ if (a != null) acc = acc == null ? a : Math.max(acc, a);+ }+ if (acc == null && Number.isFinite(gpsState.accuracy)) acc = gpsState.accuracy;+ const low = acc != null && acc > RING_LOW_ACC_M;+ el.classList.toggle('is-low', low);+ el.textContent = acc != null+ ? `This room is anchored to about ±${Math.round(acc)} m. Slide and twist the whole cluster onto its real spot, then save.`+ : 'Slide and twist the whole cluster onto its real spot, then save.';+}++async function saveRoomCalibrate() {+ if (!_roomCal) return;+ clampRoomCal();+ const saveBtn = document.getElementById('irl-cal-save');+ const errEl = document.getElementById('irl-cal-error');+ if (errEl) { errEl.hidden = true; errEl.replaceChildren(); }+ const { roomId, dEast, dNorth, dYaw } = _roomCal;+ // A no-op gesture: nothing to persist — exit cleanly rather than burn a write.+ if (Math.hypot(dEast, dNorth) < 0.02 && Math.abs(dYaw) < 0.5) {+ exitRoomCalibrate(false);+ setStatus('Room already aligned — no change to save');+ return;+ }+ if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Saving…'; }+ const pins = _roomCal.pins;+ const baseOrigin = { originLat: _roomCal.originLat, originLng: _roomCal.originLng, originYawDeg: _roomCal.originYawDeg };+ try {+ const r = await fetch('/api/irl/pins', {+ method: 'PATCH', credentials: 'include',+ headers: deviceHeaders({ 'Content-Type': 'application/json' }),+ body: JSON.stringify({ deviceToken: _deviceToken, calibrateRoom: {+ roomId, dEastM: dEast, dNorthM: dNorth, dYawDeg: dYaw } }),+ });+ if (!r.ok) {+ const m = r.status === 403 ? 'Only the room owner can align this room.'+ : r.status === 422 ? 'That move is too large — alignment slides the room a few metres, it doesn’t relocate it.'+ : r.status === 404 ? 'This room is no longer here.'+ : 'Could not save the room alignment.';+ throw new Error(m);+ }+ const data = await r.json().catch(() => ({}));+ const next = (data && data.origin)+ ? { originLat: data.origin.lat, originLng: data.origin.lng, originYawDeg: data.origin.yawDeg }+ : calibrateRoomOrigin({ ...baseOrigin, dEastM: dEast, dNorthM: dNorth, dYawDeg: dYaw });+ // Commit the new origin + per-agent facing onto every live pin so the cluster+ // persists this session; nearby viewers pick it up on their next poll. Render+ // keeps using the room frame (origin + rel), so this avoids a snap on exit.+ for (const p of pins) {+ p.origin_lat = next.originLat; p.origin_lng = next.originLng; p.origin_yaw_deg = next.originYawDeg;+ const newYaw = (((p._roomCalBaseYaw || 0) + dYaw) % 360 + 360) % 360;+ p.anchor_yaw_deg = newYaw; p.heading = Math.round(newYaw);+ if (dYaw !== 0) p.anchor_quat = null;+ }+ setStatus('Room aligned — saved here; nearby viewers update within ~10s');+ exitRoomCalibrate(false);+ loadNearbyPins();+ } catch (err) {+ if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save room position'; }+ if (errEl) {+ errEl.replaceChildren(errorStateEl({+ title: 'Alignment failed',+ body: _escHtml(err.message || 'Could not save the room alignment.'),+ actions: [+ { label: 'Retry', id: 'cal-retry', primary: true },+ { label: 'Undo', id: 'cal-undo' },+ ],+ }));+ errEl.hidden = false;+ }+ }+}++// ── Relative-frame one-tap alignment (R2) ───────────────────────────────────+// A room placed WITHOUT an absolute compass can render rotated for a second+// viewer. When such a cluster is nearby (and this viewer doesn't own it — owners+// get the full gesture), offer a one-tap "face the room's front and tap" align+// that rotates THIS viewer's frame to match (a viewer-local _roomYawOffset). It+// never moves the room for anyone else.+const _roomAlignDismissed = new Set();+function isRelativeFrameRoom(pin) {+ return (Number(pin.origin_yaw_deg) || 0) !== 0 || pin.anchor_source === 'gyro-gps:rel';+}+function maybePromptRoomAlign() {+ const prompt = document.getElementById('irl-room-align-prompt');+ if (!prompt) return;+ if (calibrateActive) return; // don't stack over an active alignment+ let target = null;+ for (const p of nearbyPins) {+ if (!p.room_id || !p.group) continue;+ if (_roomYawOffset.has(p.room_id) || _roomAlignDismissed.has(p.room_id)) continue;+ if (alignableRoomId(p)) continue; // owner — use the full align gesture instead+ if (!isRelativeFrameRoom(p)) continue;+ target = p; break;+ }+ if (!target) { prompt.classList.remove('is-shown'); prompt.hidden = true; return; }+ prompt.dataset.roomId = target.room_id;+ prompt.dataset.storedYaw = String(Number(target.origin_yaw_deg) || 0);+ prompt.hidden = false;+ requestAnimationFrame(() => prompt.classList.add('is-shown'));+}+function alignRelativeRoom(roomId, storedYaw) {+ const heading = lastCompassHeading != null+ ? lastCompassHeading+ : ((-(cameraYaw * 180 / Math.PI)) % 360 + 360) % 360;+ // Effective frame yaw becomes the viewer's current facing, so the room's local+ // "forward" (relNorth+) aligns to where the viewer is looking.+ _roomYawOffset.set(roomId, (((heading - storedYaw) % 360) + 360) % 360);+ persistRoomAlign();+ for (const p of nearbyPins) {+ if (p.room_id !== roomId || !p.group) continue;+ const wp = pinWorldPos(p);+ p.group.position.set(wp.x, wp.y, wp.z);+ p.distance_m = Math.round(Math.hypot(wp.x, wp.z));+ updatePinRing(p);+ }+ setStatus('Room aligned to your view');+}+function showCalibrateDenied() {const el = document.getElementById('irl-cal-denied');if (!el) { setStatus('Only the owner can calibrate this agent', { error: true }); return; }@@ -6126,6 +6613,22 @@ document.getElementById('irl-cal-denied')?.addEventListener('click', (e) => {});window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && calibrateActive) exitCalibrate(true); });+// Relative-frame one-tap alignment prompt (R2). "Align" rotates this viewer's+// frame to match the room; "Dismiss" hides it for the session.+document.getElementById('irl-room-align-prompt')?.addEventListener('click', (e) => {+ const btn = e.target.closest('[data-ra-action]');+ if (!btn) return;+ const prompt = document.getElementById('irl-room-align-prompt');+ const roomId = prompt?.dataset.roomId;+ if (btn.dataset.raAction === 'align' && roomId) {+ alignRelativeRoom(roomId, Number(prompt.dataset.storedYaw) || 0);+ } else if (roomId) {+ _roomAlignDismissed.add(roomId);+ }+ prompt?.classList.remove('is-shown');+ if (prompt) setTimeout(() => { prompt.hidden = true; }, 220);+});+// ── Boot ──────────────────────────────────────────────────────────────────// Permissions + first-run onboarding (E1) own the camera/motion/location prompts.// GPS starts only once location is granted — via first-run, a repeat-visit replay,@@ -6187,7 +6690,12 @@ detectFloorAnchorSupport();// supply the live pose, AR/permission readiness, and the placement (network +// scene spawn) it calls back into. Rooms are delivered to other viewers by the// REST proximity read — there is no realtime pin push to wire here.-initRoomMode({+// Live ghost preview (R1 §3): a translucent stand-in at the exact spot the agent+// will land, so the user sees it in the room before committing. room-mode drives+// it each animation frame via the previewAim dep; the geometry is the same+// room-anchor.js math the real placement uses, so the agent doesn't jump on Place.+const roomGhost = createRoomGhost(scene, { reducedMotion: prefersReducedMotion });+roomModeApi = initRoomMode({controlRow: document.querySelector('.irl-secondary-row'),getFix: () => ({ lat: gpsState.lat, lng: gpsState.lng, ready: gpsState.ready, accuracy: gpsState.accuracy }),getHeading: () => ({@@ -6208,6 +6716,7 @@ initRoomMode({return arActive;},placeRoomAgent,+ previewAim: (s) => roomGhost.preview(s),status: (m, o) => setStatus(m, o),});diff --git a/src/irl/room-ghost.js b/src/irl/room-ghost.jsnew file mode 100644index 000000000..0ad04559e--- /dev/null+++ b/src/irl/room-ghost.js@@ -0,0 +1,135 @@+// Live "ghost" preview for /irl room authoring (Epic R / R1).+//+// While the user aims to drop an agent, this renders a translucent stand-in at+// the EXACT world spot the agent will land, so they see it in the room before+// committing — the difference between guessing and placing. It is deliberately a+// lightweight proxy (a glowing figure + a floor footprint), not a clone of the+// skinned avatar GLB: the ghost moves every frame as the phone turns and the+// distance slider scrubs, so it must cost ~nothing, and the real avatar spawns+// the instant Place is tapped (irl.js → spawnNearbyPin).+//+// It is self-contained on the same principle as room-mode.js: irl.js owns the+// scene, the GPS origin and the live compass, and feeds this module the minimal+// pose each frame. The geometry comes from the one shared, unit-tested source —+// room-anchor.js — so the ghost and the persisted placement can never disagree:+// the viewer sits at the world origin (their own GPS), the drop is `distM` along+// the live compass bearing, and the figure faces back toward the viewer (or away+// on the toggle). compassToYaw matches src/irl.js's pinYawRad exactly, so a+// just-placed agent does not visibly rotate when the ghost hands off to it.++import {+ Group,+ Mesh,+ CylinderGeometry,+ SphereGeometry,+ TorusGeometry,+ MeshStandardMaterial,+} from 'three';+import { bearingDistanceToLocal, agentWorldPosition, compassToYaw } from './room-anchor.js';++const ACCENT = 0x7c5cff; // matches the HUD's --accent purple (room-mode.js)++/**+ * Build the ghost and return its controls. The figure is added to `scene` once+ * and toggled with visibility — no per-frame allocation. Nothing renders until+ * setActive(true) AND a GPS fix is present (update() hides it otherwise, so the+ * preview can never imply a placement at null-island).+ *+ * @param {import('three').Scene} scene+ * @param {object} [opts]+ * @param {() => boolean} [opts.reducedMotion] suppress the pulse for these users+ * @returns {{ setActive(on:boolean):void, setParams(p:{distM?:number,faceViewer?:boolean}):void, update(s:{ready:boolean,headingDeg:number,dt:number}):void, dispose():void }}+ */+export function createRoomGhost(scene, opts = {}) {+ const reducedMotion = opts.reducedMotion || (() => false);++ const group = new Group();+ group.visible = false;+ group.renderOrder = 3;++ // Each part gets its own material so the pulse can drive opacity without+ // touching the shared pin materials. depthWrite off + transparent so the ghost+ // reads as a hologram over the camera feed, never occluding real agents oddly.+ const figureMat = () => new MeshStandardMaterial({+ color: ACCENT, emissive: ACCENT, emissiveIntensity: 0.55,+ transparent: true, opacity: 0.42, roughness: 0.5, metalness: 0, depthWrite: false,+ });+ const bodyMat = figureMat();+ const headMat = figureMat();+ const noseMat = figureMat();+ const ringMat = new MeshStandardMaterial({+ color: ACCENT, emissive: ACCENT, emissiveIntensity: 0.95,+ transparent: true, opacity: 0.6, roughness: 0.4, metalness: 0, depthWrite: false,+ });++ const body = new Mesh(new CylinderGeometry(0.2, 0.26, 1.0, 16), bodyMat);+ body.position.y = 0.62;+ const head = new Mesh(new SphereGeometry(0.2, 16, 12), headMat);+ head.position.y = 1.32;+ // A small forward "nose" cone (cylinder with a zero top radius) so the+ // face-you / face-away toggle is legible at a glance: it points along the+ // figure's local −Z, the same forward our placed avatars use.+ const nose = new Mesh(new CylinderGeometry(0, 0.1, 0.22, 12), noseMat);+ nose.rotation.x = -Math.PI / 2;+ nose.position.set(0, 1.0, -0.26);+ // Floor footprint so the drop spot reads on the ground like a map pin.+ const ring = new Mesh(new TorusGeometry(0.5, 0.03, 8, 48), ringMat);+ ring.rotation.x = Math.PI / 2;+ ring.position.y = 0.02;++ group.add(body, head, nose, ring);+ scene.add(group);++ let pulse = 0;++ /**+ * Drive the ghost one frame. The room-mode UI calls this from its own+ * requestAnimationFrame loop while aiming, so all per-frame work stays out of+ * irl.js's render loop — irl.js only renders the group it already owns.+ * @param {object} s+ * @param {boolean} s.on preview is active (false hides the ghost)+ * @param {boolean} s.ready a GPS fix exists (never preview at null-island)+ * @param {number} s.headingDeg live compass bearing the phone points (0–359)+ * @param {number} s.distM drop distance from the slider+ * @param {boolean} s.faceViewer agent faces the placer vs. away+ * @param {number} s.dt seconds since the last frame (pulse timing)+ */+ function preview(s) {+ if (!s || !s.on || !s.ready) { group.visible = false; return; }+ const distM = Number.isFinite(s.distM) ? s.distM : 2.5;+ const headingDeg = Number.isFinite(s.headingDeg) ? s.headingDeg : 0;+ // The viewer is the world origin (their own GPS); the drop is `distM` along+ // the live compass bearing — the same path placeAround/pinWorldPos take, so+ // the ghost sits where the agent will actually render.+ const ahead = bearingDistanceToLocal(headingDeg, distM);+ const w = agentWorldPosition({ originWorld: { x: 0, z: 0 }, relEast: ahead.east, relNorth: ahead.north });+ group.position.set(w.x, w.y, w.z);+ // Faces back toward the placer by default (a person you walked up to), or+ // away on the toggle — bearing + 180 vs the aim bearing.+ const faceBearing = s.faceViewer === false ? headingDeg : headingDeg + 180;+ group.rotation.y = compassToYaw(faceBearing);++ if (reducedMotion()) {+ bodyMat.opacity = headMat.opacity = noseMat.opacity = 0.42;+ ringMat.opacity = 0.6;+ group.scale.setScalar(1);+ } else {+ pulse += Number.isFinite(s.dt) ? s.dt : 0;+ const wob = Math.sin(pulse * 2.2) * 0.5 + 0.5; // 0..1+ bodyMat.opacity = headMat.opacity = noseMat.opacity = 0.34 + wob * 0.16;+ ringMat.opacity = 0.45 + wob * 0.3;+ group.scale.setScalar(1 + wob * 0.015);+ }+ group.visible = true;+ }++ function dispose() {+ scene.remove(group);+ for (const m of group.children) {+ if (m.geometry) m.geometry.dispose();+ if (m.material) m.material.dispose();+ }+ }++ return { preview, dispose };+}diff --git a/src/irl/room-mode.js b/src/irl/room-mode.jsindex 5865557ba..22b830384 100644--- a/src/irl/room-mode.js+++ b/src/irl/room-mode.js@@ -112,6 +112,9 @@ function injectStyles() {export function initRoomMode(deps) {const { getFix, getHeading, ensureReady, placeRoomAgent } = deps;const status = deps.status || (() => {});+ // Optional: drive a live 3D ghost preview of where the agent will land. irl.js+ // owns the scene + render; we feed it the live aim each animation frame.+ const previewAim = deps.previewAim || (() => {});if (typeof getFix !== 'function' || typeof placeRoomAgent !== 'function') {throw new Error('initRoomMode: getFix + placeRoomAgent are required');}@@ -122,6 +125,8 @@ export function initRoomMode(deps) {let faceViewer = true;let activeRoom = reviveRoomFromStore();let tickTimer = null;+ let previewRaf = null;+ let previewLast = 0;let busy = false;// ── Entry button ─────────────────────────────────────────────────────────@@ -264,6 +269,28 @@ export function initRoomMode(deps) {}}+ // Per-frame ghost driver: feed irl.js the live aim so the translucent stand-in+ // tracks the phone smoothly (the 120 ms HUD-readout tick would look stepped on+ // the 3D preview). Re-projects from the live compass + current slider/facing.+ function previewTick(ts) {+ if (!active) return;+ const dt = previewLast ? Math.min(0.1, (ts - previewLast) / 1000) : 0;+ previewLast = ts;+ const fix = getFix();+ const heading = getHeading ? getHeading() : { deg: 0, absolute: false };+ previewAim({ on: true, ready: !!(fix && fix.ready), headingDeg: heading.deg, distM, faceViewer, dt });+ previewRaf = requestAnimationFrame(previewTick);+ }+ function startPreview() {+ if (previewRaf != null) return;+ previewLast = 0;+ previewRaf = requestAnimationFrame(previewTick);+ }+ function stopPreview() {+ if (previewRaf != null) { cancelAnimationFrame(previewRaf); previewRaf = null; }+ previewAim({ on: false });+ }+async function enter() {if (active) return;let ok = false;@@ -280,6 +307,7 @@ export function initRoomMode(deps) {refreshBadge();placeBtn.focus();tickTimer = setInterval(refreshReadouts, 120); // live compass/fix readout, decoupled from the render loop+ startPreview();}function exit() {@@ -291,6 +319,7 @@ export function initRoomMode(deps) {hud.classList.remove('is-open');badge.classList.remove('is-shown');if (tickTimer) { clearInterval(tickTimer); tickTimer = null; }+ stopPreview();}async function place() {diff --git a/tasks/irl-hardening/H2-device-token-transport.md b/tasks/irl-hardening/H2-device-token-transport.mddeleted file mode 100644index 9636a7c91..000000000--- a/tasks/irl-hardening/H2-device-token-transport.md+++ /dev/null@@ -1,119 +0,0 @@-# H2 — Move the device-token credential out of URLs--> Epic IRL-Hardening · Size **M** · Touches `api/irl/pins.js`, `api/irl/interactions.js`,-> `api/irl/interactions-stream.js`, `src/irl.js`, `src/dashboard-next/pages/irl-*.js`.--## Goal--Stop sending the anonymous **device token** in URL query strings. It is a bearer-credential: presenting it reads a device's full pin **location history** and-interaction inbox. Today it rides as `?deviceToken=…` on `GET /api/irl/pins/mine`,-`GET /api/irl/interactions?mine=1`, the SSE stream, and `DELETE`. Query strings-land in platform access logs, browser history, and (for any cross-origin-sub-resource) the `Referer` header. Move the credential to a request **header**-(`x-irl-device`) — or the POST/DELETE body — so it never sits in a URL.--## Why it matters--If that token leaks from a log or history entry, an attacker replays it to-`/mine` and gets the exact GPS of every spot the user dropped a pin — i.e. where-the user physically was. For a solo tester that is their home and movements. The-in-app error-log path is already scrubbed (`redactUrl`, shipped), but the-platform's own access logs and the browser are outside that scrub. The only-durable fix is to keep the credential out of the URL entirely.--## Current state (verified)--- `api/irl/pins.js`: `/mine` branch reads `req.query.deviceToken`; the nearby read- reads `req.query.deviceToken` (only to compute `is_mine`); `DELETE` reads- `req.query.id` + `req.query.deviceToken ?? req.body?.deviceToken`.-- `api/irl/interactions.js`: `?mine=1` and `PATCH` read `req.query.deviceToken` /- `req.body.deviceToken`.-- `api/irl/interactions-stream.js`: reads `req.query.deviceToken` on connect.-- `api/_lib/http.js` `cors()` already allow-lists custom request headers in- `access-control-allow-headers` — **add `x-irl-device` to that list**.-- Client device token is generated/stored client-side and appended to these URLs- in `src/irl.js` and the dashboard pages.--## What to build--### 1. Server — accept the token from a header first, body second, query last--Add one helper (e.g. in `api/_lib/irl-auth.js` or inline) and use it everywhere a-device token is read:--```js-// Header is preferred (never logged in the URL); body for POST/DELETE; query is-// a DEPRECATED fallback kept for one release so in-flight clients don't break.-export function readDeviceToken(req) {- const h = req.headers['x-irl-device'];- const fromHeader = Array.isArray(h) ? h[0] : h;- const tok = fromHeader || req.body?.deviceToken || req.query?.deviceToken || '';- return (typeof tok === 'string' && tok.length) ? tok : null;-}-```--Replace every `req.query.deviceToken` / `req.body?.deviceToken` read in the four-files with `readDeviceToken(req)`. Add `x-irl-device` to-`access-control-allow-headers` in `cors()`. **SSE caveat:** `EventSource` cannot-set headers — for `interactions-stream.js` keep accepting the token via the body-of a companion POST handshake, or document that the stream stays on the query-param but the token in it is short-lived/rotatable (decide and write it down; do-not leave it ambiguous).--### 2. Client — send the header, drop the query param--In `src/irl.js` and `src/dashboard-next/pages/irl-*.js`, change the `fetch` calls-for `/mine`, `interactions?mine=1`, `PATCH`, and `DELETE` to send-`headers: { 'x-irl-device': token }` (and move DELETE's token into the body)-instead of appending `?deviceToken=`. Keep the nearby read's `is_mine` working by-sending the header there too.--### 3. Deprecation window--Leave the query fallback in for exactly one release, logging a one-line-`console.warn('[irl] deprecated deviceToken query param')` (no token value) when-it's hit, then remove it in a follow-up. Note the removal date in the task's-out-of-scope follow-up so it isn't forgotten.--## Data / API changes--- No DB change. Request-transport change only.-- `cors()` `access-control-allow-headers` gains `x-irl-device`.--## Acceptance checklist--- [ ] All four endpoints read the token via `readDeviceToken(req)`; header wins.-- [ ] Client sends `x-irl-device` (and body for DELETE); no endpoint receives the- token as a query param in the Network tab.-- [ ] `cors()` advertises `x-irl-device`; preflight passes cross-origin.-- [ ] Query fallback still works (one-release window) and warns without logging the value.-- [ ] H1 suite extended: a `/mine` request with the token in a header returns the- device's pins; with no token returns 400; the token never appears in any- logged/echoed string.-- [ ] `npm test` + `npm run typecheck` green; no console errors in the app.--## Out of scope--Rotating/expiring device tokens (future), and the proof-of-presence binding on the-public read (**H3**). Follow-up: remove the deprecated query fallback next release.--## Verify--`npm run dev`, place a pin anonymously, open `/dashboard/irl-placements`: the-Network tab shows the `x-irl-device` header on `/mine` and **no `deviceToken=` in-any URL**. Delete a pin — succeeds via body token. Confirm the device's pins load.--<!-- 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/irl-hardening/H2-device-token-transport.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/irl-hardening/H3-proof-of-presence-read.md b/tasks/irl-hardening/H3-proof-of-presence-read.mddeleted file mode 100644index b63b42aa0..000000000--- a/tasks/irl-hardening/H3-proof-of-presence-read.md+++ /dev/null@@ -1,121 +0,0 @@-# H3 — Bind the nearby read to a genuine location fix--> Epic IRL-Hardening · Size **L** · Touches `api/irl/pins.js`, a new-> `api/irl/fix-token.js` (or `api/_lib/irl-presence.js`), and `src/irl.js`.--## Goal--Close the one structural hole left in the discovery model: the nearby read trusts-**caller-supplied** coordinates. Anyone can query `GET /api/irl/pins?lat=&lng=`-for *any* point on earth they aren't standing at, and (within the radius cap +-rate limit) harvest the pins there. Bind the read to a short-lived, server-issued-**proof-of-presence token** minted from a real geolocation fix, so the feed only-answers for where the caller actually is — making a remote sweep of a specific-person's pins, or a city-wide grid scrape, structurally hard rather than just-rate-limited.--## Why it matters--The product promise is "you stumble on an agent by walking up to it." That only-holds if you can't *browse* locations from your couch. Today the radius cap (60 m)-and IP rate-limit (60/min) slow a sweep but don't stop a patient one, and they do-nothing against someone who knows roughly where the victim tested and reads that-exact 60 m circle. Proof-of-presence turns "query anywhere" into "query where you-are," which is the actual product contract.--## Current state (verified)--- `api/irl/pins.js` nearby branch: parses `lat`/`lng` from the query, clamps- `radius` to `[10,60]`, IP rate-limits via `limits.publicIp`, returns the coarse- allow-list projection. No binding between the caller and the coordinates.-- The client already holds a real fix (`gpsState` in `src/irl.js`,- `navigator.geolocation.watchPosition`) — so minting a token from a fresh fix is- cheap and invisible to a legitimate user.-- `api/_lib/crypto.js` exists (used by the cron for `constantTimeEquals`); reuse- it / `node:crypto` HMAC for signing. No new third-party dependency.--## What to build--### 1. Mint endpoint — `POST /api/irl/fix-token`--Input: the client's current `{ lat, lng, accuracy }`. Output: a compact signed-token bound to a **coarse cell** (e.g. geocell-7, ~150 m) + an issue timestamp,-HMAC-signed with a server secret (`IRL_FIX_SECRET`), TTL ~2–5 min:--```js-// token = base64url(payload) + '.' + base64url(hmacSHA256(payload, IRL_FIX_SECRET))-// payload = { cell7: encodeGeohash(lat,lng,7), iat: nowSec }-```--Rate-limit minting per IP/device. The token authorizes reads whose caller-claimed-point falls inside (or adjacent to) `cell7`, for its TTL — enough to keep polling-as you walk, not enough to bank tokens for a sweep.--### 2. Enforce on the nearby read--`GET /api/irl/pins` requires a valid, unexpired fix token (header `x-irl-fix`,-pairs with H2's `x-irl-device`). Verify the signature, check TTL, and check the-requested `lat`/`lng` resolve to the token's `cell7` (or an immediate neighbor, so-a viewer near a cell edge still works). On failure → `401 fix_required` with a-designed body the client turns into "Getting your location…/Location needed".--### 3. Graceful degrade (don't break the product)--- A user with location **denied** can't mint a token → the read returns- `fix_required`; the client shows the existing location-permission designed state- (coordinate with **H8**), never a blank screen.-- Keep a clearly-scoped **dev/preview bypass** (`IRL_FIX_SECRET` unset → skip- enforcement) so local/sandbox testing isn't gated, but ensure production sets- the secret and enforces. Log which mode is active once at cold start.-- Tighten the IP rate-limit on the read now that every legit caller mints first;- a token-less or bad-token flood is cheap to reject.--### 4. Client--In `src/irl.js`, mint a fix token whenever a fresh GPS fix lands (debounced), cache-it, attach `x-irl-fix` to every `loadNearbyPins` fetch, and re-mint on 401 or when-the cell changes. This is invisible to the user — they already granted location.--## Data / API changes--- New `POST /api/irl/fix-token` → `{ token, expires_in }`. Register in `vercel.json`.-- New env `IRL_FIX_SECRET` (set in Vercel prod + preview). Unset → enforcement off- (dev). Document in the deploy notes.-- `GET /api/irl/pins` now requires `x-irl-fix` in production.--## Acceptance checklist--- [ ] `POST /api/irl/fix-token` mints a TTL-bounded, HMAC-signed, cell-bound token.-- [ ] Nearby read rejects a missing/expired/forged token, or one whose claimed- point is outside the token cell (+neighbors), with `401 fix_required`.-- [ ] A legitimate walking user polls seamlessly (token re-mints on cell change).-- [ ] Location-denied users hit the designed permission state, not an error.-- [ ] Dev bypass works with `IRL_FIX_SECRET` unset; prod enforces; mode logged once.-- [ ] H1 suite extended: forged token rejected; valid token for cell A can't read cell Z.-- [ ] `npm test` + `npm run typecheck` green.--## Out of scope--Per-account abuse scoring + anomaly alerting on sweep-shaped traffic (**H7**), and-device-token transport (**H2**, a prerequisite for the shared header pattern).--## Verify--`npm run dev` with `IRL_FIX_SECRET` set locally: confirm the read 401s without a-token, mints a token from your fix, then returns pins; spoofing a far-away lat/lng-with a local-cell token is rejected. With the secret unset, the read works-unchanged (dev bypass).--<!-- 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/irl-hardening/H3-proof-of-presence-read.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/irl-hardening/H8-designed-states-a11y.md b/tasks/irl-hardening/H8-designed-states-a11y.mddeleted file mode 100644index 4c0d59fb7..000000000--- a/tasks/irl-hardening/H8-designed-states-a11y.md+++ /dev/null@@ -1,114 +0,0 @@-# H8 — Designed states, permission onboarding & accessibility--> Epic IRL-Hardening · Size **M** · Touches `src/irl.js`, `pages/irl.html`,-> `src/irl/onboarding.js`, and `src/shared/state-kit.js` usage across IRL surfaces.--## Goal--Every IRL state — especially the privacy- and sensor-related ones — is **designed,-helpful, and accessible.** No blank screens, no dead ends, no mystery permission-prompts. The user always knows what's happening, why a permission is needed, what-their privacy posture is, and how to move forward. This is the polish layer that-makes `/irl` feel like a flagship product instead of a demo.--## Why it matters--A phone-camera AR product lives or dies on its first 30 seconds: camera, motion,-and location permissions, often on iOS Safari (which needs an explicit user-gesture for motion and has no WebXR). Get the onboarding wrong and the user sees a-frozen black screen and leaves. Get the privacy states wrong and they don't trust-it. Best-possible UX means every one of these moments is intentional.--## Current state (verified)--- `src/irl/onboarding.js` exists (permission flow scaffolding); `src/shared/state-kit.js`- provides skeleton/empty/error/retry shells used elsewhere in the app.-- `src/irl.js` watches GPS, runs the camera passthrough + gyro look, has an- avatar-load error overlay (`showAvatarLoadError`), and a poll/WS fallback for- presence (`src/irl-net.js` `unavailable`/`failed` statuses).-- Coverage is uneven: not every sensor-denied / no-fix / offline / privacy state is- a first-class designed state, and the new privacy surfaces (H3 `fix_required`, H4- consent, H5 controls) need states too.--## What to build--### 1. The full state matrix — each one designed--For `/irl`, ensure a designed, actionable state for **every** case:--| State | What the user sees / can do |-|---|---|-| Camera permission needed / denied | Why it's needed + how to re-enable (with iOS Safari path), Retry |-| Motion permission (iOS gesture) | A tappable "Enable motion" affordance (iOS requires the gesture) |-| Location permission needed / denied | Why + re-enable steps; degrades gracefully (no crash) |-| Acquiring GPS fix (no fix yet) | A calm "Getting your location…" with a skeleton, not a freeze |-| `fix_required` from the read (H3) | "We need your location to show nearby agents" + enable CTA |-| No nearby agents (empty) | "No agents here yet — be the first" + Place CTA, not a void |-| Offline / realtime unavailable | Presence hidden, discovery still polling; honest pill, not a spinner loop |-| Unsupported device / no WebGL | Clear fallback message; never a blank canvas |-| Privacy posture (always visible) | A small, persistent indicator: "Discovery is local-only · presence is anonymous" linking to H5's privacy center |--Reuse `state-kit.js`; do not hand-roll one-off markup. Loading uses skeletons, not-bare spinners.--### 2. Permission onboarding flow--Harden `src/irl/onboarding.js` into a guided, resumable sequence (camera → motion-→ location), each step explaining *why* before the native prompt, each handling-deny without trapping the user, and the iOS motion step gated behind a real tap.-Re-entrant: a user who denied then changed OS settings can retry without reload.--### 3. Accessibility pass (the whole surface)--- Semantic landmarks; every control has an accessible name (ARIA where needed).-- Full keyboard path: open/close sheets, place, tap a pin, navigate cards, reach- the privacy center — all without a pointer; visible focus rings.-- Respect `prefers-reduced-motion` (the ghost pulse, transitions, any camera- easing) — provide a calm static alternative.-- Color contrast ≥ WCAG AA on every chip/badge/state, including over the camera- feed (use scrims/backplates so text stays legible on any background).-- Screen-reader announces state changes (placed, error, permission needed) via a- polite live region.--### 4. Microinteraction polish--Hover/active/focus on every interactive element; intentional enter/exit on sheets-and pins (opacity/transform, GPU-friendly); no jarring pops. The privacy indicator-and consent affordances feel native, not bolted on.--## Acceptance checklist--- [ ] Every state in the matrix is a designed `state-kit` state with a working action.-- [ ] iOS Safari: motion permission gated behind a gesture; camera/location denies- degrade gracefully; tested on a real device or accurate emulation.-- [ ] Persistent, legible privacy indicator linking to the privacy center.-- [ ] Full keyboard operability + visible focus; `prefers-reduced-motion` honored;- AA contrast over the camera feed; live-region announcements.-- [ ] 320 / 768 / 1440 px clean; no console errors or warnings from our code.-- [ ] `npm test` + `npm run typecheck` green.--## Out of scope--The privacy *backend* (H3/H5) and consent *logic* (H4) — H8 designs and wires their-**states and accessibility**, not their server behavior.--## Verify--`npm run dev` → `/irl` on a throttled mobile profile: deny each permission in turn-and confirm a designed, recoverable state every time; tab through the entire-surface with no mouse; toggle reduced-motion; confirm the privacy indicator is-always visible and links to the privacy center.--<!-- 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/irl-hardening/H8-designed-states-a11y.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/irl-privacy/02-discovery-onboarding-empty-state.md b/tasks/irl-privacy/02-discovery-onboarding-empty-state.mddeleted file mode 100644index f9d702faa..000000000--- a/tasks/irl-privacy/02-discovery-onboarding-empty-state.md+++ /dev/null@@ -1,86 +0,0 @@-# 02 — Discovery onboarding + the designed empty state--> Size **M** · `src/irl.js` (`updateNearbyBadge`, first-run flow), `src/irl/onboarding.js`,-> `pages/irl.html`, `src/irl.css`. The single biggest UX task in the epic.--## Goal--Teach the "stumble upon" mental model so a first-time visitor in an empty area-understands the world is *working*, not broken. With a tight 40 m radius and no-list/map, "nothing on screen" is the **common** first experience — it must read as-"keep exploring," never as a dead feature.--## Why it matters--We deliberately removed the radar/roster. That is the safety win — and the UX-risk. Top location apps that hide a map (by choice or by privacy) live or die on-how well they set the expectation: *you find things by being somewhere, not by-browsing.* If the empty state is a bare badge, users bounce and conclude /irl is-empty everywhere. The onboarding is the product.--## Current state (real lines)--- `src/irl.js` `updateNearbyBadge()` writes `#irl-nearby-badge`: populated →- `"N nearby"`; GPS-ready + none → `"No agents nearby — be the first to pin here"`;- no fix → hidden. That badge is the *entire* current empty-state story.-- `src/irl/onboarding.js` owns the sensor-permission prompts (camera / motion /- location) and the retry copy.-- First fix triggers `startPinSync()` → `startPinPolling()`.--## What to build--1. **A first-run explainer** (once per device; store a flag in `localStorage`,- same pattern as `SHARE_GHOST_KEY`). A short, beautiful card shown after- permissions are granted and before/over the empty scene:- - One line on the model: *"Agents are hidden in the world around you. Walk- around and look through your camera — when you're near one, it appears."*- - One line that it's mutual: *"Drop your own agent anywhere; someone who comes- to that spot will find it."*- - Reassure on privacy (this builds trust, see task 08): *"We never show a list- of where agents are — not even to you."*- - A single primary action ("Start exploring") and a "Place an agent here" CTA.-2. **Upgrade the empty state** from a badge string to a *designed* state: a- centered, low-contrast prompt in the AR view with a gentle looping hint- ("Look around 👀 • or be the first to pin here") and the Place CTA. Distinct- visual from the error state (task 06 owns error/permission copy).-3. **Populated affordance.** When ≥1 agent is in range, retire the empty prompt- and keep the count subtle — never a list. (The count is fine; a roster is not.)-4. Respect `prefers-reduced-motion` for any looping hint. Keyboard + screen-reader- accessible (aria-live polite on the state, not spammy — only on transition).--## Acceptance checklist--- [ ] First-run explainer shows once per device, dismissible, re-openable from a- small "?" affordance; never blocks the camera permanently.-- [ ] Empty state is a designed component (not just badge text) that communicates- "keep exploring" + offers "Place an agent here."-- [ ] Transitions empty ⇆ populated are smooth (opacity/transform), no pop.-- [ ] Copy never implies a browsable list/map of agents exists.-- [ ] `prefers-reduced-motion` honored; aria-live announces state changes once.-- [ ] Clean at 320 / 768 / 1440; no console errors/warnings.-- [ ] Holder-readable `data/changelog.json` entry (tag: improvement) + `build:pages`.--## Out of scope--Permission-flow polish and error states (task 06), the arrival cue (task 03).--## Verify--`npm run dev` → /irl on a fresh profile (clear `localStorage`): grant permissions,-see the explainer once, see the designed empty state with no agents, then seed one-in range (`__irlSeedPins(1)` per [memory: irl-perf-e2]) and confirm the empty-prompt retires cleanly.--<!-- 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/irl-privacy/02-discovery-onboarding-empty-state.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/irl-privacy/07-e2e-and-regression-tests.md b/tasks/irl-privacy/07-e2e-and-regression-tests.mddeleted file mode 100644index f66b3278f..000000000--- a/tasks/irl-privacy/07-e2e-and-regression-tests.md+++ /dev/null@@ -1,85 +0,0 @@-# 07 — E2E + regression coverage that locks the invariant in CI--> Size **M** · `tests/api/*`, `tests/*` (vitest), `tests/e2e/*` (playwright), and a-> tiny dev seam in `src/irl.js` if needed for deterministic GPS in a headless run.--## Goal--Turn the privacy invariant and the new UX behaviors into **automated** guarantees so-no future change can quietly reopen the roster or regress discovery. The Vercel-build is the only automated gate ([memory: github-actions-unavailable]), so these-must run under `vitest run` / `playwright test` locally and in that build.--## Why it matters--Task 01 proves the lockdown *once, by hand*. This makes it permanent. The room-anchor-work already shares these files; a later refactor could re-add a pin broadcast or a-window feed without anyone noticing — unless a test fails. Safety regressions must be-loud.--## Current state (real lines)--- `tests/api/irl-pins-location-guards.test.js` already asserts: no bbox/window feed,- the hard radius cap (`Math.min(60, …)`), rate-limiting, and no owner-id projection.- Build on it; don't duplicate.-- `tests/api/irl-pins-room.test.js` covers room-frame persistence + projection.-- Presence/reaction units exist (`tests/irl-*`); `IrlRoom` is presence+reactions only.-- Playwright suite lives under `tests/e2e/`; pre-start a dedicated dev server per- [memory: vitest-cold-import-contention].--## What to build--1. **Realtime "no pins" regression (unit/integration).** Boot `IrlRoom` (or assert- on its schema/handlers) and prove `state.pins` is never populated and there is no- `applyPublish`/`_loadPins`/pin-publish path. A structural test that fails if a pin- broadcast is reintroduced.-2. **API guards — extend** `irl-pins-location-guards`: add the cross-user `?mine`- attempt (guessed `deviceToken` → no data) and assert `report`/calibrate/edit no- longer call any publish module (the modules are gone; assert no import).-3. **Pure-logic units** for the new modules from tasks 03/04:- `proximity-cue` (new arrivals, debounce, no re-fire on refresh) and the- hysteresis band (enter 40 / exit ~55 / debounce). These are pure → cheap + fast.-4. **E2E happy path (Playwright, headless).** With a deterministic GPS seam- (inject fixed `gpsState` or mock `geolocation`), and seeded pins- (`__irlSeedPins`): assert (a) an out-of-range pin does **not** render, (b) moving- into range renders it, (c) the empty-state explainer/empty prompt appears with- zero pins, (d) no console errors. Keep it hermetic (no live network/DB).-5. **E2E privacy assertion.** In the same run, assert the page never holds a list of- pin coordinates outside the in-range set (inspect the live `nearbyPins`/DOM) and- that the WS client state exposes no pins.--## Acceptance checklist--- [ ] A structural test fails if `IrlRoom` ever re-syncs pins or a pin-publish path returns.-- [ ] `?mine` cross-user attempt covered → returns no data.-- [ ] `proximity-cue` + hysteresis band unit-tested (pure).-- [ ] Playwright happy-path: out-of-range hidden, in-range renders, empty state shown,- no console errors — hermetic.-- [ ] Playwright privacy assertion: no out-of-range coordinates in client state/DOM.-- [ ] `vitest run` + `playwright test` green locally; suite stays within the- calibrated timeouts ([memory: vitest-cold-import-contention]).--## Out of scope--The features themselves (01–06) — this task only *locks them in*. Don't lower any-vitest timeout.--## Verify--`npx vitest run irl` and the new e2e spec both green; then temporarily reintroduce a-fake pin broadcast in a scratch branch and confirm the structural test goes red-(then discard the scratch change).--<!-- 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/irl-privacy/07-e2e-and-regression-tests.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/irl-production/15-launch-readiness-report.md b/tasks/irl-production/15-launch-readiness-report.mdnew file mode 100644index 000000000..be626a673--- /dev/null+++ b/tasks/irl-production/15-launch-readiness-report.md@@ -0,0 +1,147 @@+# IRL Launch-Readiness Report — Task 15 (deploy verify + QA gate)++**Date:** 2026-06-19 · **Verdict: 🔴 NOT READY — launch blocked.**+**Gate outcome:** The gate did its job and caught a production failure. Task 15 is+**not** complete; the task file is intentionally retained.++---++## Headline++Two of the six IRL endpoints are **returning HTTP 500 on every path in production**:++| Endpoint | Live prod status | Notes |+|---|---|---|+| `/api/irl/pins` | 🔴 **500** | Fails on the public nearby read, `/mine`, `?mine=1`, **and** `POST`. |+| `/api/irl/interactions` | 🔴 **500** | Same failure shape. |+| `/api/irl/agent-card` | 🟢 200/400/404 | Validates input, reads `irl_pins` correctly (clean `404` for a missing pin/agent). |+| `/api/irl/agent-summary` | 🟢 401 | Auth-gates before DB — correct. |+| `/api/irl/interactions-stream` | 🟢 401 | Auth-gates before DB — correct. |+| `/api/irl/report` | 🟢 405 | POST-only; `GET` correctly rejected. |++**Crucially, none of the six 404.** The stale-deploy-missing-code risk this gate+was created to catch (newer `/api/irl/*` 404ing from a deploy that predates them)+is **absent** — the deployed build contains all six handlers and returns our+structured `wrap()` error envelope, not a Vercel 404. The problem is a **runtime+failure**, not a missing route.++---++## Root cause (narrowed by elimination against live prod)++`/api/irl/pins` 500s on **all four** method/path variants. The only code every one+of those variants shares — in particular `POST`, which skips the GET-only rate+limiter at `api/irl/pins.js:788` — is the very first statement in the handler:++```+api/irl/pins.js:779 await ensureTable();+```++`ensureTable()` (`api/irl/pins.js:344`) runs `CREATE TABLE IF NOT EXISTS` + ~20+`ALTER TABLE … ADD COLUMN IF NOT EXISTS` + `CREATE INDEX` statements. `interactions.js`+has the **same** DDL-on-every-request pattern (`api/irl/interactions.js:126`) and+fails identically. Meanwhile `agent-card.js`, which **reads `irl_pins` without any+DDL**, succeeds — returning a clean `404 "pin not found"` for `?pin=1`, which proves+the production database and the `irl_pins` table are reachable and queryable.++**Conclusion:** the failure is the DDL in `ensureTable()` throwing at runtime in+production — not infra-wide DB loss, not missing endpoints. Most probable causes,+in order:++1. **DDL-permission / lock-timeout in prod.** The prod Neon role cannot execute+ `ALTER TABLE` / `CREATE INDEX` (or the `ACCESS EXCLUSIVE` lock times out under+ the current concurrent-cold-start load). This explains why a DDL-free read+ (`agent-card`) works while every DDL-first handler 500s.+2. **A regression on a not-yet-deployed fix.** `main` advanced through several+ `IRL: pins hardening` commits *during this session*; if prod is built from a+ commit whose `ensureTable()` has a statement that errors and the fix is only on+ newer `main`, prod 500s until redeploy.++I could not disambiguate (1) vs (2) from this sandbox — see "Could not verify".++### Recommended fix (for whoever holds prod access)+- Pull the server-side error for any of the refs below from the Vercel function+ logs — they name the exact failing statement (`column … does not exist`,+ `permission denied for relation irl_pins`, `canceling statement due to lock+ timeout`, etc.) and decide (1) vs (2) immediately.+- If permission/lock: move the DDL out of the per-request hot path into a one-time+ migration (run with a privileged role at deploy time); `ensureTable()` should+ become a no-op assertion in prod, not the thing that gates every read.+- If stale deploy: redeploy `main` and re-run the probes below.++**Reproduce (copy-paste):**+```bash+curl -s -w '\n%{http_code}\n' "https://three.ws/api/irl/pins?lat=40.7&lng=-74&radius=40"+curl -s -w '\n%{http_code}\n' -X POST -H 'content-type: application/json' -d '{}' "https://three.ws/api/irl/pins"+curl -s -w '\n%{http_code}\n' "https://three.ws/api/irl/interactions?agent=THREEsynthetic1111"+```+Server-side error refs captured during this gate (quote to Vercel logs):+`d4ec29fa7de09132`, `e2751fecb5285305`, `e194ed0269e08cfc`, `625865f495ca75c2`,+`865bfd2c652c05c4`, `34055f15220a846b`, `e2751fecb5285305`.++---++## What IS verified++- **vercel.json wiring — all six present and correctly ordered.** Each endpoint has+ both a `functions` entry (`vercel.json:172–189`) **and** a route+ (`vercel.json:2016–2041`). `/api/irl/pins/mine` is listed before `/api/irl/pins`+ (specific-before-general), and no `/api/(.*)` catch-all precedes the IRL block, so+ nothing shadows them (the `pump-action-shadows-dedicated-files` trap does not apply+ here).+- **No esbuild clobber.** `head` of every `api/irl/*.js` is source (a `/**` comment),+ not `__defProp`/`createRequire`. The `vercel-build-clobbers-api` trap is clear.+- **Handlers are healthy as source.** All six pass `node --check` (syntax) and export+ a default handler.+- **Production DB is up.** `agent-card?pin=1` → clean `404`; `?id=…` → clean `404`.++---++## Could NOT verify (honest gaps — environment-constrained)++1. **Automated gates (`npm test`, `npm run typecheck`, `npx esbuild`,+ `npm run build:pages`) — NOT RUN.** This sandbox is memory-starved: ~16 GB total+ with **~300 MB free**, and **13+ concurrent agent `npm install` processes** were+ OOM-killing each other (and every install attempt of mine, `rc=143`). A clean+ dependency tree could not be produced even in an isolated git worktree. The only+ dependency-free gate that ran: `node --check` on all six handlers (clean) and the+ clobber check (clean). **These gates must be re-run in a quiescent environment+ before launch** — their result here is *unknown*, not *green*. (A `node_modules`+ left half-installed by the contention was removed.)+2. **Deployed commit SHA — UNCONFIRMED.** The Vercel CLI is not authenticated in this+ sandbox and no response header exposes the build SHA, so prod-vs-`main` parity+ could not be proven. `main` itself moved several commits *during* this session+ (concurrent agents), so the deploy target is in motion.+3. **Real-device matrix (iOS Safari / Android Chrome) — NOT EXECUTED.** No physical+ devices and no camera/WebXR/sensor access from this sandbox. The AR/XR/GPS paths+ cannot be exercised headlessly. Remaining manual steps (unchanged from the task):+ camera permission → Camera AR → Pin here (no-GPS then GPS) → pan-anchoring →+ inspect → x402 pay reachable → rotate → background/foreground; Android adds the+ WebXR "Place on floor" + AR↔XR toggle; both add 320 px, keyboard/SR, reduced-motion.+4. **Live console audit on `/irl` — NOT EXECUTED.** Requires a browser driving the+ live page; not possible from here. Must be done manually, distinguishing real+ errors from the known benign baseline (insights 404, HMR WS, GPU-stall,+ rapier/colyseus).+5. **End-to-end smoke (place → persist → appear-in-range → inspect → report → reap).**+ Blocked outright: the place/persist/read steps all traverse the **500ing** `pins`+ endpoint, so the flow cannot complete in prod until the blocker is fixed.++---++## Definition of Done — status++- [ ] Automated gates green — **NOT RUN** (environment OOM; must re-run clean).+- [x] All six endpoints verified live — **done, and they revealed the blocker.**+- [ ] Six endpoints healthy in prod — **2/6 are 500.**+- [ ] Deploy built from the containing commit SHA — **unconfirmed.**+- [ ] Real-device matrix — **not executed (no devices); steps documented.**+- [ ] Live console clean — **not executed (no browser to live prod).**+- [ ] E2E smoke — **blocked by the `pins` 500.**++## Gate decision++**Do not launch.** Fix the `ensureTable()`/DDL 500 on `pins` + `interactions`,+confirm prod is built from the fix, re-run the automated gates in a quiescent+environment, then exercise the device matrix and console audit. Re-run this gate;+delete Task 15 and its report only when every box above is genuinely checked.+</content>diff --git a/tasks/irl-room-anchor/R1-place-around-me.md b/tasks/irl-room-anchor/R1-place-around-me.mddeleted file mode 100644index 798d95f72..000000000--- a/tasks/irl-room-anchor/R1-place-around-me.md+++ /dev/null@@ -1,163 +0,0 @@-# R1 — "Place agents around me" (room authoring UI)--> Epic R · Size **L** · Edits `src/irl.js`, `pages/irl.html`, `src/irl.css`.--A mode in `/irl` where you stand in a room and **drop agents at fixed real-world-spots around you by aiming and setting a distance**. Point the phone at the-couch, set ~3 m, tap Place — an agent appears sitting there, facing you. Turn-away and it's gone; turn back and it slides into frame exactly where you left it.-Place three more behind you; the left wall stays empty. Every agent is anchored-into one shared **room** so the engine (already built) renders the layout-identically for the next person who opens `/irl` here.--## Why it matters--The whole engine — math, persistence, projection, world-locked render — is-already shipped and green, but **a user cannot create a room pin through the-product**. R1 is the authoring surface that turns the engine into a feature. It-must feel as good as dropping a pin in a top-tier map app: instant, legible,-forgiving.--## Current state (real symbols — verify lines, they shift under concurrent edits)--- **Own-avatar placement flow** in `src/irl.js`: `setLocked(true)` → `anchorGpsPin()`- (derives lat/lng from the avatar's world position + compass heading) →- `openCaptionPanel(lat, lng, headingDeg, source)` → `commitPin(...)` →- `savePin(lat, lng, heading, caption, anchor)` which `POST`s `/api/irl/pins`.- This places **one** "my avatar." R1 adds a distinct **multi-agent room** flow.-- **Room engine helpers** (use, don't reinvent): `pinRoom(pin)`, `pinWorldPos(pin)`- in `src/irl.js`; `placeAround`, `roomOriginWorld`, `agentWorldPosition` in- `src/irl/room-anchor.js`.-- **Live pose** available now: `gpsState` (`{ lat, lng, ready, accuracy }`),- `lastCompassHeading`, `cameraYaw`, `prefersAbsOrientation`, `compassToYaw`.-- **Avatar/agent identity**: `_currentAvatarId`, `_currentAgentId`, `nameEl`,- `resolveAvatarUrl(id)`, `_deviceToken`. Reuse the existing avatar picker the- page already uses for the own-avatar.-- **Permissions**: `ensurePermission('camera'|'motion'|'location')`,- `needsMotionGesture`, `setPermissionState` in `src/irl/onboarding.js`.-- **Pin interaction surfaces** already built: `openPinSheet(pin)`, the A3- calibrate gesture, remove via `DELETE /api/irl/pins`. Reuse for editing a- placed room agent (R2 extends calibrate to the room origin).-- **DEV harness** to develop against without a phone: `window.__irlSeedRoom()` /- `window.__irlRoomCheck()`.--## What to build--### 1. Room session state--A single in-memory room the placements share, plus durable resume:--```js-// null until the first placement of a session establishes the room-let activeRoom = null; // { id, originLat, originLng, originYawDeg, createdAt, count }-```--- **Establish on first place:** capture `gpsState.lat/lng` as the origin and set- `originYawDeg = 0` when an absolute compass heading is available- (`prefersAbsOrientation` / a valid `webkitCompassHeading`) — the true-north- frame. If only page-relative orientation exists, set `originYawDeg` to the- current heading and tag placements `gyro-gps:rel` (R2 reconciles cross-user).-- **Room id:** derive a stable slug, e.g. `r-${geocell8}-${shortRand}` matching- `^[a-z0-9-]{1,64}$`. One room per (place + session); reuse `activeRoom` for- every subsequent drop until the user exits room mode.-- **Resume:** persist `activeRoom` to `localStorage` keyed by coarse geocell so- returning to the same spot in a later session keeps adding to the same room- (and so "my pins" can group by room). On load, if the nearby read returns pins- with a `room_id` this device owns at this location, adopt that room.--### 2. Entry + mode--- Add a primary **"Place agents"** affordance to the `/irl` action bar (alongside- the existing Pin/Place controls in `pages/irl.html`). Tapping it enters- **room placement mode** (`body.classList.add('irl-room-mode')`), which requires- camera + motion + location (gate via `ensurePermission`, reuse the existing- permission cards — never a dead end).-- Entering shows the **aim HUD** (next section). A clear **Done** exits the mode- back to normal viewing.--### 3. Aim + place HUD (the core interaction — make it excellent)--- **Reticle:** a centered, crisp aiming reticle over the camera feed marking where- the agent will land. Subtle pulse; CSS `transform`/`opacity` only.-- **Live ghost preview:** render the selected avatar (or a lightweight proxy) at- the prospective world position each frame using `placeAround` →- `agentWorldPosition`, so the user sees the agent *in the room* before- committing. Semi-transparent until placed. This is the "screenshot-worthy"- moment — invest here.-- **Distance control:** a thumb-reachable slider (0.5–8 m, default 2.5 m) with a- live "2.5 m" readout; the ghost moves as it changes. Optional tap-to-set by- tapping the floor if a WebXR hit-test is available (R3), else slider only.-- **Bearing = live compass heading.** The ghost sits along the current heading;- turning the phone moves where it will drop. Show a compass chip ("NE · 47°").-- **Facing:** agent faces the placer by default (`faceViewer: true`); offer a- quick toggle to face-away.-- **Place button:** large, thumb-reachable. On tap: build the `room` block via- `placeAround`, `POST /api/irl/pins` through a room-aware save (extend `savePin`- or add `saveRoomPin`), spawn it immediately via the existing- `spawnNearbyPin`/render path so it's world-locked at once, bump- `activeRoom.count`, and give a crisp confirm (scale-in + optional haptic- `navigator.vibrate?.(10)`; no fake timers).-- **Room badge:** "3 agents in this room" with the room name; tap to list/manage.--### 4. Multi-place, edit, move, remove--- After a place, stay in aim mode so the next agent can be dropped without- re-entering. A subtle list/dots show what's placed.-- **Tap a placed agent** → `openPinSheet(pin)` for caption/avatar/remove; the A3- calibrate gesture nudges a single agent. (R2 adds "move the whole room.")-- Remove uses the existing owner-gated `DELETE /api/irl/pins`. Update- `activeRoom.count` and the badge.--### 5. Every state designed--- **No GPS fix yet:** aim HUD shows "Finding your spot…" with the live accuracy;- Place is disabled until `gpsState.ready`. Never silently drop at (0,0).-- **Permission denied** (camera/motion/location): reuse the onboarding cards with- the exact recovery steps; Place stays disabled with a reason.-- **Loose lock** (poor compass / large GPS accuracy): show the honest amber state- (reuse the confidence-ring language) and the `gyro-gps:rel` warning copy that- already exists — placement still works, cross-user bearing may drift.-- **POST rejected** (area_full / pin_limit / rate / content / network): surface- the server's designed message (the `saveErrorFallback` map already exists);- keep the ghost so the user can retry without re-aiming.-- **Empty room** (mode entered, nothing placed): a one-line coach — "Aim at a- spot and tap Place to drop your first agent."--### 6. UX polish (the quality bar)--- Hover/active/focus on every control; full keyboard path (Tab to Place, Enter to- drop, Esc to exit); ARIA labels on reticle/slider/Place/Done; `aria-live` on the- room badge count.-- Responsive at 320 / 768 / 1440; thumb-zone layout on mobile; controls clear of- the iOS home indicator.-- Respect `prefers-reduced-motion` (no pulse/scale for those users).-- Reuse existing design tokens / CSS vars in `src/irl.css`; no new ad-hoc colors.--## Definition of done--- A user can enter room mode, place several agents at distinct bearings/distances- around them, see each lock to its real-world spot (turn away → gone, turn back →- there), edit/move/remove them, and exit — all reachable from `/irl` nav.-- A second device (or a reload) loading `/irl` at the same location renders the- same layout via the REST proximity read (verify with two browser contexts +- the seed harness; full cross-device is an R5 on-device check).-- Placements POST the correct `room` block; `placeAround` is the only geometry- source; any new pure helper has a unit test.-- All six states above are implemented and reachable. No console errors/warnings.-- `npm run typecheck` clean, `npm test` green, `vite build` clean.-- Changelog entry appended to `data/changelog.json` (tag `feature`) once the mode- is user-visible. On-device acceptance handed to R5.--<!-- 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/irl-room-anchor/R1-place-around-me.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/next-gen-trading/01-rug-honeypot-firewall.md b/tasks/next-gen-trading/01-rug-honeypot-firewall.mdnew file mode 100644index 000000000..f65a95499--- /dev/null+++ b/tasks/next-gen-trading/01-rug-honeypot-firewall.md@@ -0,0 +1,118 @@+# Task 01 — Rug/Honeypot Simulation Firewall (pre-trade safety engine)++> **Operating bar (applies to the whole task).** You are a senior engineer + product+> thinker building three.ws to beat the best in the world. Be genuinely innovative — this+> must be something users can't get elsewhere, not a clone. No mocks, no fake/sample data,+> no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire it 100% end-to-end with+> REAL APIs and real on-chain data. Every state designed (loading/empty/error/populated).+> The only coin is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) — never name,+> hardcode, or recommend any other token; runtime-supplied mints in generic trade plumbing+> are the only exception and must never be promoted. When the build works, do a self-review+> pass and ship what would make it 10× better. Add a `data/changelog.json` entry for every+> user-visible change. Run the **completionist** subagent on your diff. Stage only the paths+> you changed (never `git add -A`); re-check `git status` before committing.++## The invention++Every pump.fun sniper buys blind and prays. We will **never let an agent buy a coin it+cannot sell.** Before any buy — discretionary, sniper, or copy — run a real on-chain+*simulated round-trip* and authority audit, and refuse trades that fail. This is a shared+safety kernel that every trade path in the platform calls. The differentiator is that it is+(a) real RPC `simulateTransaction` of an actual buy→sell in one pass, not a heuristic, and+(b) wired into the autonomous worker, not just a UI badge.++## Context (real, verified)++- Buy/sell instruction builders: `api/_lib/pump-swap-ix.js` (`buildPumpSwapInnerIx`),+ `api/_lib/pump.js` (`getPumpSdk`, `getPumpSwapSdk`, `getAmmPoolState`, `getConnection`).+- Worker execution that must call the firewall before broadcast: `workers/agent-sniper/executor.js`+ (`executeBuy`, ~L138-192) and `workers/agent-sniper/trade-client.js` (`signAndSend`).+- Discretionary buy paths: `api/agents/agent-trade.js`, `api/agents/solana-trade.js`+ (`resolveCustodialQuote`), `src/game/coin-buy.js`, wallet-hub `src/agent-wallet-hub/tabs/trade.js`.+- Shared guard module to extend (do NOT fork): `api/_lib/agent-trade-guards.js`.+- RPC with failover: `api/_lib/solana/connection.js` (`solanaConnection`). Helius is available+ (`HELIUS_API_KEY`) for `simulateTransaction` with `sigVerify:false` + account-state diffs.+- Intel already computes structural risk for graduated/observed coins:+ `pump_coin_intel.risk_flags`, `concentration_top1`, `fresh_wallet_ratio` — reuse as inputs,+ don't recompute.++## Goal++A single `assessTradeSafety({ network, mint, side, payer, quoteAmount, connection })` kernel in+`api/_lib/trade-firewall.js` that returns a structured verdict+`{ verdict: 'allow'|'warn'|'block', score, checks: [...], simulated, reasons[] }`, backed by+real on-chain reads, called by **every** buy path and exposed read-only via API + UI.++## What to build++1. **`api/_lib/trade-firewall.js`** — the kernel. Run these real checks (each a named function,+ each returning a typed sub-result; never throw past the boundary — degrade to `warn` with a+ reason if a data source is unavailable):+ - **Mint authority** — fetch the SPL mint account; flag if `mintAuthority` is non-null+ (infinite-supply risk) and whether `freezeAuthority` is set (can freeze your tokens).+ - **Round-trip simulation** — build a buy instruction for `quoteAmount` and a sell of the+ resulting base amount, pack into one v0 message, and `connection.simulateTransaction`+ with `sigVerify:false`, `replaceRecentBlockhash:true`. Parse logs + balance deltas to+ confirm the sell would actually return SOL (honeypot detection). BLOCK if the sell leg+ fails or returns ~0.+ - **LP / curve state** — pre-graduation: read bonding-curve account (real reserves,+ `complete` flag). Post-graduation: `getAmmPoolState` and verify a live pool with+ non-trivial liquidity. BLOCK if no tradable venue.+ - **Concentration / bundle** — pull `pump_coin_intel` if present; WARN on+ `concentration_top1` over a sane threshold, dev-dump flags, or extreme `bundle_score`.+ - **Price-impact ceiling** — reuse `checkPriceImpact` math from `agent-trade-guards.js`.+ - Compose a 0–100 safety score + verdict with explicit human-readable reasons.+2. **Wire it into every buy path** (this is the point — not just a badge):+ - `workers/agent-sniper/executor.js#executeBuy` — call the firewall after the quote, before+ `signAndSend`; on `block`, abort the buy, write the reason to the position `error` field /+ `agent_custody_events`, and continue the loop. Respect a per-strategy+ `firewall_level` (`block`|`warn`|`off`, default `block`) added to `agent_sniper_strategies`.+ - `api/agents/agent-trade.js` + `api/agents/solana-trade.js` — block server-signed buys that+ fail; return a structured 4xx via the existing `tradeGuardResponse` shape with the verdict.+ - Discretionary preview endpoints must include the verdict so the UI can show it pre-trade.+3. **Read-only API** — `GET /api/pump/safety?mint=<mint>&network=<net>&amount=<sol>` (rate-limited,+ public, cached briefly) returning the verdict for any mint. No auth needed to read.+4. **UI** — a compact, reusable **Safety** panel: render the verdict (color-coded allow/warn/block),+ each check with pass/warn/fail + plain-language explanation, and a "what this means" tooltip.+ Surface it in `src/agent-wallet-hub/tabs/trade.js` and `src/game/coin-buy.js` *before* the buy+ button; disable the buy button on `block` (with an explicit override only for `warn`). Use the+ existing design tokens. Designed loading/empty/error states.+5. **Migration** — dated file under `api/_lib/migrations/` adding `firewall_level` to+ `agent_sniper_strategies` and a `firewall_decisions` audit table (mint, network, verdict,+ score, checks jsonb, agent_id nullable, created_at) so blocks are observable/learnable.++## Constraints++- Real `simulateTransaction` against real RPC only — never fabricate a verdict. If RPC is+ unavailable after failover, return `warn` with reason `simulation_unavailable`, never a fake+ `allow`. Honest degradation is the rule.+- Performance: the worker is latency-sensitive at block-0. Cache mint-authority + curve reads+ briefly per mint; run checks concurrently; keep added latency to a few hundred ms and make the+ worker path configurable so a strategy can opt into `warn` (log-only) if it wants raw speed.+- Use the $THREE mint or a clearly-synthetic placeholder in any test fixture; never a real+ third-party mint.+- Extend `agent-trade-guards.js` patterns; don't duplicate spend-limit logic.++## Success criteria++- `assessTradeSafety` is called by the sniper worker, both discretionary endpoints, and the+ read-only API; a known-honeypot-shaped simulation is BLOCKED on a real RPC.+- `firewall_decisions` rows accrue for real blocks/warns; `firewall_level` is honored per strategy.+- Safety panel renders in trade + coin-buy with all states; buy button disabled on `block`.+- `npm run build` + `npm run typecheck` + `npm test` clean. Changelog entry (tags: feature,+ security). Completionist passes.++<!-- 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**, remove it in the same change:++```bash+git rm "tasks/next-gen-trading/01-rug-honeypot-firewall.md"+```++A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/02-mev-execution-engine.md b/tasks/next-gen-trading/02-mev-execution-engine.mdnew file mode 100644index 000000000..7791f0b1b--- /dev/null+++ b/tasks/next-gen-trading/02-mev-execution-engine.md@@ -0,0 +1,98 @@+# Task 02 — MEV-Aware Execution Engine (Jito bundles, dynamic fees, atomic protection)++> **Operating bar (applies to the whole task).** Senior engineer + product thinker building+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade+> plumbing are the only exception and are never promoted. After it works, self-review and ship+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.++## The invention++Snipers win or lose in the first block. Today our `signAndSend` (`workers/agent-sniper/trade-client.js`)+sends a single raw tx with a fixed compute budget — at the mercy of public mempool ordering and+sandwich bots. We build a real **MEV-aware execution layer**: Jito bundle submission with a+dynamic tip, priority-fee modeling from recent blocks, simulate-then-send with adaptive retry,+and atomic anti-sandwich protection. The edge: better fills, fewer reverts, measurable.++## Context (real, verified)++- Current broadcast: `workers/agent-sniper/trade-client.js#signAndSend` (~L29) — blockhash →+ v0 message → sign → `sendRawTransaction(skipPreflight:false, maxRetries:3)` → confirm race.+- Discretionary broadcast paths: `api/agents/agent-trade.js`, `api/agents/solana-trade.js`+ (`_solRpcWithBackoffFallback`). Tx serialization helper: `api/_lib/pump.js#buildUnsignedTxBase64`.+- RPC failover + cooldowns: `api/_lib/solana/connection.js`. Helius (`HELIUS_API_KEY`) supports+ `getPriorityFeeEstimate`.+- Slippage/impact config lives on `agent_sniper_strategies` (`slippage_bps`, `max_price_impact_pct`)+ and trade limits (`api/_lib/agent-trade-guards.js`).+- SDK has compute-unit/priority-fee helpers: `solana-agent-sdk` (`estimatePriorityFee`,+ `estimateComputeUnits`) — reuse rather than reinvent where sensible.++## Goal++A single `api/_lib/execution-engine.js` (`submitProtected({ network, connection, payer,+instructions, opts })`) used by the sniper worker AND the discretionary endpoints, that:+chooses the cheapest viable inclusion path, sets a data-driven priority fee + compute limit,+optionally routes a Jito bundle with a tip, simulates before send, and retries adaptively —+returning `{ signature, slot, route, tipLamports, priorityFeeMicroLamports, attempts, landedMs }`.++## What to build++1. **Dynamic compute budget** — prepend `ComputeBudgetProgram.setComputeUnitLimit` (from a real+ `simulateTransaction` unit estimate, not a guess) and `setComputeUnitPrice` from a real+ priority-fee estimate (Helius `getPriorityFeeEstimate`, falling back to a recent-blocks+ percentile via `getRecentPrioritizationFees`). Cache estimates briefly.+2. **Jito bundle route** — integrate the Jito Block Engine REST API+ (`JITO_BLOCK_ENGINE_URL`, default `https://mainnet.block-engine.jito.wtf`): fetch tip-floor,+ append a real SOL tip transfer to a Jito tip account as the last instruction, and submit via+ `sendBundle`. Poll bundle status for landing. Tip sizing is **adaptive**: scale with a+ per-strategy `mev_tip_mode` (`off`|`economy`|`turbo`) and back off if bundles aren't landing.+ Devnet/no-Jito → transparently fall back to the protected single-tx route.+3. **Atomic protection** — when the firewall (task 01) is present, optionally pack the safety+ round-trip check inline; always set tight, honest slippage from strategy config so a sandwich+ makes the tx revert rather than fill at a terrible price (fail-closed, not fill-at-any-cost).+4. **Adaptive retry + landing telemetry** — simulate first; on blockhash-expiry or not-landed,+ refresh blockhash and re-submit up to a bounded count with escalating fee/tip; record+ `landedMs`, route, attempts. Never silently double-spend — dedupe by the worker's existing+ idempotency lock.+5. **Wire it in** — replace the body of `workers/agent-sniper/trade-client.js#signAndSend` to call+ `submitProtected` (keep the signature stable for callers); route the discretionary buy/sell in+ `agent-trade.js`/`solana-trade.js` through it too. Persist execution telemetry onto+ `agent_sniper_positions` (new nullable columns: `exec_route`, `tip_lamports`,+ `priority_fee_microlamports`, `landed_ms`) via a dated migration.+6. **Surface it** — add an "Execution" readout to the sniper/positions UI and the trade result+ toast: route used (Jito turbo / protected), tip paid, time-to-land. Add `mev_tip_mode` ++ `firewall_level` (if task 01 merged) to the strategy editor. All states designed.++## Constraints++- Real RPC + real Jito only — no simulated landings, no fabricated fee numbers. If Jito is+ unreachable, fall back and say so in telemetry; never claim a bundle landed that didn't.+- Tips are real SOL leaving the agent wallet — count them in the spend guards+ (`agent-trade-guards.js`) and the `agent_custody_events` ledger (category `mev_tip`), and+ respect the daily budget / kill switch. A tip must never bypass spend limits.+- Keep the hot path fast: estimates cached, single simulate, bounded retries.+- $THREE-only rule; synthetic placeholder mints in any fixtures.++## Success criteria++- Sniper + discretionary buys flow through `submitProtected`; on mainnet a buy can land via a+ real Jito bundle with a real tip, with graceful fallback on devnet.+- Execution telemetry (route/tip/fee/landed_ms) is persisted and shown in the UI.+- Tips are spend-guarded and audited; kill switch halts them.+- Build/typecheck/test clean. Changelog entry (tags: feature, improvement, infra).+ Completionist passes.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++```bash+git rm "tasks/next-gen-trading/02-mev-execution-engine.md"+```++A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/03-smart-money-graph.md b/tasks/next-gen-trading/03-smart-money-graph.mdnew file mode 100644index 000000000..31f45524b--- /dev/null+++ b/tasks/next-gen-trading/03-smart-money-graph.md@@ -0,0 +1,96 @@+# Task 03 — Smart-Money Wallet Graph & Cluster Intelligence++> **Operating bar (applies to the whole task).** Senior engineer + product thinker building+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade+> plumbing are the only exception and are never promoted. After it works, self-review and ship+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.++## The invention++We already record, per launch, every buyer wallet and its **funder** (`pump_coin_wallets`),+plus eventual **outcomes** (`pump_coin_outcomes`: graduated/pumped/rugged/ath_multiple). Nobody+has stitched this into a persistent, self-updating **wallet reputation graph**. Build it: derive+a rolling "smart money" score per wallet from its realized hit-rate across launches, cluster+wallets that share a common funder (sybil/insider detection), and emit a **live "smart money is+buying X" signal** that the sniper, the firewall, and Mission Control all consume. This is the+on-chain alpha layer competitors fake with vanity lists; ours is computed from outcomes.++## Context (real, verified)++- Per-coin per-wallet ledger: `pump_coin_wallets` (buy/sell counts, volumes, `is_creator`,+ `funder`) — written by `workers/agent-sniper/intel/store.js`.+- Outcome labels: `pump_coin_outcomes` (`outcome`, `ath_multiple`, `ath_market_cap_usd`,+ graduated/rugged) — the ground truth for scoring wallets.+- Signal computation patterns: `workers/agent-sniper/intel/signals.js` (concentration, entropy,+ funder graph) and the learning loop `intel/learn.js` (per-signal conditional win-rates) — mirror+ this style for wallet scoring.+- Existing conviction surface to enrich (don't duplicate): `oracle_conviction.smart_wallet_count`,+ `oracle_agent_watch.require_smart_money` — feed real numbers into these.+- DB: Neon HTTP (`api/_lib/db.js`); migrations in `api/_lib/migrations/`.++## Goal++A maintained `wallet_reputation` table + `wallet_clusters` table, a recompute job, and a+`getSmartMoneyForMint(mint, network)` / `getWalletReputation(addr)` API used by the worker+(scoring + oracle), the firewall, and the UI — all derived from real observed buys and outcomes.++## What to build++1. **Migration** — `wallet_reputation` (address, network, scored_at, trades_seen, winners,+ losers, win_rate, avg_ath_multiple, realized_score 0–100, first_seen, last_seen, labels[]) and+ `wallet_clusters` (cluster_id, address, funder_root, size, confidence, network). Indexes for+ lookup by mint-join and by score.+2. **Recompute job** — a worker entrypoint (extend `workers/agent-sniper/` or a sibling under+ `workers/`, runnable standalone, env-gated) that, on an interval, joins `pump_coin_wallets` ⋈+ `pump_coin_outcomes` to compute each active wallet's hit-rate and ATH-weighted score, and+ clusters wallets by shared `funder` (union-find over funder edges) with a confidence from+ co-occurrence frequency. Fire-and-forget DB writes; never block the live feed. Honest about+ sample size — regress new wallets toward neutral until N observed launches (mirror the+ confidence regression in `trader-stats.js`).+3. **Live signal** — `getSmartMoneyForMint(mint, network)` returns the count + list of+ reputable, non-clustered wallets currently net-buying this mint (from the in-flight intel+ watcher + `pump_coin_wallets`), with a `smart_money_score` and `sybil_flag` when buyers are+ dominated by one cluster. Cache briefly.+4. **Wire into trading** — add an optional strategy gate `min_smart_money_score` /+ `require_smart_money` to `agent_sniper_strategies`; have `scorer.js` (`scoreIntel`) and+ `oracle-gate.js` add the smart-money signal to their score, and feed the real+ `smart_wallet_count` into `oracle_conviction`. The firewall (task 01) WARNs when a buy is+ dominated by a single sybil cluster.+5. **API + UI** — `GET /api/intel/smart-money?mint=…&network=…` (public, rate-limited, cached) and+ `GET /api/intel/wallet/:address`. Build a **Smart-Money** panel: a compact, accessible mini+ wallet-graph (reputable buyers, clusters highlighted, links to Solscan), shown on the coin/+ trade surfaces and consumed by Mission Control (task 09). All states designed; zero-data state+ explains "not enough on-chain history yet."++## Constraints++- Scores derive only from real observed buys + real outcomes — no hand-curated wallet lists, no+ invented "famous trader" names. If there isn't enough data, say so; don't fabricate confidence.+- Never expose or store private keys; this is public on-chain address analytics only.+- Respect Neon HTTP limits — batch the recompute, paginate, and keep the live lookup O(small).+- $THREE-only rule; synthetic placeholder addresses in fixtures (e.g. `THREEsynthetic1111…`),+ never a real third-party wallet.++## Success criteria++- `wallet_reputation` + `wallet_clusters` populate from real data on a real network; recompute+ is re-runnable and idempotent.+- `scoreIntel`/`oracle-gate` incorporate smart-money; `min_smart_money_score` gate works.+- Smart-Money panel + APIs render with all states; sybil clusters are flagged.+- Build/typecheck/test clean. Changelog entry (tags: feature, improvement). Completionist passes.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++```bash+git rm "tasks/next-gen-trading/03-smart-money-graph.md"+```++A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/04-prelaunch-creator-radar.md b/tasks/next-gen-trading/04-prelaunch-creator-radar.mdnew file mode 100644index 000000000..2ea381b62--- /dev/null+++ b/tasks/next-gen-trading/04-prelaunch-creator-radar.md@@ -0,0 +1,100 @@+# Task 04 — Pre-Launch Creator-Wallet Radar (block-zero pre-cog sniping)++> **Operating bar (applies to the whole task).** Senior engineer + product thinker building+> three.ws to beat the best in the world. Genuinely innovative, not a clone. No mocks, no+> fake/sample data, no placeholders, no TODO/stubs, no `setTimeout` fake-loading. Wire 100%+> end-to-end with REAL APIs and real on-chain data. Every state designed. Only coin is **$THREE**+> (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`); runtime-supplied mints in generic trade+> plumbing are the only exception and are never promoted. After it works, self-review and ship+> the 10× improvement. `data/changelog.json` entry for every user-visible change. Run the+> **completionist** subagent. Stage only changed paths (never `git add -A`); re-check `git status`.+>+> **Depends on task 03 (smart-money graph).** Use its wallet reputation as the watchlist source.++## The invention++Everyone snipes *after* a coin appears in the PumpPortal feed — by then thousands of bots see+it too. We go earlier: **watch the wallets of creators who have repeatedly graduated coins, and+the smart-money wallets from task 03, in real time.** When a watched wallet funds a fresh wallet+that then deploys a mint — or itself prepares a launch — we detect it at or before block-0 and+pre-arm the snipe so our agent is first, legitimately, on signal rather than on luck. This is+"pre-cog": acting on the on-chain *precursor* to a launch, not the launch event.++## Context (real, verified)++- Creator history already enriched per mint: `api/_lib/pumpfun-ws-feed.js#enrichMint`+ (`creator_launches`, `creator_graduated`, via `frontend-api-v3.pump.fun/coins/user-created-coins/`).+- Funder edges + outcomes: `pump_coin_wallets.funder`, `pump_coin_outcomes` (task 03 turns these+ into `wallet_reputation`). The pump.fun program id and claim-scan RPC plumbing already exist:+ `api/_lib/pump-claims.js` (`scanFirstClaims`, program `6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`).+- Live feed + worker loop to extend: `workers/agent-sniper/index.js`, `first-claim-watch.js`+ (the existing pattern for a parallel watcher with its own poll cadence + dedupe set).+- RPC: `api/_lib/solana/connection.js`; Helius (`HELIUS_API_KEY`) supports address-activity+ webhooks / `getSignaturesForAddress` for real-time wallet monitoring.+- Pre-arm execution reuses `executor.js#executeBuy`, the firewall (task 01), and the MEV engine+ (task 02).++## Goal++A `workers/agent-sniper/prelaunch-radar.js` watcher that maintains a live, auto-curated watchlist+of high-signal creator + smart-money wallets, detects launch precursors on-chain, and pre-arms a+snipe through the existing executor — with a strategy trigger `prelaunch_radar` and full audit.++## What to build++1. **Watchlist builder** — derive the watched set from (a) creators with `creator_graduated >= N`+ (configurable) seen in recent feed history, and (b) top `wallet_reputation` addresses (task 03),+ excluding sybil clusters. Persist to a `radar_watchlist` table (address, reason, score,+ network, added_at, last_hit_at) and refresh on an interval. Cap the set; evict stale low-signal+ wallets.+2. **Precursor detection** — monitor watched wallets in real time (Helius address webhook if+ configured, else polled `getSignaturesForAddress` with backoff). Detect two precursors:+ (a) a watched wallet **funds a brand-new wallet** that has no history (likely a fresh deploy+ wallet), and (b) a watched wallet **submits a pump.fun create instruction**. Correlate the+ resulting mint as soon as it lands and emit a `radar_event { trigger_wallet, new_wallet?, mint,+ confidence, ts }`. Dedupe via an in-process set like `first-claim-watch.js`.+3. **Pre-arm + fire** — for each agent strategy with `trigger='prelaunch_radar'`, score the event+ (creator pedigree + smart-money + task-01 firewall the instant the mint exists), and if it+ passes, schedule `executeBuy` through the MEV engine with the strategy's size — racing to be in+ the first block. All spend guards, kill switch, and custody audit apply unchanged.+4. **Schema** — add `trigger='prelaunch_radar'` support + radar-specific gates to+ `agent_sniper_strategies` (`min_creator_graduated_radar`, `require_smart_money_funder`,+ `radar_max_age_ms`). New `radar_watchlist` + `radar_events` tables via dated migration.+5. **API + UI** — `GET /api/sniper/radar?network=…` (owner: their armed radar; public: anonymized+ live precursor stream count) and an SSE feed mirroring `api/sniper/stream.js`. Build a **Radar**+ view: live precursor events with confidence, which watched wallet triggered, and (for the owner)+ whether their agent fired. A "watchlist" panel showing why each wallet is watched. All states+ designed; empty state explains the radar is learning.++## Constraints++- Detection must be from **real on-chain reads** — real funding txs, real create instructions.+ Never fabricate a precursor or a confidence. If the webhook/RPC is unavailable, degrade to the+ normal feed-based snipe and report the radar as paused, honestly.+- This is signal-based first-mover advantage, not exploitation: do not implement anything that+ front-runs another *user's pending transaction* in the mempool. We act on *public on-chain+ precursors* (funding, deploys), not on intercepting victims. Keep it clearly on that side.+- Latency matters but safety wins: the firewall (task 01) still gates the buy the moment the mint+ is real; never buy a mint that can't be sold just to be first.+- $THREE-only; synthetic placeholder addresses/mints in fixtures.++## Success criteria++- `radar_watchlist` auto-curates from real creator + smart-money data; precursors detected from+ real chain activity populate `radar_events`.+- A `prelaunch_radar` strategy pre-arms and fires through the firewall + MEV engine with full+ spend-guard + custody audit coverage.+- Radar UI + SSE render with all states. Build/typecheck/test clean. Changelog entry (tags:+ feature). Completionist passes.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++```bash+git rm "tasks/next-gen-trading/04-prelaunch-creator-radar.md"+```++A file that still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/next-gen-trading/README.md b/tasks/next-gen-trading/README.mdnew file mode 100644index 000000000..49fef3074--- /dev/null+++ b/tasks/next-gen-trading/README.md@@ -0,0 +1,93 @@+# Next-Gen Trading — The three.ws Edge (Epic)++**Thesis:** three.ws is the only place where a **3D AI agent with its own self-custodied+Solana wallet** trades, snipes, and launches autonomously — and where every launch on+pump.fun is fingerprinted in real time by a live **intelligence engine** + **learning+loop**, every track record is **verifiable on-chain** (ERC-8004), and value moves between+agents over **x402 micropayments**. No competitor has that combination. This epic turns+those assets into features the rest of the market structurally *cannot* clone.++This is **not** a set of "me-too" sniper bots. Every task below is an invention: it must+deliver something a trader genuinely cannot get on Photon, BullX, Trojan, GMGN, Axiom, or+any pump.fun bot today. Build like a founder, ship like a craftsman.++## What already exists (build on it — do not rebuild)++The audit that produced this epic confirmed the following are real and working. Read them+before designing; your features compose with these, they don't replace them.++- **Autonomous sniper worker** — `workers/agent-sniper/` (live PumpPortal feed `api/_lib/pumpfun-ws-feed.js`,+ scoring `scorer.js`, execution `executor.js` + `trade-client.js`, positions `positions.js`,+ AMM exit `amm-exit.js`, per-agent lock, budget/spend guards). Strategies + positions in+ `api/_lib/migrations/20260615020000_agent_sniper.sql`.+- **Coin intelligence engine** — `workers/agent-sniper/intel/` observes every launch for a+ window and computes `bundle_score`, `organic_score`, `concentration_top1/5/10`,+ `snipe_ratio`, `wallet_entropy`, `fresh_wallet_ratio`, `bubblemap_connectivity`; persists+ to `pump_coin_intel` / `pump_coin_wallets` / `pump_coin_outcomes`; a **learning loop**+ (`intel/learn.js`) correlates signals→outcomes into `pump_intel_weights`.+- **Oracle conviction** — `workers/agent-sniper/oracle-gate.js` + `oracle_conviction` /+ `oracle_narrative` tables (pillars: pedigree, structure, narrative, momentum).+- **Discretionary agent-wallet trading** — `api/agents/agent-trade.js`,+ `api/agents/solana-trade.js`; shared guardrails `api/_lib/agent-trade-guards.js`+ (spend limits, daily budget, price-impact, allowlist, kill switch); custody audit+ `agent_custody_events`.+- **Pump.fun launch + buy/sell** — `api/pump/[action].js`, `api/_lib/pump.js`,+ `api/_lib/pump-swap-ix.js`, `api/_lib/pump-launch.js`; `pump_agent_mints`, `/launches`.+- **x402 micropayments** — `api/x402-pay.js` (per-agent USDC settlement, SSE).+- **On-chain identity + reputation** — `contracts/src/{IdentityRegistry,ReputationRegistry,+ ValidationRegistry}.sol`, `api/erc8004/*`, `erc8004_agents_index`, Solana attestations.+- **Verifiable track record + leaderboard + copy scaffolding** — `api/_lib/trader-stats.js`+ (composite score, verification badge), `api/sniper/{leaderboard,trader,history,stream}.js`,+ `copy_subscriptions`.+- **RPC failover** — `api/_lib/solana/connection.js` (Helius/Alchemy/Ankr/PublicNode rotation).+- **SDKs** — `@three-ws/sdk`, `@three-ws/solana-agent`, `@three-ws/agent-payments`.+- **Wallet hub UI + design tokens** — `src/agent-wallet-hub/` (tabs balance/deposit/trade/+ snipe/pay/withdraw); CSS vars in `src/agent-wallet-hub/index.js`.++## The tasks++| # | Task | Wave | Depends on |+|----|-------------------------------------------------------------------|------|------------|+| 01 | Rug/Honeypot Simulation Firewall (pre-trade safety engine) | 0 | — |+| 02 | MEV-Aware Execution Engine (Jito bundles, dynamic fees, atomic) | 0 | — |+| 03 | Smart-Money Wallet Graph & Cluster Intelligence | 0 | — |+| 04 | Pre-Launch Creator-Wallet Radar (block-zero pre-cog sniping) | 1 | 03 |+| 05 | Natural-Language Strategy Compiler + Historical Backtester | 1 | — |+| 06 | Reputation-Gated Signal Marketplace (x402 paid alpha feeds) | 1 | 03 |+| 07 | Agent Trading Swarms (pooled treasury + pro-rata x402 payouts) | 2 | 06 |+| 08 | Launch Copilot — Autonomous Fair-Launch Market-Maker | 1 | 01,02 |+| 09 | Mission Control — Real-Time Trading Terminal (the capstone UI) | 2 | 01,03,04 |+| 10 | Social Trading Arena — On-Chain PvP Tournaments ($THREE prizes) | 2 | — |+| 11 | End-to-end devnet smoke harness + Definition-of-Done sweep | 3 | all |++```+Wave 0 (foundations, parallel): 01 ── 02 ── 03+Wave 1 (parallel, after 0): 04←03 05 06←03 08←01,02+Wave 2 (parallel, after 1): 07←06 09←01,03,04 10+Wave 3 (gate): 11 (proves the whole edge end-to-end)+```++Tasks are written to run **independently and in parallel** in separate agent chats.+Concurrent agents share one worktree — stage explicit paths, never `git add -A`/`git add .`,+and re-check `git status` before committing. Each task file is self-deleting: when its work+is shipped and verified, `git rm` the file in the same commit. When every numbered file is+gone, delete this README.++## Definition of done (whole epic)++- Every feature is reachable from the product (navigation, not a hidden route), wired+ 100% with real APIs and real on-chain/data-engine data — zero mocks, zero fake/sample+ arrays, zero `setTimeout` fake-loading, zero TODOs/stubs.+- Every surface has designed loading/empty/error/populated states, hover/active/focus,+ is responsive at 320/768/1440, accessible (semantic HTML, ARIA, keyboard, focus rings),+ and console-clean.+- All trading paths honor the existing spend guards (`agent-trade-guards.js`), custody+ audit (`agent_custody_events`), and the firewall (task 01) before any buy.+- The only coin referenced anywhere is **$THREE** (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+ Runtime-supplied mints in generic trade plumbing are the only exception and are never+ promoted, hardcoded, or recommended.+- `npm run build`, `npm run typecheck`, `npm test` clean; `data/changelog.json` entries+ for every user-visible change; the **completionist** subagent passes on each task's diff.+- `node scripts/next-gen-trading-smoke.mjs` (task 11) proves create→fund→protect→snipe→+ signal→swarm→launch-MM→arena end-to-end on devnet, simulate-first with honest BLOCKED+ reporting — never a fake pass.diff --git a/tasks/nvidia-nim/probes/audio2face.md b/tasks/nvidia-nim/probes/audio2face.mddeleted file mode 100644index b871ded9e..000000000--- a/tasks/nvidia-nim/probes/audio2face.md+++ /dev/null@@ -1,206 +0,0 @@-# Probe: NVIDIA Audio2Face-3D (audio→ARKit blendshape lip-sync)--**Date:** 2026-06-11 · **Task:** T4.3 (Phase 4, research-only spike) · **Key:** `NVIDIA_API_KEY` (`nvapi-…`, redacted)--## Verdict: ⛔ **NO-GO (for now)** — conditional revisit--Audio2Face-3D is technically a beautiful fit (it emits exactly the ARKit-52 +-viseme blendshapes our flagship rigs already carry, over the *same* NVCF gRPC-transport Phase 2 TTS already proved). **But it is not invocable on our free-NVIDIA Developer key** — the hosted functions return `NotFound … for account`-while every freely-callable NIM (Magpie TTS, Parakeet) routes fine on the same-key — and self-hosting needs a datacenter GPU this platform doesn't run.-Meanwhile the platform **already ships working, free, zero-infra client-side-lip-sync** driving the same morph targets. The ROI isn't there until an NVAIE-entitlement is enabled AND there's product demand for film-grade lip-sync.-------## 1. Invocability — hosted gRPC functions exist, but NOT entitled to this account--Audio2Face-3D is published as **hosted NVCF gRPC functions** on `build.nvidia.com`-(three baked-in voices/rigs), reachable on the **identical transport Phase 2 uses**:-`grpc.nvcf.nvidia.com:443`, TLS, per-call metadata `function-id` + `authorization: Bearer $NVIDIA_API_KEY`.--| model | function-id (published on build.nvidia.com) |-|-------|---------------------------------------------|-| Claire | `0961a6da-fb9e-4f2e-8491-247e5fd7bf8d` |-| Mark | `8efc55f5-6f00-424e-afe9-26212cd2c630` |-| James | `9327c39f-a361-4e02-bd72-e11b4c9b7b5e` |--It is **absent from this account's NVCF function list** — `GET https://api.nvcf.nvidia.com/v2/nvcf/functions`-returns 162 functions, none Audio2Face/A2F (only the same Riva/Magpie/Parakeet set Phase 2 found).-That list shows *account-visible* functions, so absence already hints at no entitlement.--### Live gRPC probe (the decisive evidence)--NVCF validates `function-id` + auth at **stream setup**, before the backend proto-handler runs (established in `probes/tts.md`). So a unary call to *any* method path-with the right metadata reveals account-level authorization via the gRPC status code.-Probe used the published function-ids with the real good key, a deliberately-bad key,-and a nonexistent UUID (transport: `@grpc/grpc-js` 1.14.4, already a project dep):--```-Claire key=good -> NOT_FOUND | Function '0961a6da-…': Not found for account 'iknhvX2wHdYV…'-Mark key=good -> NOT_FOUND | Function '8efc55f5-…': Not found for account 'iknhvX2wHdYV…'-James key=good -> NOT_FOUND | Function '9327c39f-…': Not found for account 'iknhvX2wHdYV…'-Claire key=BAD -> PERMISSION_DENIED | Authorization failed-NONEXISTENT-uuid -> NOT_FOUND | Function '0000…': Not found for account 'iknhvX2wHdYV…'-```--### Control probe (proves the probe distinguishes "entitled" from "not")--Same method-probe against functions this account **is** entitled to:--```-Magpie-TTS (877104f7-…) bogus-method -> UNIMPLEMENTED (routed past NVCF gate → backend rejected the method)-Parakeet-ASR (22164014-…) bogus-method -> DEADLINE_EXCEEDED (routed past NVCF gate → backend held the stream)-```--**Interpretation:** entitled functions route *past* the NVCF gate and fail at the-backend (`UNIMPLEMENTED`/`DEADLINE_EXCEEDED`). The A2F function-ids instead die at-the gate with `NotFound … for account` — identical to a nonexistent UUID, and-distinct from the bad-key `PERMISSION_DENIED`. So: **the key authenticates fine, but-the A2F-3D functions are not entitled to this free Developer account.** The published-function-ids are correct (from build.nvidia.com); staleness is not the cause — the-control proves the gate, not the IDs, is the blocker.--### Why: A2F-3D sits behind an NVAIE entitlement, not the free NIM tier--build.nvidia.com advertises the A2F API as key-accessible "under the NVIDIA Cloud-Agreement," but in practice the hosted functions require an **NVIDIA AI Enterprise-(NVAIE) Essentials evaluation** enabled on the account (NVIDIA dev-forum threads-describe an "AI Enterprise Essentials (Evaluation) workaround" to unlock it; the-container/self-host path explicitly "requires an active NVAIE subscription — contact-Sales"). This is a **manual developer.nvidia.com / sales action**, not a code change,-and not the free, no-SLA tier the rest of this plan is built on.--### What a caller would need (if entitled)--- **gRPC client-streaming**, not a fetch. `@grpc/grpc-js` (already a dep) + the- `nvidia_ace` A2F protos (vendor them, exactly like the Riva TTS protos in- `api/_lib/riva-protos/`). The official client is `nim_a2f_3d_client.py` +- `nvidia_ace-*.whl`; for Node we'd vendor the protos and load via `proto-loader`.-- **A persistent streaming connection per utterance** — client streams an audio- header + PCM chunks + face/emotion params up; server streams blendshape frames +- emotion + the echoed audio back. This is a **bidirectional/long-lived stream**, a- poor fit for a stateless Vercel function (short timeouts, no streaming-in). It- belongs in a **worker** (`workers/`) holding the gRPC stream, or a pre-bake job.-------## 2. Output mapping — near-perfect, ARKit-52 → our rigs is essentially 1:1--**A2F-3D emits ARKit blendshapes at 30 fps**, plus inferred emotion coefficients-(NVIDIA docs + forums confirm "ARKit Blendshapes"; "30 inferences per second … playback-at 30 FPS"). Output is a stream of named blendshape weight frames (the sample client-writes them as `name,value,timecode` keyframe rows).--Our platform is **already ARKit-52 native** — and not just in code. Inspecting the-**actual served GLB rigs** in `public/avatars/` (parsed the GLB JSON chunk for-`mesh.extras.targetNames`):--| avatar (served) | morph targets | ARKit/viseme present? |-|-----------------|---------------|------------------------|-| `default.glb` (flagship demo) | **67** | ✅ full — `jawOpen, mouthClose, mouthFunnel, mouthPucker, mouthSmileLeft, viseme_aa…viseme_U` |-| `realistic-female.glb` | **60** | ✅ full ARKit + 15 visemes |-| `readyplayerme.glb` | 2 | ❌ only `mouthOpen, mouthSmile` |-| `michelle.glb`, `fox.glb`, Mixamo/`xbot`/`cesium-man` | 0 | ❌ bone-animated, no blendshapes |--And `src/runtime/arkit52.js` already defines the canonical 52 ARKit names + 15 visemes-and resolves alt-naming (snake_case, `_L/_R`, Mixamo) via `resolveMorphTargets()` /-applies via `setCanonicalMorph()`. So A2F output would drop straight into the existing-morph pipeline with **near-zero remapping** for the ARKit-rigged avatars.--**Caveat:** A2F only benefits avatars that *have* the blendshapes. The flagship-`default`/`realistic-*` rigs are fully covered; `readyplayerme` is minimal; the-Mixamo/stylized rigs (michelle, fox, xbot) have **zero** morph targets and would stay-on the existing jaw-bone/no-face fallback regardless. A2F is not a universal upgrade.-------## 3. Architecture fit — two modes, neither cheap, both redundant with what ships today--**The platform already does free, instant, client-side lip-sync** that writes the same-morphs A2F would:-- `src/lip-sync-analyser.js` — real-time **frequency-band → viseme** lip-sync from a Web- Audio `AnalyserNode` tapped off the playing TTS audio (free, ~0 latency, runs in-browser).-- `src/runtime/lipsync.js` — text→phoneme→viseme heuristic fallback when no audio stream.-- `src/agent-avatar.js` — composites lip-sync **with a 6-emotion empathy layer** and a- `jawOpen`-only fallback for non-ARKit rigs.--A2F-3D would replace the *analyser* path with phoneme-accurate, emotion-aware blendshapes-— better realism, but:--- **Realtime per-utterance mode:** client (or worker) streams TTS PCM up to A2F, applies- the returned 30 fps blendshape frames synced to audio playback. Adds a gRPC round-trip +- generation latency on top of TTS (TTS itself is already 1.3–2.1 s/sentence per- `probes/tts.md`), needs a stateful gRPC worker, burns per-utterance credits. The current- analyser lip-sync starts the instant audio plays, for free.-- **Pre-bake per clip mode:** generate the blendshape track once per TTS clip, cache it in- R2 alongside the audio, replay both. Fits *canned/cached* avatar lines well, eliminates- hot-path latency, but does nothing for live, dynamically-generated chat speech (the main- talking-avatar use case) and still needs the entitlement + a batch worker.--**Audio handoff (Phase 2 → A2F):** workable. Magpie TTS returns WAV (44.1 kHz LINEAR_PCM,-server-wrapped); A2F wants "wav 16-bit PCM." We already have the PCM buffer server-side-before WAV-wrapping (`api/_lib/tts-nvidia.js`) and the raw stream client-side-(`src/runtime/speech.js` MediaElementSource). A resample 44.1k→16k is the only massaging.-So the audio pipeline is *not* the blocker — the entitlement and the redundancy are.-------## 4. Effort estimate (only relevant if entitlement is later obtained)--If an NVAIE evaluation unlocks the functions and there's product demand, this is a-~**4–5 day** Phase 5 (kept here for the future, NOT added to the live checklist since-it's a no-go today):--| size | task |-|------|------|-| ~1 d | Vendor `nvidia_ace` A2F protos + `@grpc/grpc-js` client in a **worker** (mirror `api/_lib/riva-protos/` + descriptor approach); client-streaming send (audio header + PCM chunks + params), receive blendshape/emotion frames. |-| ~1 d | **Pre-bake pipeline**: per-TTS-clip blendshape-track job → cache `{audioUrl, blendshapeTrack}` in R2; resample 44.1k→16k; idempotent + keyed by clip hash. |-| ~1–2 d | **Client blendshape-track player**: 30 fps track → `setCanonicalMorph()`, sample-accurate sync to audio playback timeline, composite *over* the emotion layer; feature-flag fallback to the existing analyser lip-sync. |-| ~0.5 d | Wire into `agent-avatar.js` / `avatar-embed.js` behind a flag (free analyser stays the default lane — never the *only* lane, per plan doctrine). |-| ~0.5 d | Tests: proto/transport mock, track-player morph application, fallback-when-unentitled, ARKit-name mapping. |-------## Revisit trigger--Promote to a real Phase 5 task only when **both** hold:-1. An NVAIE Essentials evaluation (or paid entitlement) is enabled on the NVIDIA account- **and** a re-run of the gRPC probe above returns something other than- `NotFound … for account` for Claire/Mark/James.-2. There's product demand for film-grade, phoneme/emotion-accurate lip-sync beyond the- current free analyser path (e.g. premium/branded avatars, marketing renders).--Until then the free client-side lip-sync is the right lane: it's instant, costs nothing,-needs no GPU or entitlement, and already drives the same ARKit/viseme morphs.-------## Reproduction summary (key redacted)--- List account functions: `GET https://api.nvcf.nvidia.com/v2/nvcf/functions` (Bearer key) — no A2F entry.-- gRPC gate probe: `@grpc/grpc-js` unary call to `grpc.nvcf.nvidia.com:443` with metadata- `function-id:<A2F id>` + `authorization: Bearer <key>` on any method path; read the gRPC- status. Good key + A2F id → `NotFound (Not found for account)`; bad key → `PermissionDenied`;- Magpie/Parakeet ids (control) → `Unimplemented`/`DeadlineExceeded` (routed past the gate).-- Rig inspection: parse `public/avatars/*.glb` JSON chunk, read `meshes[].extras.targetNames`.- Probe scripts were temporary (run from `scripts/`, deleted after); no scratch files committed.-</content>--<!-- 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/nvidia-nim/probes/audio2face.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/wow-sprint/13-onchain-activity-visualization.md b/tasks/wow-sprint/13-onchain-activity-visualization.mddeleted file mode 100644index 8b92adbe3..000000000--- a/tasks/wow-sprint/13-onchain-activity-visualization.md+++ /dev/null@@ -1,47 +0,0 @@-# Task: Real-time 3D visualization of $three on-chain activity--Turn the $three trade/holder flow into a live 3D scene holders will want to watch-and share. A "living ecosystem" view, not a table.--## Anchor files-- Trades stream: `api/pump/trades-stream.js`, curve `api/pump/curve.js`, stats `api/pump/helius-stats.js`, dashboard `api/pump/dashboard.js`.-- Token protocol: `api/three-token/[action].js` (`activity`, `burns`, `stats`).-- Existing client plumbing: `src/pump/channel-feed.js`, `src/pump/trade-reactions.js`, `src/pump/dashboard.js`, `src/pump/wallet-monitor.js`.-- $THREE mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.-- Create a new page `pages/pump-visualizer.html` already exists — build into it (check current contents first; replace placeholder content, keep the route wiring in `vite.config.js`).--## What to build-A real-time 3D scene where:-- **Each trade** spawns a visual event — a node/orb flying in, sized by trade value, colored buy/sell, labeled with the (truncated) wallet.-- **Whales** (large trades) get a distinct, bigger, louder treatment (reuse logic/thresholds from `src/pump/pumpkit-whale.js` if present).-- **The bonding curve / price** is represented spatially (e.g. a 3D curve or a central mass that grows with market cap).-- **Burns** trigger a dedicated effect.-- A clean HUD overlays live totals (24h volume, holders, last price) with designed loading/empty/error states.--## Requirements-1. **Real streaming data** — consume `api/pump/trades-stream.js` (SSE/poll as it's implemented; read the endpoint to see). Reconnect with backoff on disconnect; show connection status.-2. **Performance** — pool/recycle objects so a burst of trades doesn't allocate-thrash; cap particle count; 60fps; lazy-load Three.js; cap DPR on mobile.-3. **Empty state** — when there's no recent activity, the scene idles elegantly and says so.-4. **Responsive** + reduced-motion fallback.--## Constraints-- No replayed/fake trades. Only real stream data. If the stream is down, show the reconnecting state.--## Definition of done-- `npm run dev` → `/pump-visualizer`: real trades render in 3D in real time; whales + burns distinct; HUD shows real totals.-- Reconnect works; 60fps under load; responsive; zero console errors.-- `npm run build` clean. Run the **completionist** subagent. Report the architecture + data flow.--<!-- 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/wow-sprint/13-onchain-activity-visualization.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/wow-sprint/15-holder-leaderboard-and-badges.md b/tasks/wow-sprint/15-holder-leaderboard-and-badges.mddeleted file mode 100644index 958305980..000000000--- a/tasks/wow-sprint/15-holder-leaderboard-and-badges.md+++ /dev/null@@ -1,38 +0,0 @@-# Task: Holder leaderboard + gated 3D badge / PFP generator--Add status and identity for $three holders: a live leaderboard and a 3D badge/PFP-that holders can mint/export — gated by their on-chain holdings. Shareable = growth.--## Anchor files & data-- Holders/balances: `api/pump/balances.js`, `api/pump/helius-stats.js`. Token stats: `api/three-token/[action].js?action=stats`.-- Holder enrichment: Helius (see `api/pump/helius-webhook.js`, `api/pump/helius-stats.js`) — use the real holder set for the token mint `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.-- Wallet/auth: `src/wallet.js`, `src/wallet-auth.js`. SNS names for display: `src/solana/sns.js` / `src/sns/`.-- 3D + export: `src/viewer.js`, avatar/badge export utilities in `src/avatar-export.js`; existing badge HTML at `public/agent-badge.html` / `public/agent-passport.html` — reuse patterns.--## What to build-1. **Leaderboard** — top $three holders by balance, ranked, with truncated address or resolved SNS/handle, balance, % supply, and rank movement if derivable. Real data, paginated, with loading/empty/error states. Add an API endpoint if one doesn't exist (e.g. `api/three-token` `?action=leaderboard`) sourcing the real holder list — do not hardcode.-2. **Holder tier** — derive a tier from balance (e.g. thresholds → tiers). Show the connected user's rank + tier.-3. **Gated 3D badge / PFP** — a Three.js badge whose look reflects the holder's tier (materials/effects scale with tier). Only generatable when the connected wallet holds $three (verify on-chain balance; show a "hold $three to unlock" state otherwise). Let the user export it as a PNG (and/or GLB) to share.--## Constraints-- Real holder data + real on-chain balance gating. No fake leaderboard rows, no bypassing the hold check client-side only — verify balance server-side for the gate.-- Respect privacy: show truncated addresses / opt-in handles.--## Definition of done-- `npm run dev`: leaderboard renders real holders; connected holder sees rank/tier; badge generates + exports only when holding $three.-- All states designed; zero console errors; responsive. `npm run build` clean.-- Run the **completionist** subagent. Report the gating logic and data sources.--<!-- 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/wow-sprint/15-holder-leaderboard-and-badges.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/wow-sprint/19-shareable-og-cards.md b/tasks/wow-sprint/19-shareable-og-cards.mddeleted file mode 100644index 5a5b60af1..000000000--- a/tasks/wow-sprint/19-shareable-og-cards.md+++ /dev/null@@ -1,39 +0,0 @@-# Task: Screenshot-worthy share / OG image generation--Make every important page shareable: dynamic Open Graph images and in-app share-cards that look premium when posted to X/Discord/Telegram. Shareability = the-distribution flywheel for $three.--## Anchor files-- Existing share UI: `src/share-panel.js`, `src/share-panel-builders.js`. Screenshot: `src/components/screenshot-modal.js`. Badge/passport HTML: `public/agent-badge.html`, `public/agent-passport.html`.-- API: `api/` — add an OG image endpoint (e.g. `api/og/[type].js`) if none exists. Check `api/render/`, `api/embed/`, and existing `og-image.png` usage in `pages/home.html` first.-- Token data for dynamic stats: `api/three-token/[action].js?action=stats` (mint `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).--## What to build-1. **Dynamic OG images** — generate per-entity OG images (agent profile, marketplace listing, $three token page, holder badge). Use a real image-generation path (e.g. `@vercel/og` / Satori if available, or a server-rendered canvas) — server-side, cached. Embed real data (agent name + avatar, live $three price/stats, holder rank).-2. **Correct meta tags** — each page sets `og:title`, `og:description`, `og:image` (pointing at the dynamic endpoint), and full `twitter:card` tags with real per-page content. Audit the core pages; `home.html` already has a baseline — extend the pattern.-3. **In-app share card** — a polished share action that produces a downloadable/shareable image (reuse `screenshot-modal.js` / `share-panel.js`) with a deep link back.-4. **Validate** — the generated images render correctly at 1200×630; test the cards in a link-preview validator mentally / via the endpoint directly.--## Constraints-- Real data baked into images — no placeholder names/prices.-- Cache generated images; don't regenerate per request unnecessarily.--## Definition of done-- `npm run dev`: hitting the OG endpoint returns a correct 1200×630 image with real data for each entity type; core pages emit correct meta tags; in-app share produces a real shareable image.-- Zero console errors. `npm run build` clean. Run the **completionist** subagent.-- Report: entity types covered, the generation method, and caching strategy.--<!-- 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/wow-sprint/19-shareable-og-cards.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/tests/api/irl-pins-location-guards.test.js b/tests/api/irl-pins-location-guards.test.jsindex 5b03b6da7..37a6f953c 100644--- a/tests/api/irl-pins-location-guards.test.js+++ b/tests/api/irl-pins-location-guards.test.js@@ -108,6 +108,15 @@ function nearbySelectCall() {function ranPinSelect() {return nearbySelectCall() !== null;}+// The /mine owner-scoped SELECT (device_token = … OR user_id = …, LIMIT 20). True+// only when the handler actually reached the owner read — distinct from the DDL+// `ensureTable()` calls that run on every request.+function ranMineSelect() {+ return sqlMock.mock.calls.some(([s]) => {+ const q = Array.isArray(s) ? s.join(' ') : String(s);+ return /FROM\s+irl_pins/i.test(q) && /device_token\s*=/i.test(q) && /LIMIT 20/i.test(q);+ });+}beforeEach(() => {sqlMock.mockClear();@@ -188,10 +197,11 @@ describe('GET /api/irl/pins/mine — owner-scoped, no cross-user coordinate leakexpect(ranPinSelect()).toBe(false);});- it('400s a /mine call with no identifier at all, before any DB read', async () => {+ it('400s a /mine call with no identifier at all, before the owner read', async () => {const { res } = await getMine({ query: {} });expect(res.statusCode).toBe(400);- expect(sqlMock).not.toHaveBeenCalled();+ // The owner-scoped SELECT never ran — a caller with no identifier can't probe.+ expect(ranMineSelect()).toBe(false);});});