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
Publish avatar-fix changelog; add IRL/wallet task backlogs
nirholasca2b7595d464
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d6820a82..815b5755a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-17+- **Agent profiles now show the agent's real avatar — no more stray model over the name** — On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged. `[fix]`- **Agents placed from an iPhone now land in the right real-world spot for everyone** — iPhone Safari can't use WebXR, so placing an agent in the real world relies on the phone's motion sensors and GPS. Until now it leaned on a relative gyro reading with no fixed sense of north, which meant an agent you pinned could show up rotated — or facing the wrong way — for other people standing at the same spot. IRL now reads the iPhone's true compass heading when you pin, so your agent is anchored to a real-world direction: pan your phone and it stays planted on its actual bearing instead of sliding with the camera, and walk toward it and it holds its place and grows as you approach. Everyone nearby sees it in the same orientation you intended. If your compass needs calibrating we still place the agent and tell you it may look rotated to others, rather than failing silently — and Android, which already had richer world-anchoring, is unchanged. (`/irl`) `[improvement, fix]`- **An inbox for your IRL agents — see who tapped, messaged, or paid, and reply** — Your IRL Agents dashboard now has an Inbox: a live, chronological feed of everyone who met your placed agents in real life. Each entry shows what happened — a view, a tap, a message, or a payment — where it happened, and how long ago. Payments show the exact amount and link straight to the block-explorer receipt, and you can reply to anyone who left your agent a message; if they were signed in, your reply lands in their notifications. Unread counts appear on the Inbox button and on each agent's card, the feed refreshes itself every few seconds, and opening the inbox marks everything read. High-signal events (a payment or a message) also ping you in the notification bell, so you find out the moment a stranger across the city engages your agent. (`/dashboard/irl-placements`) `[feature]`- **Change a placed agent's outfit from your dashboard — everyone nearby sees it** — Your IRL Agents dashboard now has a real outfit editor. Open Change outfit on any agent you've placed and a live 3D preview loads with wardrobe controls for the exact layers that avatar has — recolour its hair, skin, and clothing, strip back to the base body and dress it up again, or stack on hats, glasses, and earrings. Because your agents are public, the new look is baked into the agent itself and pushed to its real-world pin, so every person who walks up to that spot sees the updated outfit in their camera — not just you. Save when you're happy; the avatar is re-rendered for real before it confirms, the previous look stays untouched if anything fails, and nearby viewers refresh to the new outfit within seconds. Run a seasonal look, brand your agents as staff for an event, or just keep them fresh — all without walking back to where you pinned them. (`/dashboard/irl-placements`) `[feature]`diff --git a/data/changelog.json b/data/changelog.jsonindex 65fc1e83c..bcd495318 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,12 @@{"$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-17",+ "title": "Agent profiles now show the agent's real avatar — no more stray model over the name",+ "summary": "On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged.",+ "tags": ["fix"]+ },{"date": "2026-06-17","title": "IRL has its own logo",diff --git a/prompts/avatar-animation-hardening/00-README.md b/prompts/avatar-animation-hardening/00-README.mdnew file mode 100644index 000000000..625f98335--- /dev/null+++ b/prompts/avatar-animation-hardening/00-README.md@@ -0,0 +1,155 @@+# Avatar Animation Hardening — build plan++This directory contains **sequenced task prompts** that take avatar animation on three.ws+from "the catastrophic case is fixed" to **100% production-ready: zero broken poses, correct+across every rig convention, and a polished embed/home-page experience.** Each `NN-*.md` file+is a self-contained unit of work meant to be pasted into a **fresh agent chat** in this repo.+Run them **in order** where the dependency column says so. Every task assumes the agent has+loaded the repo's `CLAUDE.md` operating rules (no mocks, no stubs, wire 100%, real APIs, design+every state, verify in a real browser).++## Why this initiative exists++The platform animates an avatar by retargeting one shared clip library+([public/animations/clips/*.json](../../public/animations/clips)) onto whatever rig a user+loads. A bug surfaced on the home page: the "Create" door-card avatar (`michelle.glb`, a Mixamo+export) **rendered lying on its back** the moment it played `celebrate`, while the neighboring+Avaturn-rigged avatar animated fine.++Root cause: Mixamo/FBX rigs bake the Y-up correction as `+90°X` on the armature root and a+compensating `−90°X` on `Hips`. The retargeter copied each clip bone's local rotation+**verbatim**, overwriting that `−90°X` and tipping the body flat.++### What already shipped (baseline — do NOT redo)++Commit `a1cdc528` added a **bind-rotation-aware correction** to+[src/animation-retarget.js](../../src/animation-retarget.js): for each bone the retargeter now+replays the clip's *deviation from rest* in the **target rig's own rest frame**+(`Ta = Tr · Sr⁻¹ · Sa`), instead of copying verbatim. The primitives are in place:++- `SOURCE_REST` — a map of `canonical bone → authoring-rig rest quaternion`. **Currently lists+ only `Hips`** (rest = identity), because Hips is the bone carrying the up-axis convention.+- `bindCorrections(targetRest)` — builds the per-bone correction `C = Tr · Sr⁻¹`, skipping bones+ where it is identity (so a matching rig round-trips bit-for-bit — verified on `cz.glb`).+- `canonicalRestMapFromObject` / `canonicalRestMapFromRig` — capture the target rig's rest pose.+- `premultiplyQuaternionTrack` / `rotateVectorTrack` — apply the correction to clip tracks.+- `AnimationManager.attach` captures `_canonicalRest` while the model is in bind pose and passes+ it through `_retarget`.+- Unit coverage in [tests/animation-retarget.test.js](../../tests/animation-retarget.test.js)+ (the `bind-rotation correction` describe block).++Verified result: michelle's Hips up-axis went from **90.4° off vertical → 1.7°**; cz unchanged+(**1.7° → 1.7°**).++**The fix is intentionally scoped to Hips only.** That stands every rig upright but leaves limb+fidelity, locomotion root-motion, ingest-time normalization, a permanent regression guard, and+the embed/home UX as the remaining work. That is what these tasks deliver.++## Task sequence++| # | File | Depends on | What it delivers |+|---|------|-----------|------------------|+| 1 | `01-full-bind-correction.md` | — | Extend `SOURCE_REST` from Hips-only to the **full** canonical authoring rest pose (captured from the reference rig) so limbs retarget correctly onto T-pose/A-pose mismatched rigs |+| 2 | `02-root-motion-cross-rig.md` | 1 | Make hip **position** (root motion) correct for any parent-axis convention — walk/run travels the right world direction & distance on Mixamo/RPM/Avaturn rigs |+| 3 | `03-ingest-rig-normalization.md` | — (parallel) | Canonicalize rig orientation + bone names at **avatar ingest** so all stored avatars share one convention — defense-in-depth + zero runtime cost for future avatars |+| 4 | `04-regression-corpus-and-runtime-guard.md` | 1 | Locked cross-rig regression corpus (upright-invariant assertions) + a runtime "fallen pose" guard wired to the observability pipeline — the "zero error, stays shipped" guarantee |+| 5 | `05-embed-and-home-avatar-ux.md` | — (parallel) | The surface the bug appeared on: `<agent-3d>` loading/error/reduced-motion states, seamless looping, per-clip framing, offscreen pause — the "best UX" mandate |+| 6 | `06-final-qa-and-promote.md` | 1–5 | End-to-end QA across every avatar surface (/pose, avatar pages, embeds, /irl, /walk), changelog, completionist — "shipped complete" |++Tasks 1, 3, and 5 are independent and can run in parallel. 2 and 4 follow 1; 6 is last.++---++## Shared architecture & conventions (READ THIS — every task relies on it)++These are verified facts about the codebase. Cite file paths in your work and **read the+referenced files before editing.**++### The retargeting pipeline (the heart of this initiative)+- [src/animation-retarget.js](../../src/animation-retarget.js) — pure module (three + the+ canonicalizer only; runs in browser AND Node). Key exports: `retargetClip`,+ `retargetClipToObject`, `retargetClipToRig`, `canonicalNodeMapFromObject`,+ `canonicalRestMapFromObject`, `MIN_COVERAGE`. The bind-correction internals+ (`SOURCE_REST`, `bindCorrections`, `BIND_EPSILON`) are documented inline — read those comments+ before changing the math.+- [src/animation-manager.js](../../src/animation-manager.js) — runtime playback engine wrapping+ `THREE.AnimationMixer`. `attach(model)` builds `_canonicalToNode` + `_canonicalRest` and+ retargets every registered clip. `_retarget` is the single chokepoint.+- The math invariant: `Ta = Tr · Sr⁻¹ · Sa` where `Sr` = authoring-rig rest, `Tr` = target-rig+ rest, `Sa` = clip keyframe. When the clip is at the authoring rest, the target sits at the+ target rest. A correction that is identity (rig already matches authoring convention) must be+ skipped so output is byte-for-byte unchanged.++### The reference rig & canonical bone naming (critical)+- **Reference rig used by the build pipeline: [public/avatars/cz.glb](../../public/avatars/cz.glb).**+ It is an Avaturn rig whose `Armature` has no rotation and whose `Hips` rest is identity — i.e.+ it **is** the authoring convention the clips were baked against. Clips play on it verbatim with+ zero correction. This makes cz.glb the source of truth for the authoring rest pose (Task 1).+- Mixamo test rig: [public/avatars/michelle.glb](../../public/avatars/michelle.glb) — bones are+ `mixamorig:`-prefixed; `Character` armature = `+90°X`, `mixamorig:Hips` rest = `−90°X`. This is+ the canonical "broken before the fix" avatar; use it as the cross-convention test subject.+- Canonical bone set: `CANONICAL_BONES` in+ [src/glb-canonicalize.js](../../src/glb-canonicalize.js). `canonicalizeBoneName(name)` maps any+ vendor name (`mixamorig:Hips`, `DEF-spine`, `left_arm`, `CH_Hips`, …) → canonical. A second+ normalizer, `normalizeBoneName()`, lives in+ [src/avatar-export.js](../../src/avatar-export.js) (used by export/ingest). **Reuse these —+ never hand-roll bone-name parsing.**++### Clip format & built-ins+- Stored clips are `THREE.AnimationClip.toJSON()`; track name = `BoneName.property`+ (`Hips.position` vector, `Hips.quaternion` quaternion). Parse with `AnimationClip.parse(json)`.+- Manifest: [public/animations/manifest.json](../../public/animations/manifest.json) —+ `{ name, url, label, icon, loop }`. **Note the `loop` field** (e.g. `celebrate` is+ `loop:false`, a one-shot) — Task 5 must honor it.+- Featured clips (what users hit first): `FEATURED` in+ [src/animation-presets.js](../../src/animation-presets.js) — idle, walk, jump, wave, dance,+ celebrate.++### Where avatars are rendered (the surfaces that must all stay correct)+- The `<agent-3d>` web component: [src/element.js](../../src/element.js) → wraps+ [src/viewer.js](../../src/viewer.js) (`Viewer` class, GLTFLoader with Draco/KTX2/Meshopt,+ ~lines 841–887) → `AnimationManager`.+- Home page door cards / bento / hero: `initLiveFeatures()` in+ [pages/home.html](../../pages/home.html) (`LIVE_SPOTS`, `spawnMini`, the `IntersectionObserver`+ ~line 6004+). This is where the bug was visible.+- Also: `/pose` studio, avatar profile pages, `/irl`, `/walk` — all drive the same+ `AnimationManager`, so a retarget fix is global.++### Avatar ingest / canonicalization (Task 3)+- [src/glb-canonicalize.js](../../src/glb-canonicalize.js) — `canonicalizeGlbBoneNames(buffer)`+ rewrites bone names in a GLB to canonical. Task 3 extends this concept to **orientation**.+- Ingest path: search for where uploaded/generated avatars are processed before R2 storage+ (avatar create/upload endpoints under `api/`; the avatar decoration shape is in+ [api/_lib/avatars.js](../../api/_lib/avatars.js)). Read before editing.++### Observability (Task 4)+- Client error reporter posts to `/api/client-errors` (logged as `[client-error]`). A runtime+ "fallen pose" guard should report through this existing channel — do not invent a new one.++---++## Rules for every task (do not skip)++- **Follow [CLAUDE.md](../../CLAUDE.md).** No mocks, no fake data, no stubs, no TODOs, no+ commented-out code, no `setTimeout` fake loading. Real wiring, every state designed+ (loading/empty/error/populated), accessibility, hover/active/focus states.+- **The no-regression bar is absolute.** Any change to the retarget math must remain a+ byte-for-byte no-op for rigs that already animate correctly (prove it on `cz.glb`). The shipped+ `cz: 1.7° → 1.7°` invariant must hold.+- **Read before you write.** Open the referenced files; match existing patterns, naming, tokens.+- **Verify with real assets.** Use `cz.glb` (reference) and `michelle.glb` (Mixamo) plus at least+ one more convention. For UI, `npm run dev` (port 3000), exercise in a browser, confirm zero+ console errors. State exactly what you verified and the measured numbers.+- **Tests:** keep `npm test` green; extend+ [tests/animation-retarget.test.js](../../tests/animation-retarget.test.js) and add new suites+ where a matching pattern exists. Respect the typecheck ratchet (`npm run typecheck`).+- **Changelog:** every user-visible change gets an entry in+ [data/changelog.json](../../data/changelog.json); run `npm run build:pages` to validate.+- **Concurrent fleet:** other agents share this worktree on `main`. Stage **explicit paths**+ (never `git add -A`), and re-check `git status` / `git diff --staged` right before committing.+- **Do not push** unless the user explicitly approves. When they do, push to **both** remotes+ (`git push threeD main` && `git push threews main`). Never pull/fetch from `threeD`.+- **Run the `completionist` subagent** over your changed files before declaring done; fix+ everything it flags.+- At the end of your task, write a short handoff note: what changed and what the next task should+ build on.diff --git a/prompts/avatar-animation-hardening/01-full-bind-correction.md b/prompts/avatar-animation-hardening/01-full-bind-correction.mdnew file mode 100644index 000000000..b9cfcc046--- /dev/null+++ b/prompts/avatar-animation-hardening/01-full-bind-correction.md@@ -0,0 +1,90 @@+# Task 1 — Full per-bone bind correction (limb fidelity across rig conventions)++> Read [00-README.md](./00-README.md) first (the retarget pipeline, the `Ta = Tr · Sr⁻¹ · Sa`+> invariant, the reference rig `cz.glb`, the already-shipped Hips-only baseline).+> Follow [CLAUDE.md](../../CLAUDE.md). The no-regression bar is absolute: `cz.glb` must stay+> byte-for-byte unchanged.++The shipped fix corrects only the **Hips** bone, so every rig now stands upright. But the clip+library is authored against the Avaturn reference rest pose (`cz.glb`), and a Mixamo rig is in a+**T-pose** while Avaturn is an **A-pose** — so on `michelle.glb` the arms, shoulders, and legs+still play in the wrong local frame (shoulders too high/spread, elbows rolled). The motion is+upright but anatomically off. This task extends the bind correction from Hips-only to **every+bone**, using the real authoring rest pose, so any humanoid rig performs clips faithfully.++## What to build++### 1. Capture the canonical authoring rest pose (as committed data)+- Write a reproducible generator under `scripts/` (e.g. `scripts/build-canonical-rest.mjs`) that+ reads the reference rig **[public/avatars/cz.glb](../../public/avatars/cz.glb)**, walks its+ skeleton, and emits each canonical bone's **local rest (bind-pose) quaternion**. cz.glb is the+ authoring convention (clips play on it with zero correction), so its rest pose *is* `Sr` for+ every bone. Key each entry by `canonicalizeBoneName(boneName)`.+- Emit the result as a small committed module/data file the pure retarget module can import+ without a build step (e.g. `src/animation-canonical-rest.js` exporting a frozen+ `{ [canonicalBone]: [x,y,z,w] }`). Round to a stable precision so the file is diff-friendly and+ deterministic. Document in a header comment that it is generated from `cz.glb` and how to+ regenerate it.+- The generator must run in Node without a browser (parse the GLB JSON chunk directly, as the+ diagnosis script did — `GLTFLoader` needs `self`/DOM). Make it idempotent and add an+ `npm run` script alias if that matches repo convention.++### 2. Wire the full rest pose into the retargeter+- In [src/animation-retarget.js](../../src/animation-retarget.js), replace the Hips-only+ `SOURCE_REST` with the full canonical rest map imported from Task 1.1 (keep `Hips` = identity+ if and only if that is what cz.glb actually has — verify, don't assume).+- `bindCorrections` already computes `C = Tr · Sr⁻¹` per canonical bone and skips identities, so+ the math generalizes for free. Confirm it now produces corrections for limb bones on a Mixamo+ rig and **still skips every bone on cz.glb** (all corrections identity → empty map → verbatim).+- Quaternion tracks get `premultiplyQuaternionTrack`. Position tracks: only Hips carries root+ motion, but if any other bone has a position track, decide and document whether it needs+ rotating (Task 2 owns root-motion correctness — coordinate, don't double-handle).++### 3. Correctness & no-regression proof+- **cz.glb invariant:** retargeting any clip onto cz.glb yields tracks identical to the verbatim+ path (deep-equal the values arrays). Add this as a locked test.+- **Mixamo fidelity:** on `michelle.glb`, after retarget, the *world-space direction* of each+ major limb segment (upper arm, forearm, thigh, shin) at representative keyframes should match+ cz.glb playing the same clip within a tolerance (e.g. ≤ a few degrees). Assert this numerically+ — reconstruct the bone graph from the GLB and compose world transforms (the diagnosis script in+ the conversation shows the technique). No eyeballing as the *only* check.+- Coverage gating (`MIN_COVERAGE`) and hip scaling must still behave as before.++### 4. Verify in a real browser+- `npm run dev`; load `michelle.glb` somewhere it animates (the `/pose` studio with+ `?avatar=`, or a scratch page under `scripts/`). Play idle, wave, dance, celebrate, walk.+ Confirm upright AND natural limb poses, zero console errors. Compare side-by-side with cz.glb.+ State the avatars and clips you exercised.++## Definition of done+- A generated, committed canonical-rest data file derived from `cz.glb`, plus the generator+ script (reproducible, documented, Node-only).+- `SOURCE_REST` (or its replacement) covers the full canonical skeleton; `bindCorrections`+ produces per-limb corrections for Mixamo rigs and an empty map for cz.glb.+- Locked tests: cz.glb verbatim-equality invariant + numeric limb-direction parity for a Mixamo+ rig. `npm test` green, `npm run typecheck` green.+- Browser-verified on ≥2 rig conventions; measured numbers reported.+- Changelog entry (improvement: avatars from any tool now animate with correct limb poses, not+ just upright).+- `completionist` run; all findings fixed. Handoff note for Task 2 (root motion) and Task 4+ (regression corpus).++Do not change root-motion/position semantics beyond what's needed here — that is Task 2. Do not+push unless the user approves (then both remotes).++<!-- 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 "prompts/avatar-animation-hardening/01-full-bind-correction.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. A file+that still exists is unfinished work; a file that is gone has shipped.diff --git a/public/changelog.json b/public/changelog.jsonindex f37f2f42a..56a5c3708 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-06-17T11:04:20.491Z",+ "generated_at": "2026-06-17T11:11:16.259Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Agent profiles now show the agent's real avatar — no more stray model over the name",+ "summary": "On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged.",+ "link": null,+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 9210e9607..a778bc20f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Agent profiles now show the agent's real avatar — no more stray model over the name</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-17:Agent profiles now show the agent's real avatar — no more stray model over the name</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged.</description>+ </item><item><title>Agents placed from an iPhone now land in the right real-world spot for everyone</title><link>https://three.ws/irl</link>diff --git a/public/features.json b/public/features.jsonindex 73da0d336..e10367a00 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T11:04:20.456Z",+ "generated_at": "2026-06-17T11:11:16.197Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/shot-agent-detail.mjs b/scripts/shot-agent-detail.mjsdeleted file mode 100644index c5356f768..000000000--- a/scripts/shot-agent-detail.mjs+++ /dev/null@@ -1,43 +0,0 @@-import { chromium } from 'playwright';--const id = process.argv[2] || '6bf40884-35af-432e-b432-8ba73fb5ba15';-const wait = Number(process.argv[3] || 15000);-const url = `http://localhost:3000/agents/${id}`;-const browser = await chromium.launch();-const page = await browser.newPage({ viewport: { width: 1280, height: 1600 } });-const errs = [];-page.on('console', (m) => { if (m.type() === 'error') errs.push(m.text()); });-page.on('pageerror', (e) => errs.push('PAGEERROR ' + e.message));-await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 }).catch((e) => console.log('nav:', e.message));-await page.waitForTimeout(wait);--const info = await page.evaluate(() => {- const out = [];- const walk = (root, path) => {- for (const el of root.querySelectorAll('*')) {- if (el.tagName === 'MODEL-VIEWER' || el.tagName === 'CANVAS') {- const r = el.getBoundingClientRect();- const cs = getComputedStyle(el);- out.push({- path: path + ' > ' + el.tagName.toLowerCase() + (el.id ? '#' + el.id : ''),- src: (el.getAttribute && el.getAttribute('src') || '').slice(-44),- box: { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) },- pos: cs.position, z: cs.zIndex, disp: cs.display, vis: cs.visibility, op: cs.opacity, overflow: cs.overflow,- });- }- if (el.shadowRoot) walk(el.shadowRoot, path + ' > ' + el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + '::shadow');- }- };- walk(document, 'doc');- // Also: avatar-actions host box + its display- const aa = document.getElementById('ad-avatar-actions');- const aaInfo = aa ? (() => { const r = aa.getBoundingClientRect(); const cs = getComputedStyle(aa); return { box: { x: Math.round(r.x), y: Math.round(r.y), w: Math.round(r.width), h: Math.round(r.height) }, disp: cs.display, hasShadow: !!aa.shadowRoot, html: aa.shadowRoot ? aa.shadowRoot.innerHTML.slice(0, 300) : aa.outerHTML.slice(0, 200) }; })() : null;- return { viewers: out, avatarActions: aaInfo };-});-console.log(JSON.stringify(info, null, 1));--await page.screenshot({ path: `/tmp/hero-${id.slice(0, 8)}.png`, clip: { x: 0, y: 130, width: 1280, height: 560 } });-console.log('saved /tmp/hero-' + id.slice(0, 8) + '.png');-console.log('CONSOLE ERRORS:', errs.length);-errs.slice(0, 10).forEach((e) => console.log(' ', e.slice(0, 160)));-await browser.close();diff --git a/tasks/agent-wallet-trading/01-wallet-foundation.md b/tasks/agent-wallet-trading/01-wallet-foundation.mdnew file mode 100644index 000000000..159a20317--- /dev/null+++ b/tasks/agent-wallet-trading/01-wallet-foundation.md@@ -0,0 +1,115 @@+# Task: Agent-wallet foundation — `walletReady` invariant, backfill, and wallet hub shell++## Context++Every agent created today gets a real Solana keypair auto-provisioned at creation+(`api/agents.js:258` → `generateSolanaAgentWallet()` in+`api/_lib/agent-wallet.js:325`), encrypted with AES-256-GCM keyed off `JWT_SECRET`+(`:18` `deriveKey`) and stored in `agent_identities.meta.encrypted_solana_secret`+(+ public `meta.solana_address`). The default-agent bootstrap path does the same+(`api/agents.js:150`). The platform can recover the keypair to sign+(`recoverSolanaAgentKeypair`, `:419`).++Two problems block "every avatar has a wallet, guaranteed":++1. **No invariant / no backfill.** Agents created before auto-provision shipped+ (or via any code path that skipped it) may have no `solana_address`. There is+ no migration to backfill them and no single helper that guarantees a wallet+ exists before the wallet UI/trade/x402 paths touch it.+2. **No product home for the wallet.** The balance lives on the owner-only+ agent-detail page; deposit (02), trade (04), sniper (06), x402 (08), and+ withdraw (09) all need one coherent surface to plug into. This task builds that+ shell so the later tasks slot in instead of each inventing their own page.++## Goal++A guaranteed `walletReady` invariant (every agent resolvable to a valid Solana+address, legacy rows backfilled), one reusable server helper that enforces it, and+a single **Agent Wallet hub** UI shell (tabbed: Balance · Deposit · Trade · Snipe ·+Pay · Withdraw) that all later tasks render into. No mocks, no placeholder+balances.++## Files to Read First++- `api/agents.js:140-310` — default-agent bootstrap + `handleCreate`; where wallets+ are generated and where `encrypted_*` secrets are stripped from responses (`:627`)+- `api/_lib/agent-wallet.js` — `generateSolanaAgentWallet` (`:325`),+ `recoverSolanaAgentKeypair` (`:419`), `deriveKey` (`:18`); the canonical+ custodial-key module — reuse it, do not fork+- `api/agents/solana-wallet.js:251` — `GET /api/agents/:id/solana` (balance/activity)+- `src/agent-solana-wallet.js:287,310` — client wallet fetch + 30s poll+- `src/agent-detail.js:1771-1796` — existing owner-gated wallet actions to refactor from+- `api/_lib/migrations/` — migration file naming/format (e.g. the dated+ `20260615020000_agent_sniper.sql`)+- `STRUCTURE.md`, `public/nav-data.js` (`tasks/nav-single-source`), design tokens+ used across `src/` pages++## What to Build / Do++1. **`ensureAgentWallet(agentId, userId)` helper** in `api/_lib/agent-wallet.js`+ (or a thin sibling): idempotently guarantees the agent has a valid+ `meta.solana_address` + `encrypted_solana_secret`, generating + persisting one if+ missing, and returning `{ address, created }`. Every wallet-touching endpoint+ (02/03/08/09) calls this first instead of assuming the field exists. Audit-log+ any lazy provision.+2. **Backfill migration** under `api/_lib/migrations/` that finds+ `agent_identities` rows lacking `meta.solana_address` and provisions them via the+ same code path (run it as a one-shot script invoked by the migration, since key+ generation is JS, not SQL — see how existing migrations pair `.sql` with a runner+ if needed). Idempotent; safe to re-run; logs how many were backfilled.+3. **`walletReady` in the agent API response.** `GET /api/agents/:id` (and the+ list/me endpoints) expose a boolean `walletReady` + the public `solana_address`+ (never the secret — keep the `:627` strip). The UI uses this to decide whether to+ show "preparing wallet…" vs the live hub.+4. **Agent Wallet hub shell.** Build one component/surface (reuse existing design+ tokens, nav from `public/nav-data.js`) with tabs: **Balance · Deposit · Trade ·+ Snipe · Pay · Withdraw**. This task ships **Balance** fully (live SOL + USD est.,+ activity list from `…/solana/activity`, refresh, skeleton loading, empty + error+ states) and renders labelled "coming online" placeholders for the other tabs that+ tasks 02/04/06/08/09 replace. Reachable from the agent profile and the+ create-agent success screen. Owner sees management actions; visitors see a+ read-only public view (balance + deposit only).+5. **Refactor, don't duplicate.** Move the owner-gated wallet logic out of+ `src/agent-detail.js:1771` into the hub so there is one wallet surface, and link+ agent-detail to it.++## Constraints++- Reuse `api/_lib/agent-wallet.js` for all key work — never generate or decrypt keys+ elsewhere. Secrets never leave the server; never log a decrypted key.+- Custodial keys are real funds — treat `ensureAgentWallet` and the backfill as+ security-sensitive: audit-log, no secret in responses, no secret in error messages.+- Real balances only (live RPC via `api/_lib/agent-pumpfun.js:26` failover). No+ hardcoded or sample balances. Handle RPC failure as a designed "balance+ unavailable, retry" state — never a blank or a thrown error.+- Mobile-responsive (320/768/1440), keyboard-navigable tabs, ARIA, focus rings.++## Success Criteria++- A SQL/script backfill leaves zero `agent_identities` rows without a valid+ `solana_address`; re-running it is a no-op.+- `ensureAgentWallet` is the single entry point used by tasks 02/03/08/09 (grep+ shows no other provisioning call site).+- The Agent Wallet hub renders for owner and visitor, with the Balance tab fully+ designed (loading/empty/error/populated) and live data; other tabs show honest+ placeholders.+- `walletReady` + `solana_address` present in agent API responses; no secret leaks+ (`git grep` for `encrypted_solana_secret` in any response path returns only the+ strip).+- `npm run dev`: hub loads with zero console errors/warnings; real RPC calls in the+ Network tab. `npm run typecheck` + `npm test` clean.+- Changelog entry (tag: feature). Run the **completionist** subagent on changed files.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "tasks/agent-wallet-trading/01-wallet-foundation.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/agent-wallet-trading/02-public-deposit-panel.md b/tasks/agent-wallet-trading/02-public-deposit-panel.mdnew file mode 100644index 000000000..3e6875683--- /dev/null+++ b/tasks/agent-wallet-trading/02-public-deposit-panel.md@@ -0,0 +1,105 @@+# Task: Public / onboarding deposit panel — scan QR or copy address, send SOL, live confirmation++## Context++The pieces to fund an agent wallet already exist but are scattered and+owner-gated, so a first-time user has no clean "send SOL to your agent" moment:++- Zero-dep QR generator: `src/erc8004/qr.js` (`renderQRToCanvas`,+ `renderQRToSVG`). The agent-detail page also loads QRious from a CDN+ (`pages/agent-detail.html:39`) — prefer the first-party `src/erc8004/qr.js` to+ avoid a third-party CDN dependency.+- A Receive button + QR canvas + copy-address control exist, but behind+ `bindWalletActions(isOwner)` so only the owner ever sees them+ (`src/agent-detail.js:1771-1796`, `pages/agent-detail.html:419-443`).+- Live balance API (`GET /api/agents/:id/solana`, `api/agents/solana-wallet.js:251`)+ + activity feed (`…/solana/activity`) + 30s client poll+ (`src/agent-solana-wallet.js:287,310`) are ready.+- The create-agent success screen already tells the user "It now has its own+ wallet" (`pages/create-agent.html:1493`) but offers no way to fund it.++This task turns those into a polished deposit experience that lives in the wallet+hub's **Deposit** tab (built in task 01) and is surfaced on the create-agent+success screen as the natural next step.++## Goal++Any user (owner or visitor) can fund an agent: see the agent's Solana address,+scan a QR with their phone, tap a `solana:` deep-link to open a mobile wallet, or+copy the address — then watch the balance update live and get a clear "X SOL+received" confirmation the moment funds land.++## Files to Read First++- `src/erc8004/qr.js` — first-party QR renderer (use this, not the CDN)+- `src/agent-detail.js:1771-1796` — current owner-only receive/QR logic to generalize+- `pages/agent-detail.html:419-443` — current address/QR markup+- `api/agents/solana-wallet.js:251` — balance + `…/activity` endpoint shape+- `src/agent-solana-wallet.js:287-313` — `fetchAgentSolanaWallet` + poll loop to reuse+- `pages/create-agent.html:1485-1500` + `src/create-agent.js:923-1050` — success screen+- Task 01's wallet hub shell (Deposit tab placeholder) — render into it++## What to Build / Do++1. **Deposit panel** rendered in the hub's Deposit tab and reusable as a modal:+ - Agent display name + avatar thumbnail for trust ("You're funding **Nova**").+ - The Solana address shown in full + truncated, with a one-tap copy control+ (toast on success).+ - A crisp QR encoding a **Solana Pay-style `solana:<address>` URI** (with+ `?label=<agentName>`), rendered via `src/erc8004/qr.js`. Tapping/clicking it on+ mobile triggers the same `solana:` deep-link to open Phantom/Solflare/etc.+ - A short, friendly "How to fund" line: scan with your phone wallet, or copy the+ address and send SOL from any wallet/exchange.+ - Optional amount field that updates the QR/deep-link `?amount=` (SOL).+2. **Live "funds received" feedback.** Reuse the existing poll+ (`src/agent-solana-wallet.js`) to watch the balance; when it increases, show a+ celebratory but professional confirmation ("◎0.50 SOL received") and refresh the+ activity list. Before any deposit, show a calm "Waiting for your first deposit…"+ empty state, not a blank.+3. **Wire into onboarding.** On the create-agent success screen+ (`pages/create-agent.html` / `src/create-agent.js`), add a prominent+ "Fund your agent" action that opens this deposit panel, so funding is the natural+ first step after creation. Also reachable from the agent profile.+4. **Make it public-safe.** Visitors (not just owners) can view + use the deposit+ panel — funding someone's agent is a feature. No secret, no management controls+ for non-owners.++## Constraints++- First-party QR only (`src/erc8004/qr.js`); drop the QRious CDN dependency for this+ surface. No external script for core funding UX.+- Real balance/activity from the live endpoints — never simulate a deposit or fake+ the "received" event. The confirmation must fire only on a real on-chain balance+ increase.+- `solana:` URI must be valid per Solana Pay (correct scheme, base58 address,+ optional `amount`/`label`). Verify it opens a wallet on a real phone (or document+ the exact tested URI if no device is available).+- Designed states: idle/waiting (empty), polling (subtle), received (success), RPC+ error (retry, never blank). Mobile-first (the QR is scanned on a phone but shown on+ desktop and vice-versa); 320/768/1440; ARIA labels on copy/QR; focus rings.++## Success Criteria++- `npm run dev`: open the deposit panel from both the create-agent success screen+ and the agent profile; QR renders, copy works, the `solana:` deep-link is valid.+- On a devnet/testnet address, sending SOL makes the balance update live and the+ "received" confirmation fire from real on-chain state (Network tab shows the real+ balance poll).+- Empty/waiting, success, and RPC-error states all render and look premium.+- Zero console errors/warnings; no third-party CDN for the QR. `npm run typecheck` ++ `npm test` clean.+- Changelog entry (tag: feature). Run the **completionist** subagent on changed files.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "tasks/agent-wallet-trading/02-public-deposit-panel.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md b/tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.mdnew file mode 100644index 000000000..723a7e3ca--- /dev/null+++ b/tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md@@ -0,0 +1,113 @@+# Task: Authenticated "trade from the agent wallet" endpoint + shared guardrail module++## Context++Pump.fun trading is real, but the product path is **user-signed**: the client+provides `wallet_address`, the user signs with their own external wallet, and the+server only verifies the signature after the fact+(`api/pump/[action].js` buy/sell prep+confirm, verify-after-sign at `:524`). The+**only** code that signs a pump.fun trade from the agent's own custodial wallet is+the sniper worker (`workers/agent-sniper/executor.js`), which loads the agent+keypair (`keys.js:25` → `agent_identities.meta.encrypted_solana_secret`), builds+buy/sell instructions (`api/_lib/pump.js:130`, `api/_lib/pump-swap-ix.js`), signs a+v0 tx (`trade-client.js:29`), and enforces serious guardrails first+(`executor.js:51-85`: idempotency lock, daily budget, per-trade cap, concurrency,+price-impact breaker, SOL fee headroom).++For the user's flow — fund the agent wallet, then have the agent trade from it —+we need that same custodial signing exposed as an authenticated, owner-only API,+with the guardrails shared (not duplicated) between this discretionary path and the+sniper. This is the security-critical core of the epic.++## Goal++`POST /api/agents/:id/trade` (owner-authenticated) that buys/sells a pump.fun token+**from the agent's own wallet**, server-signed, reusing the exact instruction+builders and a **shared guardrail module** extracted from the sniper executor.+Real on-chain execution, idempotent, fully guarded, audit-logged.++## Files to Read First++- `workers/agent-sniper/executor.js:46-206` — `executeBuy`/`executeSell`, guardrail+ sequence (`:51-85`), idempotency `INSERT…ON CONFLICT`, PnL recording, graduation+ catch (`:161`)+- `workers/agent-sniper/keys.js:25-45` — agent keypair loading (TTL cache)+- `workers/agent-sniper/trade-client.js:29-60` — `signAndSend` v0 tx flow+- `api/_lib/pump.js:130-137`, `api/_lib/pump-swap-ix.js` — buy/sell instruction builders+- `api/pump/[action].js` — existing buy/sell prep+confirm, slippage handling,+ fee-recipient routing, quote helpers (reuse, don't re-derive)+- `api/_lib/agent-wallet.js:419` — `recoverSolanaAgentKeypair` (the only decrypt path)+- `api/_lib/agent-pumpfun.js:26` — RPC failover connection+- Auth helper used elsewhere (`requireAuth`) and the audit-log helper used by+ `recoverSolanaAgentKeypair`++## What to Build / Do++1. **Extract a shared guardrail module** (e.g. `api/_lib/agent-trade-guards.js`)+ from `workers/agent-sniper/executor.js`: idempotency lock, per-trade lamport cap,+ daily budget, max-concurrent, price-impact circuit breaker, SOL fee headroom,+ kill switch, wallet-balance check. The sniper executor and the new endpoint must+ **both** call this module — one source of truth for "is this trade allowed."+ Refactor the sniper to use it (no behavior change; its tests still pass).+2. **`POST /api/agents/:id/trade`**: owner-authenticated (`requireAuth` + ownership+ check). Body: `{ side: 'buy'|'sell', mint, amount, denom: 'sol'|'token',+ slippageBps, network }`. Flow: `ensureAgentWallet` (task 01) → recover keypair+ (audit-logged) → quote → run shared guards → build instructions+ (`api/_lib/pump.js` / `pump-swap-ix.js`) → `signAndSend` → record the trade+ (reuse the sniper's position/trade ledger tables or the existing `pump_agent_*`+ tables — pick the one the sniper UI/PnL already reads so history is unified) →+ return signature + filled amounts + new balance.+3. **Idempotency + safety**: require a client-supplied idempotency key (or derive+ one) so a retried request never double-spends. Enforce the same daily/per-trade+ caps as the sniper (configurable per agent). Never execute if guards reject —+ return a structured, actionable error (reason + limit), never a 500.+4. **A read endpoint** (or extend an existing one) for the agent's discretionary+ trade quote/preview so the UI (task 04) can show expected out, price impact, and+ fees before the user confirms.++## Constraints++- The agent keypair is decrypted only via `recoverSolanaAgentKeypair`+ (`api/_lib/agent-wallet.js:419`), only server-side, only after auth + ownership,+ always audit-logged. Never return or log the secret.+- No duplicated guardrail logic — the shared module is the single source of truth;+ the sniper must be refactored to consume it in the same change (or a clearly+ preceding one) and its tests must still pass.+- Real quotes and real submission only. Honor `SNIPER_MODE`/a `simulate` flag so the+ endpoint can run in paper mode for tests, but production default is live execution+ against real RPC. No fabricated fills.+- Errors handled at the boundary (auth, input, RPC, guard rejection, graduation) and+ returned as structured JSON with a recovery hint. A guard rejection is a 4xx with+ the reason, not an exception.+- Respect the graduation case: if the mint has graduated, route the sell through the+ AMM path (coordinate with task 07) rather than throwing.++## Success Criteria++- `POST /api/agents/:id/trade` buys and sells a pump.fun token from the agent's own+ wallet on devnet, returns a confirmed signature, and the new balance reflects the+ trade.+- The shared guardrail module is used by both the endpoint and the sniper; sniper+ tests still pass; `git grep` shows no second copy of the cap/breaker logic.+- Retrying the same idempotency key does not double-execute.+- Guard rejections (over budget, over per-trade cap, price-impact breaker, kill+ switch, insufficient balance) each return a clear 4xx with reason — verified with+ unit tests.+- Unauthenticated or non-owner callers are rejected; no secret ever appears in a+ response or log.+- `npm run typecheck` + `npm test` clean. Changelog entry (tag: feature). Run the+ **completionist** subagent on changed files.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "tasks/agent-wallet-trading/03-agent-wallet-trade-endpoint.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/agent-wallet-trading/04-agent-wallet-trade-ui.md b/tasks/agent-wallet-trading/04-agent-wallet-trade-ui.mdnew file mode 100644index 000000000..8d325e9be--- /dev/null+++ b/tasks/agent-wallet-trading/04-agent-wallet-trade-ui.md@@ -0,0 +1,92 @@+# Task: Agent-wallet pump.fun trade UI — buy & sell from the agent's own wallet++## Context++The discretionary trade endpoint from task 03 (`POST /api/agents/:id/trade` ++quote/preview) lets a funded agent wallet buy and sell pump.fun tokens, server-+signed, fully guarded. The existing buy/sell widget (`src/game/coin-buy.js`) is+**SOL-only and user-wallet-only** — it signs with the visitor's external wallet,+not the agent's custodial wallet. This task builds the agent-wallet trading UI in+the wallet hub's **Trade** tab (shell from task 01), to the `CLAUDE.md` UX bar.++## Goal++From the agent's funded wallet, the owner can buy and sell a pump.fun token with a+polished trade panel: live quote (expected out, price impact, fees, slippage),+confirm, real on-chain execution via task 03, and an updated balance + position —+every state designed.++## Files to Read First++- Task 03 endpoint + quote/preview shape (`POST /api/agents/:id/trade`)+- `src/game/coin-buy.js` — existing buy/sell widget patterns (SOL-only) to learn+ from and improve on (sorting/states gaps noted in `CLAUDE.md`)+- Task 01 wallet hub shell (Trade tab placeholder) — render into it+- `src/agent-solana-wallet.js:287-313` — balance fetch/poll to reflect post-trade+- `api/sniper/history.js` / `…/positions` source — so discretionary trades show in+ the same unified history the sniper UI uses+- Existing design tokens + modal/toast patterns used across `src/`++## What to Build / Do++1. **Trade panel** in the hub Trade tab:+ - Token selector / mint input with metadata + price (real data; resolve mint to+ name/symbol/icon via the existing pump metadata path).+ - Buy/Sell toggle; amount entry in SOL or token (denom switch, matching the+ endpoint's `denom`); quick-amount chips (25/50/75/Max based on real balance).+ - **Live quote** from the task-03 preview: expected output, price impact (warn at+ high impact), fees, slippage control (bps), minimum received. Debounce input;+ re-quote on change.+ - Confirm step showing exactly what will happen; on submit, call the trade+ endpoint with an idempotency key; show in-flight → confirmed (with explorer+ link) → balance/position refresh.+2. **Positions / holdings view**: the agent's current token holdings and a unified+ trade history (discretionary + sniper) reading the same ledger task 03 writes to.+ Realized/unrealized value where available.+3. **Every state designed**: empty (no holdings — prompt to fund/trade), loading+ (skeleton, not spinner), quoting, submitting, success (toast + explorer link),+ error (guard rejection reasons from task 03 surfaced verbatim and actionable —+ "over daily budget", "price impact too high", "insufficient SOL for fees"),+ insufficient-balance (link to the deposit panel from task 02).+4. **Owner-only writes.** Visitors see read-only holdings/history; only the owner+ sees the trade controls. Reflect `walletReady` (task 01) — if the wallet is still+ provisioning, show that, not a broken form.++## Constraints++- Real quotes, real execution through task 03 — no client-side fake fills, no+ optimistic balances that aren't confirmed on-chain. The balance/position updates+ only after the tx confirms.+- Reuse the task-03 endpoint for all signing; the UI never holds or sends a key.+- Surface guard rejections as designed, recoverable states — never a raw error or a+ silent failure. Tie "insufficient funds" to the deposit flow (task 02).+- Mobile-responsive (320/768/1440), keyboard-operable, ARIA on controls, focus+ rings, hover/active states. Animations on opacity/transform only.+- Coin-agnostic: the trade UI accepts any runtime-supplied mint (a product+ capability), but must never name, hardcode, market, or recommend any token other+ than $THREE in copy, defaults, examples, or placeholders.++## Success Criteria++- `npm run dev`: from a funded agent wallet, complete a buy and a sell on devnet+ through the UI; balance + holdings update from real on-chain state; explorer links+ resolve.+- Quote (impact/fees/min-received/slippage) is live and matches the endpoint preview.+- Empty, loading, quoting, submitting, success, and every error/guard state render+ and look premium; "insufficient funds" routes to deposit.+- Zero console errors/warnings. `npm run typecheck` + `npm test` clean.+- Changelog entry (tag: feature). Run the **completionist** subagent on changed files.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:++```bash+git rm "tasks/agent-wallet-trading/04-agent-wallet-trade-ui.md"+```++Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/agent-wallet-trading/README.md b/tasks/agent-wallet-trading/README.mdnew file mode 100644index 000000000..5467e3834--- /dev/null+++ b/tasks/agent-wallet-trading/README.md@@ -0,0 +1,126 @@+# Agent Wallet & Trading → 100% — Completion Plan++**Goal:** Ship the complete, production-grade flow for a three.ws 3D AI agent's+own Solana wallet:++> A user creates an avatar → it has a self-custodied Solana wallet by default →+> the user funds it by scanning a QR with their phone or copying the address and+> sending SOL → the agent can **trade pump.fun tokens**, **snipe new pump.fun+> launches**, and **pay for services via x402** — all from its own wallet, with+> the user always able to withdraw funds back out.++This is **not a rewrite**. The audit below confirms most of the backend already+exists and is real. The remaining work is: deploying the autonomous worker,+wiring the user-facing UX to the bar in `CLAUDE.md`, closing two correctness+gaps, and proving the whole loop end-to-end on devnet. Bar: **100% production+ready, zero error, complete, professional, best-possible UX.**++The only coin this platform references is **$THREE**+(`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). No other token may be named,+hardcoded, or recommended anywhere in this epic. Runtime-supplied mints in the+generic pump.fun trade path are the only exception and must never be promoted.++## Current state (verified 2026-06-17)++**Real and working — do not rebuild:**++- **Wallet by default.** Every agent created via `POST /api/agents`+ unconditionally generates a real Solana keypair, encrypts the secret+ (AES-256-GCM, key derived from `JWT_SECRET`), and stores it in+ `agent_identities.meta.encrypted_solana_secret` with the public+ `meta.solana_address`. Same on first-login default-agent bootstrap.+ `api/agents.js:258`, `api/_lib/agent-wallet.js:325` (`generateSolanaAgentWallet`),+ `:419` (`recoverSolanaAgentKeypair`), `:18` (`deriveKey`).+- **Custodial signing authority.** Platform can recover the keypair server-side+ to sign — so trading / sniping / x402 from the agent wallet is technically+ possible today.+- **Balance + activity API.** `GET /api/agents/:id/solana` returns live SOL+ balance with RPC failover + 60s cache; `…/solana/activity` returns tx history.+ `api/agents/solana-wallet.js:251`, RPC plumbing `api/_lib/agent-pumpfun.js:26`,+ `api/_lib/solana/connection.js`.+- **QR + copy primitives.** Zero-dep QR generator `src/erc8004/qr.js`; a Receive+ button + QR canvas + copy-address exist on the agent-detail page — but+ **owner-gated** (`bindWalletActions(isOwner)`), not an onboarding surface.+ `src/agent-detail.js:1784`, `pages/agent-detail.html:419-443`.+ Client balance poll: `src/agent-solana-wallet.js:287` (30s).+- **Pump.fun trade (real).** Bonding-curve + AMM buy/sell via `@pump-fun/pump-sdk`.+ `api/pump/[action].js` (buy/sell prep+confirm), instruction builders+ `api/_lib/pump-swap-ix.js`, `api/_lib/pump.js:130`. **But the product path is+ user-signed** (external wallet); only the sniper signs from the agent wallet.+- **Sniper engine (real, not deployed).** `workers/agent-sniper/` is a genuine+ autonomous trader: live PumpPortal feed + scoring (`index.js:97`,+ `scorer.js:21`), real v0 tx signing from the agent keypair+ (`executor.js`, `trade-client.js:29`, `keys.js:25`), serious pre-trade+ guardrails (`executor.js:51`), and position lifecycle+ (`positions.js:20`). PnL/track-record APIs are live: `api/sniper/{strategy,+ history,stream,leaderboard,trader}.js`, migration+ `api/_lib/migrations/20260615020000_agent_sniper.sql`.+- **x402 pay (real).** `api/x402-pay.js` builds/signs/submits Solana USDC x402+ payments; per-agent path exists (`:179` `loadAgentKeypairForUser`, `:611`+ routing). Asset `X402_ASSET_MINT_SOLANA` (`:263`); Solana payload builder `:320`.++**Gaps these tasks close (verified, not speculative):**++| # | Gap | Evidence |+|---|-----|----------|+| 01 | No single "agent wallet" product surface; legacy agents predating auto-provision may have no wallet; no guaranteed `walletReady` invariant | `api/agents.js:150,258`; no backfill migration |+| 02 | Funding UX is owner-only on agent-detail; no onboarding deposit panel (QR + `solana:` deep-link + live "funds received" confirmation) reachable right after creation | `src/agent-detail.js:1771` (`bindWalletActions(isOwner)`); `pages/create-agent.html:1493` success screen has no fund step |+| 03 | No authenticated endpoint to trade pump.fun **from the agent's own wallet**; only the sniper worker signs from it | `api/pump/[action].js` buy path is user-signed (`:524` verify-after-sign); guardrails live only inside `workers/agent-sniper/executor.js:51` |+| 04 | Buy/sell widget is SOL-only and user-wallet-only; no agent-wallet discretionary trade UI with full state design | `src/game/coin-buy.js` |+| 05 | Sniper worker is **not deployed** — long-lived process, Dockerfile exists, no Cloud Run pipeline / env / watchdog-alerting; nothing fires snipes in prod | `workers/agent-sniper/Dockerfile`; no deploy script; no cron (can't run on Vercel) |+| 06 | No UI to arm a sniper strategy or watch live positions/PnL, though every API exists | `api/sniper/strategy.js` (POST) has no form; `stream.js`/`history.js`/`leaderboard.js` unsurfaced |+| 07 | Graduated positions park forever in `error='graduated:awaiting_amm_exit'`; no automatic AMM exit | `workers/agent-sniper/executor.js:161` (`CoinGraduatedError`) |+| 08 | x402 falls back to a **shared platform wallet** when no `agentId` is passed; no in-product per-agent pay affordance / activity | `api/x402-pay.js:266` (`X402_AGENT_SOLANA_SECRET_BASE58`), `:611` |+| 09 | **No withdraw/sweep path** — the platform takes custodial SOL/SPL deposits with no way for the user to get funds out; no per-agent spend limits or custody audit trail surfaced | no withdraw endpoint; spend caps live only inside the sniper |+| 10 | No end-to-end proof of create→fund→trade→snipe→x402→withdraw on devnet; no one-pass Definition-of-Done sweep across the new surfaces | `tasks/devnet-smoke-trade.md` precedent |++## Execution order++Written to run **independently and in parallel** where possible. Concurrent+agents share one worktree — stage explicit paths, never `git add -A`, and+re-check `git status` before committing.++| # | Task | Wave | Blocks |+| -- | ----------------------------------------------------------------- | ---- | -------- |+| 01 | Agent-wallet foundation: `walletReady` invariant + backfill + hub | 1 | 02,04,06 |+| 02 | Public/onboarding deposit panel (QR + copy + deep-link + live) | 1 | 10 |+| 03 | Authenticated "trade from agent wallet" endpoint + shared guards | 1 | 04 |+| 04 | Agent-wallet pump.fun trade UI (buy/sell, all states) | 2 | 10 |+| 05 | Deploy sniper worker to Cloud Run (simulate→live, watchdog alerts)| 1 | 06,10 |+| 06 | Sniper arming UI + live positions/PnL dashboard | 2 | 10 |+| 07 | Automatic AMM exit for graduated positions | 1 | — |+| 08 | x402: per-agent wallet default + in-product pay + activity | 1 | 10 |+| 09 | Custody safety: withdraw/sweep, spend limits, key/audit hardening | 1 | 10 |+| 10 | End-to-end devnet smoke harness + Definition-of-Done sweep | 3 | — |++```+01 ─┬─→ 02 ─┐+ ├─→ 03 ─→ 04 ─┤+ └─→ 06 ←─ 05 ─┼─→ 10 (e2e + DoD sweep)+07 ── independent │+08 ── independent ─┤+09 ── independent ─┘+```++## Definition of done (whole plan)++- A first-time user creates an avatar and, on the same success screen, can scan a+ QR (or copy the address / tap a `solana:` deep-link) to fund the agent wallet,+ and sees the balance update live when SOL arrives.+- From the agent's own funded wallet the user can: buy & sell a pump.fun token,+ arm a sniper strategy that fires on real new launches, and pay an x402 endpoint+ — each with designed loading/empty/error/success states, hover/active/focus,+ mobile-responsive at 320/768/1440, a11y, and zero console errors/warnings.+- The user can withdraw all SOL and SPL tokens back to any address; spend limits+ and a custody audit trail exist.+- The sniper worker is deployed and running (simulate verified, live gated), with+ feed watchdog + alerting.+- Graduated positions exit automatically via AMM; no position parks indefinitely.+- `node scripts/agent-wallet-smoke.mjs` (task 10) proves the full loop on devnet,+ re-runnably.+- Every user-visible change has a `data/changelog.json` entry; `npm run build`,+ `npm run typecheck`, and `npm test` are clean; the **completionist** subagent+ passes on each task's changed files.++When every numbered task file in this directory has been shipped and deleted,+delete this README in the final commit.diff --git a/tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.md b/tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.mdnew file mode 100644index 000000000..8eb7ea2de--- /dev/null+++ b/tasks/irl-floor-anchor/01-pure-anchor-math-and-tests.md@@ -0,0 +1,95 @@+# 01 — Pure floor-anchor math + unit tests++> Epic IRL/floor-anchor · Size **S** · Foundation — run first.+> Mirrors the pure-policy pattern of [src/irl/room-anchor.js](../../src/irl/room-anchor.js)+> and its test [tests/irl-room-anchor.test.js](../../tests/irl-room-anchor.test.js).++## Goal++Make the math that turns an anchored XR pose into a durable GPS pin **pure,+shared, and unit-tested**. Today it is hand-rolled inline inside the host with+duplicated constants and zero test coverage — the one part of the feature whose+correctness silently determines whether a saved pin reloads where the user tapped.++## Why it matters++`persistFloorAnchor` re-derives metres-per-degree and a yaw-from-quaternion by+hand. The same projection already exists, unit-tested, in `room-anchor.js`. Two+copies drift; an untested copy on the *write* path means a sign error ships+silently and every saved anchor lands in the wrong place for every viewer. A pure+module with tests is the cheapest possible insurance and unblocks confident edits+in tasks 02/05/07.++## Current state (real lines)++- [src/irl.js:1631-1635](../../src/irl.js#L1631-L1635) `yawFromQuat(q)` — quaternion+ → yaw degrees, hand-rolled, untested.+- [src/irl.js:1658-1664](../../src/irl.js#L1658-L1664) `persistFloorAnchor` hand-rolls+ `mLat = 110540`, `mLng = 111320 * cos(lat)`, then+ `pinLat = lat + (-position.z / mLat)`, `pinLng = lng + (position.x / mLng)`.+- [src/irl/room-anchor.js:46-73](../../src/irl/room-anchor.js#L46-L73) already exports+ `M_PER_DEG_LAT`, `mPerDegLng(lat)`, `geoToLocal`, `localToGeo` — the exact same+ projection, with the exact same axis convention (`north = −Z`, `east = +X`).+- Convention comment to preserve: [src/irl/room-anchor.js:34-38](../../src/irl/room-anchor.js#L34-L38).++## What to build++### 1. A pure module — `src/irl/floor-anchor.js`++No DOM, no Three.js, no I/O — plain numbers in/out, exactly like `room-anchor.js`.++```js+// yaw (deg, 0–359, clockwise from local −Z) from a quaternion's (x,y,z,w).+export function yawDegFromQuat(x, y, z, w) { /* move src/irl.js:1631 here, normalized 0–359 */ }++// Anchored local-space pose (metres from the eye-level session origin) → the GPS+// pin to persist. Reuses room-anchor's localToGeo so there is ONE projection.+// localX = +east, localZ = +north-ish but world north = −Z, so pass −z as north.+export function anchorPoseToPin({ originLat, originLng, x, y, z, quat }) {+ const { lat, lng } = localToGeo(originLat, originLng, /*east*/ x, /*north*/ -z);+ const heading = ((Math.round(yawDegFromQuat(...quat)) % 360) + 360) % 360;+ return { lat, lng, heading, heightM: y, quat, source: 'webxr' };+}+```++Import `localToGeo` from `./room-anchor.js`. Keep the `heightM` sign note from+[src/irl.js:1670](../../src/irl.js#L1670) (negative = below eye level) in a comment.++### 2. Rewire the host to the module++In [src/irl.js](../../src/irl.js): delete the inline `yawFromQuat` and the+hand-rolled `mLat`/`mLng` block; have `persistFloorAnchor` call+`anchorPoseToPin({ originLat: gpsState.lat, originLng: gpsState.lng, x: position.x,+y: position.y, z: position.z, quat: [q.x,q.y,q.z,q.w] })` and forward the result+straight into the existing `savePin(... { heightM, yawDeg, quat, source })` call.+Behaviour must be **identical** — this is a pure extraction, not a redesign.++### 3. Tests — `tests/irl-floor-anchor.test.js`++Mirror [tests/irl-room-anchor.test.js](../../tests/irl-room-anchor.test.js):++- `yawDegFromQuat`: identity quat → 0; 90°/180°/270° yaw quats → 90/180/270;+ output always in `[0,360)`.+- `anchorPoseToPin`: a pose `+2 m east / +3 m north` of a known origin round-trips+ through `geoToLocal` back to ~`(2, 3)` (sign sanity — catches the `−z` mistake);+ `heightM` passes through unchanged; `source === 'webxr'`.+- Round-trip property: `anchorPoseToPin` then `geoToLocal` is identity within 1e-6.++## Acceptance checklist++- [ ] `src/irl/floor-anchor.js` is pure (no `import 'three'`, no DOM) and reuses+ `room-anchor.js`'s projection — no duplicated metre-per-degree constants.+- [ ] `persistFloorAnchor` produces byte-identical `savePin` args vs. before.+- [ ] `tests/irl-floor-anchor.test.js` passes; covers yaw, sign, height, round-trip.+- [ ] `npm test` green; `npm run typecheck` clean if the file opts into `// @ts-check`.++## Out of scope++Orientation *replay* on render-back (that's 02). This task only makes the **write**+path pure and tested; it does not change what the viewer does with the stored quat.++## Verify++`npm test -- irl-floor-anchor` passes. Then `npm run dev` → place a floor anchor+on a WebXR device (or the 07 harness) and confirm the saved pin's `lat/lng/heading`+match the pre-refactor values for the same tap.diff --git a/tasks/irl-floor-anchor/02-orientation-replay-and-tilt.md b/tasks/irl-floor-anchor/02-orientation-replay-and-tilt.mdnew file mode 100644index 000000000..55d2d576d--- /dev/null+++ b/tasks/irl-floor-anchor/02-orientation-replay-and-tilt.md@@ -0,0 +1,96 @@+# 02 — Orientation replay: make `anchor_quat` real (or retire it)++> Epic IRL/floor-anchor · Size **M** · Depends on 01.+> Closes the "stored but never used" gap on the render-back path.++## Goal++Decide and implement what the viewer does with the orientation captured at+placement. Right now the full tap-moment quaternion is written to the database and+returned to every client, then **silently ignored** when the agent is rendered.+Either use it (precise facing + optional surface tilt) or stop persisting it.+Shipping a dead column that looks like a feature is exactly the "half-wired" the+operating rules forbid.++## Why it matters++A pin you place facing a specific way should reload facing that way for everyone.+Today render-back only applies a rounded integer `anchor_yaw_deg`; the richer+`anchor_quat` — which also carries any surface tilt — is dropped. The result: a+flat-floor placement is *mostly* fine, but the data we collect promises fidelity+we never deliver, and a sloped or non-axis placement reloads subtly wrong.++## Current state (real lines)++- Write path stores it: [src/irl.js:1669-1673](../../src/irl.js#L1669-L1673)+ forwards `quat: [x,y,z,w]`; `savePin` carries it through+ [src/irl.js:1385-1387](../../src/irl.js#L1385-L1387).+- Server persists + returns it: [api/irl/pins.js:211](../../api/irl/pins.js#L211)+ (`anchor_quat JSONB`), returned at [api/irl/pins.js:540](../../api/irl/pins.js#L540).+- Render-back only uses height + yaw:+ [src/irl.js:1146-1156](../../src/irl.js#L1146-L1156) `pinHeightM` /+ `anchor_yaw_deg`, applied at [src/irl.js:1273-1330](../../src/irl.js#L1273-L1330)+ (`avatarRig.position` from `wp`, `avatarRig.quaternion.setFromAxisAngle(upY, …)`).+ **`anchor_quat` is never read in `src/irl.js`.**+- The agent content also never picks up surface tilt at placement time:+ [src/ar/webxr.js:176-178](../../src/ar/webxr.js#L176-L178) and+ [195-196](../../src/ar/webxr.js#L195-L196) set `content.position` only; the+ reticle gets the hit quaternion but the avatar does not.++## Decision (bake this in — do not block)++**Recommended:** keep humanoid avatars **upright** (yaw-only) for placement, but+make yaw *exact* by deriving it from `anchor_quat` when present (full float),+falling back to the rounded `anchor_yaw_deg` for legacy/gyro pins. Do **not** tilt+a standing humanoid to match a 30° ramp — it looks broken, not realistic. Reserve+true surface-tilt for a future non-humanoid prop mode and gate it behind an+explicit `anchor_tilt` flag, off by default.++This means: `anchor_quat` becomes the high-precision source for yaw, justifying its+existence, while we consciously ignore pitch/roll for humanoids and document why.++If after reading the code you conclude the rounded yaw is indistinguishable in+practice, the alternative is to **retire** the column: stop writing `quat`+(src/irl.js), drop it from the select/return (api/irl/pins.js), and migrate it out.+Pick one path; no dead field survives this task.++## What to build (recommended path)++1. Add `yawDegFromQuat` (from task 01's `floor-anchor.js`) as the render-back yaw+ source: in the pin pose resolver around [src/irl.js:1146-1156](../../src/irl.js#L1146-L1156),+ prefer `Array.isArray(pin.anchor_quat)` → `yawDegFromQuat(...pin.anchor_quat)`+ over the integer `anchor_yaw_deg`; keep `anchor_yaw_deg` as the fallback so gyro+ pins (no quat) and legacy rows are unaffected.+2. Keep `setFromAxisAngle(upY, yaw)` upright application+ ([src/irl.js:1330](../../src/irl.js#L1330)) — exact yaw, no tilt.+3. Document the deliberate pitch/roll drop with a one-line comment next to the+ resolver, referencing this task.+4. Round-trip test in `tests/irl-floor-anchor.test.js` (extend 01): a quat encoding+ yaw=137° survives `anchorPoseToPin` → `yawDegFromQuat` to within <0.5°, proving+ precision is actually retained end-to-end.++## Data / API changes++None if taking the recommended path (columns already exist). If retiring instead:+a guarded `ALTER TABLE irl_pins DROP COLUMN IF EXISTS anchor_quat` migration plus+removal from the select/return lists, and a changelog note.++## Acceptance checklist++- [ ] `anchor_quat` is either **consumed** on render-back (exact yaw, documented+ upright policy) or **fully retired** (write, select, return, column) — not dead.+- [ ] Gyro/legacy pins (no quat) render exactly as before — fallback intact.+- [ ] A WebXR pin placed facing a non-axis direction reloads within <1° of the tap+ facing on a second client (or the 07 harness asserts the float survives).+- [ ] No console errors; `npm test` + `npm run typecheck` green.++## Out of scope++Surface tilt for humanoids (intentionally rejected here) and the prop-mode tilt+flag (future). Occlusion is task 03.++## Verify++Place a floor anchor facing ~45° off a cardinal direction, reload `/irl` on a+second device near the spot, confirm the agent faces the same way — visibly tighter+than the old integer-rounded yaw.diff --git a/tasks/irl-floor-anchor/03-realworld-occlusion-depth.md b/tasks/irl-floor-anchor/03-realworld-occlusion-depth.mdnew file mode 100644index 000000000..9ca5e15a8--- /dev/null+++ b/tasks/irl-floor-anchor/03-realworld-occlusion-depth.md@@ -0,0 +1,82 @@+# 03 — Real-world occlusion (WebXR depth-sensing)++> Epic IRL/floor-anchor · Size **M** · Depends on 01/02; parallel with 04.+> The single biggest "is this real AR?" perception upgrade.++## Goal++Make the placed agent hide behind real-world geometry — a couch, a doorway, a+person walking in front — instead of always painting on top of the camera feed.+This is what separates a sticker pasted on video from an object that lives in the+room. Snapchat gets this via World Mesh; WebXR exposes the equivalent through the+`depth-sensing` feature, and it must degrade silently where unsupported.++## Why it matters++Our agent currently draws over everything (`depthTest:false` reticle aside, the+avatar has no occluder). The instant a real object should be in front of it, the+illusion breaks and the agent looks like a floating overlay. Occlusion is the+highest-leverage realism fix available to a browser AR app and it is the feature+users instinctively test by walking behind something.++## Current state (real lines)++- Session requests no depth: [src/ar/webxr.js:95-98](../../src/ar/webxr.js#L95-L98)+ `requiredFeatures:['hit-test']`, `optionalFeatures:['anchors','local-floor']`.+- The agent content is rendered normally against the transparent passthrough+ background ([src/ar/webxr.js:120-123](../../src/ar/webxr.js#L120-L123),+ render at [199](../../src/ar/webxr.js#L199)); nothing writes real-world depth.+- Three.js `WebGLRenderer.xr` is already in use (`renderer.xr.setSession`,+ `renderer.xr.getCamera`) — the integration point exists.++## What to build++1. **Request depth, optionally.** Add `'depth-sensing'` to `optionalFeatures` with+ the required descriptor:+ ```js+ optionalFeatures: ['anchors', 'local-floor', 'depth-sensing'],+ depthSensing: { usagePreference: ['gpu-optimized', 'cpu-optimized'],+ dataFormatPreference: ['luminance-alpha', 'float32'] },+ ```+ Feature-detect after start: `session.enabledFeatures?.includes('depth-sensing')`+ (guard — not all UAs populate it) and only enable the occlusion path when present.++2. **Occluder pass.** Use Three's WebXR depth path: set+ `renderer.xr.setSession(...)` (already done) and, where supported, build a depth+ occlusion using the per-frame `XRWebGLDepthInformation` from+ `frame.getDepthInformation(view)`. Prefer wiring through Three's built-in+ `WebXRDepthSensing` support if the installed three version exposes it (check+ `three/examples` / renderer flags for the version in `package.json`); otherwise+ implement a minimal occluder material that samples the depth texture and discards+ agent fragments behind real depth. Keep it in a new helper+ `src/ar/depth-occlusion.js` so `webxr.js` stays readable; dispose it in `_handleEnd`.++3. **Quality + perf.** Occlusion runs every frame — keep allocations out of the+ tick (reuse buffers, mirror the scratch-vector discipline in+ [src/ar/webxr.js:255-261](../../src/ar/webxr.js#L255-L261)). Target no measurable+ FPS regression on the tier budgets noted in the IRL perf system.++4. **Graceful degradation.** No `depth-sensing` → today's exact behavior, no error,+ no console noise. Optionally surface a one-time subtle hint+ ("Your device supports occlusion" is *not* needed — silence is the bar).++## Acceptance checklist++- [ ] On a depth-capable device (recent Android Chrome) the agent is correctly+ hidden when a real object/person is between it and the camera.+- [ ] On a non-depth device the session runs exactly as before — no thrown errors,+ no console warnings, button still works.+- [ ] No per-frame allocations added to the XR tick; FPS within perf budget.+- [ ] Depth resources disposed on exit ([src/ar/webxr.js:277-314](../../src/ar/webxr.js#L277-L314)).+- [ ] Reticle/anchor placement behavior unchanged.++## Out of scope++Using the depth texture for *placement* (depth-based instant hit-test) — that is a+nice follow-up but hit-test already places fine; this task is occlusion only.++## Verify++WebXR device: place the agent, walk a chair or your hand between phone and agent —+the agent is occluded. Toggle a non-depth UA (or simulate by removing the feature)+and confirm identical pre-occlusion behavior with a clean console.diff --git a/tasks/irl-floor-anchor/README.md b/tasks/irl-floor-anchor/README.mdnew file mode 100644index 000000000..5ca726a14--- /dev/null+++ b/tasks/irl-floor-anchor/README.md@@ -0,0 +1,71 @@+# IRL "Place on floor" — production-hardening epic++Make the WebXR floor-anchor feature (`/irl` → **Place on floor**) genuinely+production-ready: zero error paths, every state designed, parity across devices,+and the best AR placement UX on the web. Run each task in a fresh Claude Code+chat. Every task is grounded in real lines — read the cited code before writing.++## What the feature is today (verified ground truth)++On WebXR-capable devices (Android Chrome) the user taps **Place on floor**+([pages/irl.html:1602](../../pages/irl.html#L1602)), enters `immersive-ar` with a+hit-test reticle, points at the floor, and taps to bind the agent to a real+`XRAnchor`. The anchored pose is converted to a GPS pin and persisted so it+reloads near the same spot and nearby users see it.++- Session controller: [src/ar/webxr.js](../../src/ar/webxr.js) — `WebXRSession`+ (reticle, hit-test follow, `XRAnchor` on tap, content glue, restore-on-exit).+- Host wiring: [src/irl.js:1500-1689](../../src/irl.js#L1500-L1689) —+ `detectFloorAnchorSupport` (1542), `enterFloorAnchor` (1587),+ `onFloorAnchored` (1640), `persistFloorAnchor` (1658), `yawFromQuat` (1631).+- Persistence: [api/irl/pins.js](../../api/irl/pins.js) — `anchor_height_m`,+ `anchor_yaw_deg`, `anchor_quat`, `anchor_source` columns (209-214).+- Pure math the client should reuse: [src/irl/room-anchor.js](../../src/irl/room-anchor.js).+- Overlay markup: `#irl-xr-overlay` / `.irl-xr-hint` / `#irl-xr-error`+ ([pages/irl.html:1658-1666](../../pages/irl.html#L1658-L1666)).+- Server tests exist ([tests/api/irl-pins-anchor-pose.test.js](../../tests/api/irl-pins-anchor-pose.test.js));+ the **client** pose math is untested.++## Real gaps this epic closes++1. **No client-math tests** and duplicated metre-per-degree constants — fragile,+ unverifiable. → **01**+2. **`anchor_quat` is dead on render-back** — stored + returned, never applied;+ tilt/orientation is silently lost. → **02**+3. **No real-world occlusion** — agent always draws over furniture/people. → **03**+4. **Placement UX is minimal** — one static ring, no contact shadow, no confirm+ feedback, no haptics, no reduced-motion. → **04**+5. **No session-lifecycle hardening** — backgrounding, tracking loss, camera+ contention, anchor-reject, and the pre-GPS replay path are unguarded. → **05**+6. **iOS / non-WebXR users have no AR path** — button hidden, no parity. → **06**+7. **Not verifiable without a phone**, and no final DoD/changelog. → **07**++## Tasks++| # | File | Summary | Size |+|---|------|---------|------|+| 01 | [01-pure-anchor-math-and-tests.md](01-pure-anchor-math-and-tests.md) | Extract client pose→GPS math into a pure, unit-tested module reusing `room-anchor.js` | S |+| 02 | [02-orientation-replay-and-tilt.md](02-orientation-replay-and-tilt.md) | Wire (or retire) `anchor_quat`; precise yaw + surface-tilt decision on render-back | M |+| 03 | [03-realworld-occlusion-depth.md](03-realworld-occlusion-depth.md) | `depth-sensing` optional feature + occlusion so the agent hides behind real objects | M |+| 04 | [04-placement-ux-polish.md](04-placement-ux-polish.md) | Reticle states, contact shadow, confirm pulse, haptics, reduced-motion, copy pass | M |+| 05 | [05-session-lifecycle-hardening.md](05-session-lifecycle-hardening.md) | Visibility/tracking-loss/interruption/anchor-reject/pre-GPS-replay; zero console noise | M |+| 06 | [06-ios-nonwebxr-parity.md](06-ios-nonwebxr-parity.md) | Best-available AR placement on iOS + a polished, honest fallback everywhere else | L |+| 07 | [07-verification-harness-and-signoff.md](07-verification-harness-and-signoff.md) | Fake-XRFrame test harness, full-flow verify without a phone, DoD sweep + changelog | M |++## Run order++`01 → 02 → 05 → 03 → 04 → 06 → 07`++01 is the zero-risk foundation (pure math + tests). 02 and 05 are correctness and+must land before the polish (03/04). 06 is the largest and depends on the others+being stable. 07 closes the epic. 03/04 can run in parallel after 02/05.++## Standing rules for every task++- No mocks, no stubs, no TODOs — finish what you touch (CLAUDE.md hard rules).+- Every state designed: searching, found, anchored, denied, unsupported, error.+- Real device verification where possible; otherwise the 07 harness + a written+ note of what was and wasn't exercised on hardware. Never claim done unverified.+- Every user-visible change gets a `data/changelog.json` entry (tag `feature` or+ `improvement`); run `npm run build:pages` to validate it.+- $THREE is the only coin. Stage explicit paths; re-check `git status` before commit.diff --git a/tasks/irl-hardening/H1-privacy-invariant-test-suite.md b/tasks/irl-hardening/H1-privacy-invariant-test-suite.mdnew file mode 100644index 000000000..f269f3db2--- /dev/null+++ b/tasks/irl-hardening/H1-privacy-invariant-test-suite.md@@ -0,0 +1,100 @@+# H1 — Privacy-invariant test suite + build gate++> Epic IRL-Hardening · Size **M** · New `tests/api/irl-privacy.test.js` (+ siblings).+> The regression fence. Build this FIRST — every other task lands against it.++## Goal++A single, fast, offline test suite that asserts every location-privacy invariant+of `/irl` and **fails the build** the moment one regresses. Today the guarantees+exist in code and comments but are only partially pinned by tests; a future edit+could silently re-leak coordinates, an owner id, or a device token. After this+task, that edit goes red in CI instead of shipping.++## Why it matters++The founder's bar is "nobody's location ever leaks." A guarantee with no test is+a guarantee with a shelf life. This suite is the contract: it encodes the privacy+model so precisely that the safest way to change `/irl` is to keep it green.++## Current state (verified)++- `tests/api/irl-pins-room.test.js` already mocks `db.js`/`auth.js`/`rate-limit.js`/+ `granite-guardian.js` and drives the real `api/irl/pins.js` handler with a+ content-addressed `sqlMock`. **Reuse this harness pattern verbatim.**+- `tests/api/http-redact-url.test.js` already covers `redactUrl()` (shipped this pass).+- Invariants currently true in code but **not** all asserted:+ - Nearby projection omits `user_id` + `device_token`, exposes only `is_mine`.+ - `roundCoord()` coarsens `lat`/`lng`/`origin_lat`/`origin_lng` to `PUBLIC_COORD_DP=5`.+ - Radius is clamped to `[10, 60]`, default 40; missing lat/lng → 400.+ - `handleCalibrate` / outfit / PATCH / DELETE reject a non-owner (403/404).+ - `interactions.js` `pay` requires a valid signature + a `$THREE`/USDC mint.+ - `interactions.js` never stores the **viewer's** GPS — only the pin's `lat`/`lng`.+ - `IrlRoom._coarseViewerPos` returns a cell-centre±jitter point, never the input.++## What to build++### 1. `tests/api/irl-privacy.test.js` — the read/write feed invariants++Drive the real `pins.js` handler (copy the `irl-pins-room.test.js` mock setup):++```js+it('nearby feed never leaks an owner identifier', async () => {+ nearbyRow = { /* …with user_id + device_token set… */ };+ const { body } = await getNearby({ lat, lng });+ for (const p of body.pins) {+ expect(p).not.toHaveProperty('user_id');+ expect(p).not.toHaveProperty('device_token');+ expect(p).toHaveProperty('is_mine');+ }+});++it('nearby feed coarsens every outbound coordinate to ≤ 5 decimals', async () => {+ // assert lat/lng/origin_lat/origin_lng have ≤ PUBLIC_COORD_DP fractional digits+});++it('clamps radius to 60 m and rejects a missing fix', async () => { /* 400 path */ });+```++Add ownership-gate tests: a PATCH `calibrate`, an outfit change, a field PATCH,+and a DELETE from a non-owner (wrong `deviceToken`, wrong/absent session) each+return 403/404 and mutate nothing.++### 2. `tests/api/irl-interactions-privacy.test.js`++Drive `api/irl/interactions.js`: assert a `pay` without a valid signature or with+a non-`$THREE`/USDC mint is rejected; assert the inserted row carries the **pin's**+`lat`/`lng` (snapshotted from the pin), never a caller-supplied coordinate; assert+the `?mine=1` owner feed is null-guarded so an empty device token matches nothing.++### 3. `tests/irl-presence-privacy.test.js`++Unit-test `IrlRoom._coarseViewerPos(lat, lng)` (or extract the pure helper if it+isn't already importable): for a known precise input, the output must be inside+the geocell-6 cell but **not equal** to the input, proving raw GPS never survives.+Assert the room's `pins` MapSchema stays empty after a join (no roster broadcast).++### 4. Wire into the gate++These run under the existing `npm test` (vitest). Confirm they're picked up by the+default glob and that the Vercel build runs `npm test` (or add them to whatever+pre-deploy check exists). Keep the whole suite **offline** (all I/O mocked) and+under a few seconds so it's a cheap, always-on fence.++## Acceptance checklist++- [ ] `irl-privacy.test.js`, `irl-interactions-privacy.test.js`, `irl-presence-privacy.test.js` exist and pass.+- [ ] A deliberately reverted guarantee (e.g. temporarily return `user_id`, or drop `roundCoord`) turns the suite RED — verified by trying it.+- [ ] No real DB/RPC/network — fully mocked, runs in the existing vitest config.+- [ ] Suite added to the run that gates deploys; total added runtime < 5 s.+- [ ] `npm test` + `npm run typecheck` green.++## Out of scope++New product behavior — H1 only *locks in* existing + subsequently-built behavior.+The new invariants from H2/H3/H6 get their assertions added in those tasks.++## Verify++`npm test` green. Then locally revert one guarantee in `pins.js`, re-run, watch+the specific assertion fail with a clear message, restore it, confirm green again.diff --git a/tasks/irl-hardening/H2-device-token-transport.md b/tasks/irl-hardening/H2-device-token-transport.mdnew file mode 100644index 000000000..c7d7bf940--- /dev/null+++ b/tasks/irl-hardening/H2-device-token-transport.md@@ -0,0 +1,105 @@+# 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.diff --git a/tasks/irl-hardening/H3-proof-of-presence-read.md b/tasks/irl-hardening/H3-proof-of-presence-read.mdnew file mode 100644index 000000000..7635bbdd9--- /dev/null+++ b/tasks/irl-hardening/H3-proof-of-presence-read.md@@ -0,0 +1,107 @@+# 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).diff --git a/tasks/irl-hardening/README.md b/tasks/irl-hardening/README.mdnew file mode 100644index 000000000..2b7e93962--- /dev/null+++ b/tasks/irl-hardening/README.md@@ -0,0 +1,119 @@+# IRL Hardening — Location Privacy & Launch Readiness++The program that takes `three.ws/irl` from "works and is already well-built" to+**100% production-ready: zero-error, privacy-safe by construction, and the best+phone-camera UX we can ship.** The spine is the founder's non-negotiable: a+user's real-world location must never leak — not to another user, not to a log,+not to a third party, not by accident, not ever.++`/irl` lets anyone drop a 3D AI agent at a real GPS spot; anyone who physically+walks up sees it in AR, taps it for a profile + services card, and pays it via+x402. That product *is* location data. This epic makes handling that data+bulletproof and makes the privacy posture legible to the user.++---++## What is ALREADY shipped (do NOT rebuild — these are the baseline)++The discovery model and realtime layer are already privacy-hardened. Verify, build+on, and lock these in with tests (H1) — do not re-implement them.++| Guarantee | Where | State |+|---|---|---|+| Nearby feed never returns `user_id` / `device_token` | `api/irl/pins.js` allow-list projection | shipped — only `is_mine` boolean leaves |+| Tight proximity gate (10–60 m, default 40) + IP rate-limit on every read | `api/irl/pins.js` (`limits.publicIp`) | shipped — no bbox/window feed, no roster |+| Realtime presence is coarse by construction | `multiplayer/src/rooms/IrlRoom.js` `_coarseViewerPos` | shipped — geocell-6 centre + jitter; raw GPS discarded server-side |+| Realtime room never broadcasts a pin roster | `IrlRoom.js` (pins map never populated) | shipped — pins travel only via the per-viewer proximity read |+| Ghost presence is opt-in, default OFF | `src/irl-net.js` (`ghost` flag) | shipped — a viewer is counted, never positioned, unless they opt in |+| **Coordinates / device tokens scrubbed from error logs** | `api/_lib/http.js` `redactUrl()` | **shipped this pass** — 5xx never spills position/credential to console/Sentry/Telegram |+| **Public feed coordinates coarsened to ~1.1 m** | `api/irl/pins.js` `roundCoord()` (`PUBLIC_COORD_DP=5`) | **shipped this pass** — strips false precision / fingerprint tail |+| Responses are `no-store` + `referrer-policy` set | `api/_lib/http.js` `json()` | shipped — coordinate-bearing URLs aren't cached or sent in cross-origin Referer |+| Share composite carries no EXIF GPS | `src/irl/share-frame.js` | shipped — canvas PNG; URL fallback shares only the `avatar` param |++---++## The residual gaps this epic closes++After the audit, these are the real, grounded gaps between "well-built" and+"100% production-ready, zero-leak, best-UX":++1. **The device token is a bearer credential that still travels in URL query+ strings** (`?deviceToken=` on `/mine`, interactions, the SSE stream, DELETE).+ It unlocks a device's full pin **location history** — so it must leave URLs+ (which land in platform access logs, browser history, Referer). → **H2**+2. **The nearby read trusts caller-supplied coordinates** — a caller can query+ *any* lat/lng they aren't standing at. Rate-limit + radius cap blunt a sweep+ but don't bind the read to a genuine fix. → **H3**+3. **No user-facing privacy posture.** Placement gives no disclosure, no+ "approximate placement" option, no visible public/precise indicator. → **H4**+4. **No privacy center / right-to-be-forgotten.** No unpublish, no "remove all my+ pins," no "forget this device," no plain-language data summary. → **H5**+5. **Retention gap:** the reaper purges expired pins + orphaned reports but+ **never `irl_interactions`** — which store `viewer_device` and the pin's+ `lat`/`lng`. PII outlives the pin. → **H6**+6. **Anti-scrape posture is undocumented and may fail open.** The sweep threat+ model isn't pinned by tests, and limiter-degradation behavior for the read+ path isn't verified to fail closed. → **H7**+7. **Designed-state + accessibility coverage is uneven** across the permission,+ no-fix, location-off, offline, and privacy-disclosure states. → **H8**+8. **No single launch gate** that proves zero-error on real devices before the+ public flip. → **H9**+9. **No regression fence** around any of the privacy invariants above. → **H1**++---++## Task index++| # | File | Title | Size |+|---|---|---|---|+| **H1** | `H1-privacy-invariant-test-suite.md` | Privacy-invariant test suite + build gate | **M** |+| **H2** | `H2-device-token-transport.md` | Move the device-token credential out of URLs | **M** |+| **H3** | `H3-proof-of-presence-read.md` | Bind the nearby read to a genuine location fix | **L** |+| **H4** | `H4-placement-consent-approximate.md` | Placement consent + approximate-placement control | **M** |+| **H5** | `H5-privacy-center-forget-me.md` | Privacy center: visibility, export, delete / forget device | **L** |+| **H6** | `H6-retention-data-minimization.md` | Retention + data-minimization (reaper + interactions) | **S** |+| **H7** | `H7-anti-scrape-resilience.md` | Anti-scrape resilience, fail-closed reads, anomaly alerting | **M** |+| **H8** | `H8-designed-states-a11y.md` | Designed states, permission onboarding & accessibility | **M** |+| **H9** | `H9-launch-readiness-audit.md` | Launch-readiness audit & sign-off | **M** |++---++## Recommended run order++**Fence first, then harden, then expose, then polish, then ship:**++```+H1 (test fence) ──> everything else lands against a green privacy suite+H6 (retention) ── independent, small, do early+H2 (token transport) ─> H3 (proof-of-presence) ─> H7 (anti-scrape)+H4 (consent UX) ─> H5 (privacy center) ── user-facing privacy+H8 (states + a11y) ── alongside H4/H5+H9 (launch audit) ── LAST; gates the public flip+```++1. **Phase 1 — Fence & minimize:** H1, H6.+2. **Phase 2 — Close the credential + sweep holes:** H2, H3, H7.+3. **Phase 3 — Make privacy a feature the user can see and control:** H4, H5.+4. **Phase 4 — Polish & ship:** H8, H9.++---++## Ground rules for every task++- **Location is sacred.** No precise coordinate, device token, or owner identifier+ may ever reach another user, a log line, a third party, or a cached/shared+ surface. When in doubt, expose less. Every change is judged against H1's suite.+- **$THREE is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+ Never reference any other token anywhere — code, copy, tests, fixtures.+- **No mocks, no placeholders, no fake data.** Real Neon, real RPC, real wallet,+ real sensors. Errors handled at the boundary into a retryable designed state.+- **Best-UX bar.** Match Linear/Stripe/Vercel polish: every state designed,+ microinteractions present, mobile-first (this is a phone-camera product — mind+ iOS Safari's motion-permission gesture and no-WebXR path), accessible+ (keyboard, ARIA, focus, reduced-motion, contrast).+- **Zero-error definition of done.** No console errors/warnings from your code,+ Network tab shows real calls succeeding, `npm test` + `npm run typecheck` green,+ `git diff` self-reviewed, demoable to senior engineers.+- **Each task file is self-contained** — a fresh agent can execute it without this+ README. Update `data/changelog.json` for every user-visible change (tag+ `security` for privacy work) per CLAUDE.md.diff --git a/tasks/irl-privacy/01-ship-and-prove-lockdown.md b/tasks/irl-privacy/01-ship-and-prove-lockdown.mdnew file mode 100644index 000000000..834ea53bc--- /dev/null+++ b/tasks/irl-privacy/01-ship-and-prove-lockdown.md@@ -0,0 +1,72 @@+# 01 — Ship both surfaces safely + adversarial "no roster" proof++> Size **M** · Touches deploy of `api/` (Vercel) **and** the standalone Colyseus+> server (`multiplayer/`), plus a written red-team proof. No app-code changes+> expected unless the proof finds a hole.++## Goal++Get the location-privacy model **live on both deploy targets** and then *prove*,+adversarially and from the open internet, that an agent's location cannot be+obtained without physical presence. The implementation is done; this task makes+"it's actually shipped and actually locked" a verified fact, not an assumption.++## Why it matters++Two independent deploy targets back /irl: the Vercel API (`api/irl/*`) and the+standalone Colyseus multiplayer server (`multiplayer/src/index.js`, hosts the+`irl_world` room **and `/walk`**). A privacy fix that only landed on one is a+false sense of safety. Past incident: `/api/irl/*` endpoints 404'd in prod from a+stale deploy ([memory: irl-b2-agent-card]). And a realtime change can silently+regress `/walk`. The whole point of the feature is safety — so we verify it like+safety, not like a feature.++## What to do++### 1. Deploy, in order+- Deploy the **multiplayer server** first (it no longer depends on the API's+ publish webhook). Confirm boot logs show `irl_world` registered and **no**+ reference to the removed `irl-registry` / `irl-publish-auth` / `/internal/irl-publish`.+- Deploy the **Vercel API**. Confirm the live commit is the one containing the+ lockdown (`git`-verify against the deployments API, per [memory: vercel-symlink-build-trap]).+- Guard against `npx vercel build` clobbering `api/*.js` ([memory: vercel-build-clobbers-api]).++### 2. Adversarial proof (write results to `reports/irl-privacy-proof.md`)+Run each from an **unauthenticated, off-platform** client and record the result:++- **No window feed.** `GET /api/irl/pins?bbox=…` (any box, with and without an+ `x-mp-internal` header) → must be `400` (missing lat/lng), never a multi-pin body.+- **Radius is hard-capped.** `GET /api/irl/pins?lat&lng&radius=100000` → the+ returned set is confined to a tight box; a pin known to be ~200 m away is **not**+ returned. (Place a throwaway test pin via the real POST, stand it 200 m off, verify.)+- **Rate limit bites.** A scripted grid sweep of nearby reads trips `429` quickly+ (the `limits.publicIp` ceiling) — a global harvest is impractical.+- **Realtime carries no pins.** Connect a raw `colyseus.js` client to an+ `irl_world` geocell (the same join `src/irl-net.js` does) and dump+ `room.state` — `state.pins` must be **empty**; only `viewers` (coarse, jittered)+ and `reaction` messages appear. This is the headline proof: joining a cell hands+ you no coordinates.+- **No owner ids.** The nearby projection contains no `user_id` / `device_token`.+- **`/walk` unaffected.** Join a `walk_world` room; movement/presence still work.++### 3. If any check fails+Fix the root cause in app code (not the test), re-deploy, re-run. Zero failures is+the bar. There is always a correct fix — find it.++## Acceptance checklist++- [ ] Multiplayer server live; boot logs clean; `/walk` verified working.+- [ ] Vercel API live on the lockdown commit (verified via deployments API).+- [ ] `reports/irl-privacy-proof.md` committed with all six checks **passing**,+ each with the exact request and observed response.+- [ ] The raw-WS dump showing `state.pins` empty is captured verbatim in the proof.+- [ ] A throwaway test pin used for the radius proof is deleted afterward.++## Out of scope++UX, copy, new tests in CI (that's 07). This is deploy + manual adversarial proof.++## Verify++The proof doc IS the verification. A reviewer should be able to re-run every+command in it and reproduce the same safe result.diff --git a/tasks/irl-privacy/02-discovery-onboarding-empty-state.md b/tasks/irl-privacy/02-discovery-onboarding-empty-state.mdnew file mode 100644index 000000000..01d5deb1d--- /dev/null+++ b/tasks/irl-privacy/02-discovery-onboarding-empty-state.md@@ -0,0 +1,72 @@+# 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.diff --git a/tasks/irl-privacy/README.md b/tasks/irl-privacy/README.mdnew file mode 100644index 000000000..907a44589--- /dev/null+++ b/tasks/irl-privacy/README.md@@ -0,0 +1,83 @@+# Epic: IRL location privacy → production++The /irl world lets anyone place a 3D AI agent at a real-world spot and come+across other people's agents in AR. We just changed the trust model: **an agent's+location is private.** It is revealed to a viewer ONLY when they are physically+within a tight radius of it (the per-viewer proximity read) — never as a list, a+map, a neighborhood feed, or a realtime roster. You discover an agent by walking+up to its spot and pointing your camera; you cannot browse where agents are.++This epic takes that model from *implemented + unit-tested* to **100% production+ready, zero-error, shipped, and the best discovery UX on the planet** — without+ever weakening the privacy guarantee.++---++## The hard invariant (every task inherits this — do not break it)++> **No surface — API response, realtime channel, UI, deep-link, share image,+> dashboard, or log — may let anyone obtain the location of an agent they are not+> physically standing near.**++Concretely, all of these must stay true after every task:++- The realtime room (`multiplayer/src/rooms/IrlRoom.js`) carries **presence ++ reactions only** — never pins. A client that joins a geocell receives **zero**+ pin coordinates in its synced state.+- The only read that returns another user's pin coordinates is the nearby GET in+ `api/irl/pins.js`, scoped to the caller's **own** live position, **hard-capped**+ to a tight radius (`Math.min(60, Math.max(10, … ?? '40'))`) and IP rate-limited+ (`limits.publicIp`). There is no bbox/window feed.+- Owner identifiers (`user_id`, `device_token`) are **never** projected into any+ public feed.+- The `?mine` feeds return coordinates only for the authenticated/device owner's+ own pins.++If a task seems to require relaxing any of the above to ship — stop and flag it.+The privacy model wins; find another way.++---++## Current shipped state (ground truth, do not re-derive wrong)++- **API** — `api/irl/pins.js`: nearby GET returns pins within `NEARBY_RADIUS`+ around the caller, projecting public fields + the room-frame columns+ (`room_id`, `rel_east_m`, `rel_north_m`, `origin_lat`, `origin_lng`,+ `origin_yaw_deg`) but never owner ids. No `?bbox`. No realtime publish.+ Rate-limited on every GET. `report.js` hides on threshold (poll picks it up).+- **Client** — `src/irl.js`: `NEARBY_RADIUS = 40`; pins come *only* from the+ proximity poll (`startPinPolling`/`stopPinPolling`, `POLL_INTERVAL_MS = 10000`,+ `loadNearbyPins` + `refreshKnownPin`); the WS (`src/irl-net.js`, `IrlNet`) is+ presence + reactions only. Rendering is room-aware via `pinWorldPos`/`pinRoom`+ (shared room-anchor — `src/irl/room-anchor.js`). HUD: `updateNearbyBadge`+ (`#irl-nearby-badge`), `setNetPill` (`#irl-net-pill`), `updatePresence`+ (`#irl-presence-chip`), confidence ring, opt-in ghosts.+- **Realtime** — `multiplayer/src/rooms/IrlRoom.js` is presence + reactions only;+ the publish webhook + `irl-registry`/`irl-publish-auth` and the API-side+ `irl-publish`/`irl-realtime` modules are deleted.+- **Tests** — `tests/api/irl-pins-location-guards.test.js` proves no window feed,+ the hard radius cap, rate-limiting, and no owner-id projection; room-frame and+ presence/reaction suites are green.++## Definition of done (the whole epic)++Per the root `CLAUDE.md`: real APIs only, no mocks/placeholders, every state+designed (loading/empty/error/populated/permission-denied), accessible, responsive+at 320/768/1440, no console errors/warnings, existing tests green + new coverage,+exercised in a real browser/device, and a holder-readable changelog entry for each+user-visible change. The feature should be something you'd demo to a room of+senior engineers and screenshot to share.++## Tasks (suggested order)++1. **01** — Ship both surfaces safely + adversarial "no roster" proof.+2. **02** — Discovery onboarding + the designed empty state (teach "stumble upon").+3. **03** — Proximity-arrival cue + non-map directional hint (the delight).+4. **04** — GPS-edge hysteresis / anti-flicker (zero jank at the radius boundary).+5. **05** — Location-leak audit across every sibling endpoint, deep-link, share.+6. **06** — Every state, permission, and accessibility pass.+7. **07** — E2E + regression coverage that locks the invariant in CI.+8. **08** — User-facing "how location works" trust surface + docs + changelog.++Each task file is self-contained: read it, read the real lines it cites, ship it,+check its acceptance list, then delete the task file in the shipping commit.diff --git a/tasks/irl-room-anchor/R1-place-around-me.md b/tasks/irl-room-anchor/R1-place-around-me.mdnew file mode 100644index 000000000..f9509c847--- /dev/null+++ b/tasks/irl-room-anchor/R1-place-around-me.md@@ -0,0 +1,153 @@+# R1 — "Place agents around me" (room authoring UI)++> Epic R · Size **L** · Edits `src/irl.js`, `pages/irl.html`, `src/irl.css`.+> Depends on the committed engine (`7bf9cecf`); see `tasks/irl-room-anchor/README.md`.+> **This is the gate task — the feature is not reachable by a user without it.**++## Goal++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.diff --git a/tasks/irl-room-anchor/README.md b/tasks/irl-room-anchor/README.mdnew file mode 100644index 000000000..af7cfaaac--- /dev/null+++ b/tasks/irl-room-anchor/README.md@@ -0,0 +1,163 @@+# Epic R — IRL Room Anchoring (shared, room-scale, world-locked agents)++Ship the ability to **pin 3D AI agents to fixed spots in a real room** — place an+agent on the couch to your right, three behind you, nothing on the left wall —+so that with the camera on you only see each agent when you physically turn to+face its spot, exactly like a person sitting there. The layout is identical for+everyone who opens `/irl` at that location.++This epic finishes a feature whose **engine is already built, committed, and+green** (commit `7bf9cecf`). What remains is the authoring UX, cross-user+alignment, the precision layer, production hardening, and on-device QA.++The bar for this epic is the user's words: **100% production-ready, zero error,+shipped complete, professional, best-possible UX.** A task is not done until its+Definition of done is fully met in the running app — not "written," *met*.++---++## Why room-scale needs its own frame (the core idea)++Consumer GPS is accurate to ~5–15 m. At city scale that's fine; at **room+scale it is useless** — your couch (3 m right) and your wall (3 m left) are well+inside the same GPS noise, so per-agent GPS lets a layout smear and even swap+sides, and it differs phone-to-phone. The fix, already implemented:++- **GPS is the index, not the precision.** It only decides which room you load+ and roughly places the cluster in the world. It never positions an agent.+- **Compass is the shared north reference** so two phones agree on the frame+ without a visual scan.+- **Each agent stores an EXACT offset (metres east/north) from one shared room+ origin.** Relative geometry is therefore exact and identical for everyone — GPS+ noise translates the whole cluster together, never smears it internally — so+ you **calibrate the room once**, not each agent.+- **WebXR floor anchors / a manual nudge refine** the origin where the device can.++This is the same layered, graceful-degradation model the best AR systems use+(Niantic VPS, ARCore Geospatial). We do every layer and fall back cleanly.++---++## Already built — DO NOT rebuild (commit `7bf9cecf`)++Read these before writing anything; build on them, match their conventions.++- **Pure math core — `src/irl/room-anchor.js`** (16 unit tests in+ `tests/irl-room-anchor.test.js`). Coordinate conventions match `src/irl.js`+ exactly: **North = −Z · East = +X · Y up · 1 unit = 1 m**; compass bearing+ 0–359° clockwise from north; world yaw = `−(deg·π/180)`. Exports:+ `geoToLocal`, `localToGeo`, `bearingDistanceToLocal`, `localToBearingDistance`,+ `localToTrueNorth`, `roomOriginWorld`, `agentWorldPosition`, `compassToYaw`,+ `placeAround`. **Use these; do not re-derive geodesy.**+- **Persistence + API — `api/irl/pins.js`.** Six columns on `irl_pins`:+ `room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg`+ (inline `ALTER TABLE … ADD COLUMN IF NOT EXISTS`; partial index `irl_pins_room`).+ POST accepts an optional `room` block (contract below), validates/clamps+ (`ROOM_ID_RE = /^[a-z0-9-]{1,64}$/`, `REL_MAX_M = 500`, null-island origin+ rejected) and falls back to a standalone pin if invalid. The nearby + bbox+ SELECTs and the projection carry the room columns to viewers **without leaking+ owner identity**. Covered by `tests/api/irl-pins-room.test.js` (5 tests).+- **Viewer render path — `src/irl.js`.** `pinRoom(pin)` normalizes the room+ fields; `pinWorldPos(pin)` resolves a room pin through its shared origin+ (`roomOriginWorld` + `agentWorldPosition`) and falls back to absolute GPS for a+ standalone pin. Wired into `spawnNearbyPin` and the `onGPSPosition`+ reprojection loop. DEV harness: `window.__irlSeedRoom()` lays the canonical+ couch-right / three-behind / wall-left scene; `window.__irlRoomCheck()` asserts+ the world sides.++The turn-to-see behaviour itself (camera passthrough, gyro/compass-driven camera,+frozen-camera world-lock, A3 absolute-bearing anchoring) **already shipped** —+see `src/irl.js` `onDeviceOrientation`, `anchorGpsPin`, `setLocked`. Rooms ride+that machinery; you are adding the authoring + alignment layers on top.++---++## Delivery path: REST proximity read, NOT realtime++The IRL realtime room (`irl_world`) was deliberately reduced to **presence ++reactions only**; pins no longer sync over the socket (privacy — no broadcasting+a browseable GPS roster of a ~1 km cell). **Shared rooms are delivered by the+per-viewer `GET /api/irl/pins` proximity read + poll fallback**, which already+carries the room fields. Do not re-introduce a pin broadcast. R4 reconciles the+now-dormant realtime additions (`IrlPin` schema fields, `irl-net` relay,+`normalizeStreamPin` room fields) — keep them dormant/forward-compatible or+remove them; never leave dead code that implies a live pin stream.++---++## The POST `room` contract (stable — build against it)++```jsonc+POST /api/irl/pins+{+ "lat": 37.7749, "lng": -122.4194, // absolute coord (GPS index + legacy); the+ // client computes it via placeAround()+ "heading": 270, // agent facing, compass deg (relYawDeg)+ "avatarUrl": "/api/avatars/…glb",+ "avatarName": "Scout",+ "deviceToken": "<uuid>",+ "agentId": "<id|null>",+ "anchor": { "heightM": 0, "yawDeg": 270, "source": "gyro-gps" }, // A2 pose+ "room": { // OPTIONAL — present to anchor into a room+ "id": "living-room-7", // slug, ^[a-z0-9-]{1,64}$ (client-derived)+ "originLat": 37.7749, // shared room origin (first placement's GPS)+ "originLng": -122.4194,+ "originYawDeg": 0, // 0 = true-north-aligned (compass calibrated)+ "relEast": 3.0, // metres east of origin (clamped ±500)+ "relNorth": 0.0 // metres north of origin+ }+}+```++Compute the `room` values with `placeAround({ originLat, originLng, viewerLat,+viewerLng, bearingDeg, distM, faceViewer })` — it returns `{ relEast, relNorth,+relYawDeg, lat, lng }`. Send `lat/lng` from its result, `heading = relYawDeg`,+and the `room` block. An invalid block silently degrades to a standalone pin, so+always send a valid one in room mode.++---++## Build order++1. **R1 — Place agents around me** (authoring UI). The user-facing core; nothing+ ships without it.+2. **R2 — Room alignment + one-gesture calibrate** (makes "shared at location"+ correct and honest).+3. **R3 — WebXR floor-anchor refine** (the precision layer; Android, iOS falls+ back cleanly).+4. **R4 — Production hardening + cleanup** (every state, a11y, perf, security,+ dead-code/realtime reconcile, console-clean, changelog, Definition-of-done sweep).+5. **R5 — On-device QA** (the verification protocol; this is what proves "done").++R1 is the gate. R2–R3 can proceed in parallel once R1's room session exists.+R4 + R5 run last, over the whole surface.++---++## Invariants every task must honour++- **Coordinate conventions** (above) are law; reuse `room-anchor.js`, never+ re-derive. Add a unit test for any new pure helper.+- **No mocks, no fake data, no placeholders, no `setTimeout` fake progress, no+ TODOs, no commented-out code.** Real APIs, real async, every path wired+ (CLAUDE.md hard rules). Errors handled at boundaries; ship working fallbacks.+- **$THREE is the only coin.** Never name, hardcode, or render any other token in+ code, copy, fixtures, or tests. CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.+- **Privacy holds:** never surface another owner's `user_id`/`device_token`; keep+ the bbox feed internal-only; never broadcast a pin roster.+- **Concurrent worktree:** other agents edit `src/irl.js`, `api/irl/pins.js`,+ `multiplayer/*` on `main` simultaneously. Stage **explicit paths only** (never+ `git add -A`), re-check `git status`/`git diff --staged` right before any+ commit, and watch for `__defProp`/`createRequire` bundle clobber in `api/*`.+- **Definition of done (every task):** code written + wired + reachable in the UI;+ every state designed (loading skeleton / empty / error / populated / overflow);+ hover/active/focus + keyboard + ARIA on interactive elements; `npm run+ typecheck` clean; `npm test` green (single-worker if cross-file mock-bleed+ appears — see `tests/api/irl-pins-room.test.js` for the `vi.resetModules()`+ pattern); `vite build` clean; no console errors/warnings from our code;+ on-device behaviour verified per R5 (or explicitly flagged as the one+ post-deploy step); changelog entry appended once user-visible; `git diff`+ self-reviewed line-by-line.++When this epic is genuinely shipped and verified, delete these files+(`git rm tasks/irl-room-anchor/*`) per `tasks/CLEANUP-PLAN.md`.