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
Add IBM x402, IRL location-control, and follow-up task/prompt specs
nirholas78177b54a527
diff --git a/prompts/avatar-animation-hardening/02-root-motion-cross-rig.md b/prompts/avatar-animation-hardening/02-root-motion-cross-rig.mdnew file mode 100644index 000000000..ec49310f9--- /dev/null+++ b/prompts/avatar-animation-hardening/02-root-motion-cross-rig.md@@ -0,0 +1,68 @@+# Task 2 — Root-motion correctness across rig conventions++> Read [00-README.md](./00-README.md) first. **Depends on Task 1** (full bind correction) — read+> its handoff note. Follow [CLAUDE.md](../../CLAUDE.md); the `cz.glb` no-regression bar is absolute.++The shipped fix rotates the Hips **position** track by the same correction `C` used on the Hips+**quaternion**. That is exact only when the Hips' parent armature rotation equals `C⁻¹` — true for+the standard Mixamo `+90°X armature / −90°X Hips` split, but **not general**. For locomotion+clips (walk, run, jump with travel), root motion must move the body in the correct world direction+and distance on *any* rig, or a walking avatar drifts sideways, sinks, or moonwalks.++## What to build++### 1. Correct hip position by the true parent-frame difference+- Root motion lives in the Hips' **parent** local frame. The clip authors it in the authoring+ rig's Hips-parent frame (cz.glb: armature with no rotation → world-aligned Y-up). On the target+ rig, the Hips' parent may carry an arbitrary rest rotation (Mixamo armature `+90°X`, others+ differ).+- In [src/animation-retarget.js](../../src/animation-retarget.js), compute the position+ correction from the **parent's** rest-frame difference rather than reusing the Hips' own bone+ correction. You will need the target Hips' parent rest world-rotation; capture it alongside+ `_canonicalRest` (extend `canonicalRestMapFromObject` / the attach-time capture, or add a small+ dedicated capture for the Hips parent). Keep the module pure.+- Preserve hip **scaling** (`hipScale`) — rotation and uniform scale compose; document the order.+- Result: world-space root displacement per frame on the target equals the authoring world-space+ displacement (scaled for height), regardless of the rig's axis convention.++### 2. Validate locomotion on multiple conventions+- Reconstruct each rig's bone graph (cz.glb, michelle.glb, and at least one more convention —+ e.g. a Ready Player Me or synthetic rig with a non-`±90` armature rotation) and, for a walk and+ a jump clip, assert:+ - **Direction:** net world XZ travel points the same way on all rigs (no sideways drift).+ - **Verticality:** the body does not sink into or float above the ground plane beyond tolerance.+ - **In-place clips stay in place:** idle/wave/celebrate produce ~zero net XZ travel on every rig.+- Add these as deterministic unit tests (no browser, no GLTFLoader — raw GLB parse + world-matrix+ composition).++### 3. Browser verification+- `npm run dev`; play walk/run on michelle.glb and cz.glb in `/pose` or `/walk`. Confirm the+ avatar travels forward correctly, feet plant (no gross sliding), no console errors. Compare the+ two rigs moving in the same direction. Report what you saw.++## Definition of done+- Hip position is corrected by the parent-frame difference; `cz.glb` output is unchanged+ (identity parent correction → byte-for-byte equal — locked test).+- Locomotion direction/verticality/in-place invariants hold across ≥3 rig conventions+ (unit-tested) and are confirmed in a browser on Mixamo + Avaturn rigs.+- `npm test` + `npm run typecheck` green.+- Changelog entry if user-visible (e.g. walking avatars travel correctly on every rig).+- `completionist` run; findings fixed. Handoff note for Task 4 (add locomotion cases to the+ regression corpus).++Do not push unless the user approves (then both remotes).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++The moment every item above is **built, wired, verified, and committed**, remove it in the same+change:++```bash+git rm "prompts/avatar-animation-hardening/02-root-motion-cross-rig.md"+```++Stage the deletion in the completion commit. A file that still exists is unfinished work.diff --git a/prompts/avatar-animation-hardening/03-ingest-rig-normalization.md b/prompts/avatar-animation-hardening/03-ingest-rig-normalization.mdnew file mode 100644index 000000000..736a086c7--- /dev/null+++ b/prompts/avatar-animation-hardening/03-ingest-rig-normalization.md@@ -0,0 +1,71 @@+# Task 3 — Canonicalize rig orientation at avatar ingest++> Read [00-README.md](./00-README.md) first. Can run in **parallel** with Tasks 1/5. Follow+> [CLAUDE.md](../../CLAUDE.md).++Runtime bind correction (Tasks 1–2) makes any rig animate correctly *when played*. This task adds+**defense-in-depth at the source**: when an avatar is created/uploaded, normalize its rig to the+canonical convention so the stored GLB needs **zero** runtime correction — cheaper, simpler, and a+guarantee that every avatar in the catalog is already "good." Runtime correction stays as the+safety net for anything not re-ingested.++## What to build++### 1. Extend the canonicalizer to orientation+- [src/glb-canonicalize.js](../../src/glb-canonicalize.js) already rewrites **bone names** to+ canonical (`canonicalizeGlbBoneNames`). Add an orientation pass that bakes the up-axis+ convention into the canonical form: flatten the `armature(+R) / Hips(−R)` split so the stored+ rig matches the reference (`cz.glb`: armature rest ≈ identity, `Hips` rest ≈ identity), with the+ geometry and skin weights preserved so the avatar looks identical at bind.+- The transform must be **mathematically lossless for appearance**: bind-pose vertices in world+ space are unchanged; only the bone/local-frame bookkeeping moves. Verify by comparing world+ positions of skinned vertices (or bone world transforms) before/after.+- Reuse `canonicalizeBoneName` / `normalizeBoneName`+ ([src/avatar-export.js](../../src/avatar-export.js)) — do not add a third bone-name parser.++### 2. Wire it into the ingest path+- Find where avatars are processed before R2 storage (avatar create/upload/generate endpoints+ under `api/`; the decoration shape is in [api/_lib/avatars.js](../../api/_lib/avatars.js)). Run+ the normalization there so new avatars are stored canonical. Read the path end-to-end before+ editing; match existing patterns (storage keys, presigning, error handling at the boundary).+- Make normalization **idempotent**: re-running on an already-canonical GLB (e.g. `cz.glb`) is a+ no-op (no bone renames, no orientation change). Log a concise summary (bones renamed,+ orientation corrected y/n) — no noisy per-bone logging.+- Do **not** bulk-rewrite the existing catalog in this task; that is an ops migration. Ensure+ existing avatars keep working via the runtime correction (they do). Note the catalog-backfill as+ a follow-up if warranted.++### 3. Correctness+- An ingested Mixamo rig (`michelle.glb` fixture) comes out with canonical bone names and a Hips+ rest ≈ identity, plays every featured clip upright with the runtime correction reduced to a+ no-op, and is visually identical at bind pose to the input.+- Non-humanoid / unrecognized rigs pass through untouched (don't corrupt props or rigs the+ canonicalizer can't map).++## Definition of done+- `glb-canonicalize.js` normalizes orientation losslessly + idempotently; unit-tested (appearance+ invariance, idempotency on cz.glb, Mixamo → canonical Hips-identity).+- Ingest path runs normalization on new avatars; errors handled at the boundary; concise logging.+- A re-ingested Mixamo avatar needs no runtime correction and is visually identical — verified+ (numeric vertex/bone-world comparison + a browser spot-check).+- `npm test` + `npm run typecheck` green. Changelog entry if user-visible (new uploads animate+ perfectly regardless of source tool).+- `completionist` run; findings fixed. Handoff note: whether a catalog backfill is recommended and+ how it would run.++Do not push unless the user approves (then both remotes).++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++The moment every item above is **built, wired, verified, and committed**, remove it in the same+change:++```bash+git rm "prompts/avatar-animation-hardening/03-ingest-rig-normalization.md"+```++Stage the deletion in the completion commit. A file that still exists is unfinished work.diff --git a/tasks/agent-wallet-trading/05-deploy-sniper-worker.md b/tasks/agent-wallet-trading/05-deploy-sniper-worker.mdnew file mode 100644index 000000000..3a1e06d3f--- /dev/null+++ b/tasks/agent-wallet-trading/05-deploy-sniper-worker.md@@ -0,0 +1,104 @@+# Task: Deploy the agent-sniper worker to Cloud Run — simulate→live, with feed watchdog + alerting++## Context++The sniper engine (`workers/agent-sniper/`) is real and production-grade — it+subscribes to the live PumpPortal feed, scores launches, signs v0 transactions+from each agent's own wallet, enforces serious guardrails, and manages position+exits (see README and task 03). **It is not deployed.** It is a long-lived process+that holds a websocket feed open, so it cannot run on Vercel; a `Dockerfile`+exists but there is no deploy pipeline, no documented production env, no cron, and+no watchdog/alerting. Until this ships, **nothing snipes in production** — this is+the single biggest unlock for "snipe new pump.fun tokens."++Reference precedent: `world.three.ws` runs on Cloud Run (memory:+`world-three-ws-hyperfy`), so the platform already has a Cloud Run deploy pattern+to follow.++## Goal++The agent-sniper worker deployed and running on Cloud Run as a long-lived+background service: started in `simulate` mode and verified end-to-end against the+real feed, with `live` mode gated behind explicit config; documented env; a feed+watchdog that auto-reconnects; and ops alerting on disconnect/error.++## Files to Read First++- `workers/agent-sniper/README.md` — operating model, modes, known graduation gap+- `workers/agent-sniper/index.js:1-206` — entrypoint, feed hold-open (`:97`),+ position sweep loop (`:161`), watchdog hooks+- `workers/agent-sniper/config.js:28-92` — `loadConfig()` required env+ (`DATABASE_URL`, `JWT_SECRET`, RPC for live, `SNIPER_MODE`)+- `workers/agent-sniper/Dockerfile` — existing image (no HTTP port, background worker)+- `workers/agent-sniper/executor.js:51-85` — guardrails enforced before any signature+- `api/_lib/agent-pumpfun.js:26` — RPC selection (`SOLANA_RPC_URL`, Helius)+- Observability: `tasks/.../observability-stack` precedent, `TELEGRAM_ALERTS_CHAT_ID`,+ `/api/client-errors` log conventions, uptime cron + `/status` page+- `world.three.ws` Cloud Run deploy/repair notes for the house pattern++## What to Build / Do++1. **Deploy pipeline.** A documented, repeatable deploy of `workers/agent-sniper`+ to Cloud Run (build image → push → deploy) with `--no-cpu-throttling` (it must+ keep running between requests) and min-instances ≥ 1 so the feed stays open. Put+ the script under `scripts/` (e.g. `scripts/deploy-sniper.mjs` or a documented+ `gcloud`/`make` recipe), not in the repo root.+2. **Production env.** Document every required var (`DATABASE_URL`, `JWT_SECRET`,+ `SOLANA_RPC_URL`/`HELIUS_API_KEY`, `SNIPER_MODE`, budget/throttle knobs) and where+ it's set (Cloud Run secret/env). `loadConfig()` already throws loudly on missing+ vars — verify it fails closed. Never commit secrets.+3. **Simulate first.** Deploy with `SNIPER_MODE=simulate`, confirm it connects to+ the live PumpPortal feed, scores real launches, and records simulated positions —+ with no real spend. Capture evidence (logs showing scored mints + simulated buys).+4. **Gate live mode.** `SNIPER_MODE=live` must require deliberate config + a funded+ agent wallet; the existing guardrails (budget/per-trade/concurrency/price-impact/+ kill switch) must be confirmed active in the deployed env. Document the cutover.+5. **Feed watchdog + auto-reconnect.** Ensure the worker detects a dropped feed and+ reconnects with backoff (extend `index.js` if the watchdog is incomplete). A+ silent dead feed is the worst failure mode — it must self-heal and alert.+6. **Alerting + health.** On feed disconnect, repeated RPC failure, or executor+ error, emit an ops alert (Telegram via `TELEGRAM_ALERTS_CHAT_ID`, matching the+ existing observability stack). Add a lightweight health signal (heartbeat+ row/log) the uptime cron / `/status` page can read so "is the sniper alive?" is+ answerable without SSHing in.++## Constraints++- No secrets in the repo or image. Keypairs are never baked in — the worker decrypts+ per-agent keys at runtime via the existing key module.+- Fail closed: missing/invalid config must stop startup loudly, never silently run+ degraded or in the wrong mode.+- Live mode is opt-in and gated; the default deploy is `simulate`. Do not flip an+ agent to live without a funded wallet and explicit config.+- Don't weaken any guardrail to make deploy easier. The deployed worker enforces the+ same caps/breakers as code.+- This worker is a consumer of the feed, not the missing pump.fun bot (memory:+ `pumpfun-graduations-bot`) — don't reintroduce a non-existent upstream.++## Success Criteria++- The worker runs on Cloud Run, stays up (min-instances ≥ 1, no CPU throttling), and+ holds the PumpPortal feed open across requests.+- In `simulate`, logs show real new-mint scoring + simulated buys against the live+ feed, with zero real spend (evidence captured).+- `loadConfig()` fails closed on missing env (verified). Live mode is gated and+ documented; guardrails confirmed active in-env.+- Feed drop → auto-reconnect with backoff; disconnect/error → ops alert fires;+ a heartbeat is visible to `/status` / uptime cron.+- Deploy is a documented, re-runnable script under `scripts/` (no root clutter, no+ committed secrets).+- Changelog entry (tag: infra). 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/05-deploy-sniper-worker.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/ibm-x402-demo/00-PLAN.md b/tasks/ibm-x402-demo/00-PLAN.mdnew file mode 100644index 000000000..5fae42a33--- /dev/null+++ b/tasks/ibm-x402-demo/00-PLAN.md@@ -0,0 +1,115 @@+# IBM × three.ws — x402 Live Demo: Production-Readiness Plan++Goal: take the single-file x402 demo at [`pages/ibm/x402-demo.html`](../../pages/ibm/x402-demo.html)+from "built and data-layer-verified" to **100% production-ready, zero-error, best-in-class+UX** — hostable on `live.ibm.com` as the public face of the IBM × three.ws partnership.++This is the index. Each `NN-*.md` below is a self-contained brief an agent can execute from+a fresh session at repo root. CLAUDE.md auto-loads in every session, so each assumes those+rules (no mocks, real APIs, every state designed, push to both remotes).++## The deliverable++One self-contained HTML file (inline CSS + JS, no build step) that:++- loads the drop-in widget from `https://three.ws/x402.js`,+- shows the live `402` challenge for a real paid endpoint,+- lets a visitor pay **$0.001 USDC** from their own wallet (MetaMask → Base, Phantom →+ Solana) to call a real three.ws data API, and+- renders the result + on-chain receipt.++It will be copied onto `live.ibm.com`, and (task 09) also served at+`https://three.ws/pages/ibm/x402-demo.html` as a preview.++## Verified ground truth (2026-06-17 — do not re-derive)++- Widget `https://three.ws/x402.js` → **200**, served as an ES module. Public API:+ `window.X402.pay({ endpoint, method, body, merchant, action, caps }) → { ok, result, payment, response }`+ (the returned promise rejects with `err.code === 'cancelled'` when the user closes the+ modal). It also auto-binds any element carrying `data-x402-endpoint` and dispatches+ `x402:result` / `x402:error` CustomEvents. Source: [`public/x402.js`](../../public/x402.js).+- Endpoint `https://three.ws/api/x402/symbol-availability` → **HTTP 402** with+ `access-control-allow-origin: *` (verified from an `Origin: https://live.ibm.com` request)+ and `access-control-expose-headers` including `PAYMENT-REQUIRED` and `x-payment-response`.+ Price **1000 atomics = $0.001 USDC**. Accepts:+ - Base (`eip155:8453`) → payTo `0x4022de2d36c334e73c7a108805cea11c0564f402`,+ USDC `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` (plus a Permit2 sibling the modal ignores).+ - Solana (`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`) → payTo+ `wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV`,+ USDC `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`.+- The Solana helper `https://three.ws/api/x402-checkout` preflight (OPTIONS) → **204**, wildcard CORS.+- **The Base path is the most embed-robust:** EIP-3009 typed data is signed entirely+ client-side; the only external dependency is `x402.js` + one cross-origin fetch to the+ wildcard-CORS endpoint. **The Solana path additionally** dynamic-imports+ `@solana/web3.js` from `https://esm.sh` and POSTs to `/api/x402-checkout`. This distinction+ drives the CSP work in task 02.+- The page drives payment programmatically via `window.X402.pay()` (button `#payBtn`), shows+ a live 402 preview, and renders symbol-availability-shaped results (`recommendation`,+ `exact_matches[]`, `similar[]`) plus a receipt. **The price tag and 402 preview are+ endpoint-agnostic; the result-body renderer is symbol-availability-specific** (relevant to+ task 08 if the endpoint is swapped).++## Task list++| # | Task | Phase | Edits the HTML? |+|----|-------------------------------------------------------------|-------|-----------------|+| 01 | Real-wallet end-to-end verification (Base + Solana) | 1 | only to fix a found bug |+| 02 | CSP + cross-origin hardening for `live.ibm.com` | 1 | yes |+| 03 | Error states + resilience (every failure mode) | 2 | yes |+| 04 | UX polish + microinteractions + motion | 2 | yes |+| 05 | Responsive 320/768/1440 + mobile in-wallet browsers | 2 | yes |+| 06 | Accessibility pass (WCAG 2.1 AA) | 2 | yes |+| 07 | Cross-browser / device matrix | 3 | only to fix a found bug |+| 08 | Copy, brand & $THREE-compliance review | 3 | yes |+| 09 | Deploy: three.ws preview route + telemetry + IBM handoff | 4 | yes (+ build wiring) |+| 10 | Definition-of-done sweep (capstone sign-off) | 4 | no (verifies) |++## Running order — one file, so serialize edits++Unlike a multi-page sprint, **every editing task mutates the same file**+(`pages/ibm/x402-demo.html`). Do not run editing tasks concurrently — in this shared worktree+they will clobber one another.++- **Phase 1 (foundation):** 01 then 02. (01 is mostly read/verify; 02 makes the first+ structural edits — self-hosted fonts, CSP-safe loading.)+- **Phase 2 (polish, strictly in order):** 03 → 04 → 05 → 06. Each consumes the prior; 04 may+ introduce CSS tokens that 05/06 reuse.+- **Phase 3 (validate + content):** run 08 (edits copy/brand) then 07 (verifies across+ browsers; fixes only if it finds a defect).+- **Phase 4 (ship):** 09 then 10. 10 is the final gate.++Read/verify-only tasks (01, 07) may run against the current file anytime, but any fix they+produce must be serialized with the editing tasks.++## Definition of done (whole plan)++- A funded visitor can pay $0.001 and get real data on **both** Base (MetaMask) and Solana+ (Phantom), in a real browser, with the on-chain tx visible on Basescan/Solscan — proven by+ task 01's result file.+- Zero console errors/warnings in any supported browser, desktop or mobile.+- The page works served from a **foreign origin** (not three.ws) under a realistic IBM CSP —+ at minimum the Base path with no third-party CDN beyond `three.ws`.+- Every state (idle / preview / loading / success / each distinct error) is designed,+ on-brand, and actionable. WCAG 2.1 AA. Flawless at 320 / 768 / 1440.+- `$THREE` is the only coin referenced anywhere on the page. IBM brand usage is correct.+- The IBM handoff package exists: the file, a hosting README, and a recommended CSP header.+- `npm run build` clean; changelog entry added; completionist subagent run.++## Hard rules (inherited from CLAUDE.md)++- The only coin is `$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Never reference+ any other coin in code, copy, fixtures, or docs.+- No mocks, no fake data, no stubs, no fake-loading. Real endpoint, real wallet, real+ settlement. If you lack mainnet USDC for a verification step, **say so** — do not simulate+ the payment leg.+- Errors handled at boundaries; every error has a designed, actionable UI state.+- Stage explicit paths before committing (concurrent agents share this worktree). Never+ `git add -A` / `git add .`.+- `npx vercel build` clobbers `api/*.js` and `public/*` with esbuild bundles — never commit those.+- Push to BOTH remotes (`threeD`, `threews`) only when the user approves.++---++Each `NN-*.md` is a unit of work that **deletes itself on completion** (`git rm`, staged in+the same commit). A file that still exists is unfinished; a file that is gone has shipped.+This `00-PLAN.md` is the last to go — task 10 removes it as part of the final sign-off.diff --git a/tasks/ibm-x402-demo/01-e2e-wallet-verification.md b/tasks/ibm-x402-demo/01-e2e-wallet-verification.mdnew file mode 100644index 000000000..a41f96fea--- /dev/null+++ b/tasks/ibm-x402-demo/01-e2e-wallet-verification.md@@ -0,0 +1,93 @@+# Task 01 — Real-wallet end-to-end verification (Base + Solana)++## Context++three.ws workspace at `/workspaces/three.ws`. The deliverable and all verified facts are in+[00-PLAN.md](00-PLAN.md). The page under test is+[`pages/ibm/x402-demo.html`](../../pages/ibm/x402-demo.html); it drives the drop-in widget+[`public/x402.js`](../../public/x402.js) against the real $0.001 endpoint+`https://three.ws/api/x402/symbol-availability`.++This is the foundation task. CLAUDE.md's definition of done is "feature exercised in a real+browser, no console errors, network tab shows real API calls succeeding with real data." This+task is where that gets done — with **real wallets and real on-chain USDC settlement**.++## Rails (non-negotiable)++- No mocks, no fake wallets, no "simulated" payment leg. If the test wallet lacks mainnet+ USDC, **stop and report it** — do not fake success. (The endpoint advertises mainnet only;+ there is no testnet accept to fall back to. If mainnet USDC is unavailable, document the+ blocker in the result file and mark the leg `BLOCKED`, not `PASS`.)+- Exercise **both** ecosystems — Base via MetaMask and Solana via Phantom — because both are+ advertised in the 402 body and both code paths in the widget differ (Base signs EIP-3009+ client-side; Solana round-trips `/api/x402-checkout` + dynamic-imports `@solana/web3.js`).++## Method++1. Serve the file from a local origin (a fresh dev server, or `npx http-server pages/ibm -p 8088`).+ Because the page uses absolute `https://three.ws` URLs, it behaves identically whether served+ locally, from three.ws, or from `live.ibm.com`.+2. Open it in a real browser with MetaMask **and** Phantom installed and funded with a few+ cents of USDC (Base USDC on MetaMask; Solana USDC on Phantom).+3. Keep DevTools open (Console + Network) for the whole run.++## What to verify++### Scenario A — Base (MetaMask)+1. On load, the **402 preview** populates: `$0.001 USDC`, networks `Base, Solana`, the two+ payTo addresses from 00-PLAN. No console errors.+2. Type a ticker (default `GRANITE`), click **Pay $0.001 & run**. The widget modal opens; pick+ the Base / browser-wallet option.+3. MetaMask prompts an **EIP-3009 `TransferWithAuthorization`** typed-data signature (a+ signature, not a gas transaction). Approve.+4. Network tab: the endpoint is re-called with an `X-PAYMENT` header and returns **200** with+ the JSON body; an `x-payment-response` response header is present.+5. The page result panel switches to the success state: recommendation pill, any matches, and a+ receipt with network = Base, the payer (short), and a **Basescan** tx link that resolves to a+ real settled USDC transfer to `0x4022…f402`.+6. Click the Basescan link — confirm the on-chain transfer exists and the amount is 1000 units (0.001 USDC).++### Scenario B — Solana (Phantom)+Same flow with Phantom. Additionally confirm:+- The widget POSTs to `https://three.ws/api/x402-checkout?action=prepare` then `…=encode`+ (Network tab) and dynamic-imports from `esm.sh` succeed.+- Phantom prompts to sign a transaction; on approval the call returns 200.+- The receipt shows network = Solana and a **Solscan** tx link to a real USDC transfer to+ `wwwPqsM4N7T9J69tB82nLyzxqsH159j4orftLTQfUGV`.++### Scenario C — Cancellation & re-run+- Open the modal, close it (✕ / Escape). The page result must return cleanly to the **idle**+ state (not an error) — the promise rejects with `code === 'cancelled'` and the page handles it.+- Re-run and complete a payment afterward to prove the flow is re-entrant.++## Output (required)++Write a result file at `~/.claude/ibm-x402-verify/result.json` with, per scenario: timestamp,+network, payer address, tx hash, explorer URL, HTTP status, and `PASS` / `FAIL` / `BLOCKED`+with a one-line reason. Include the exact console output if anything logged.++## Definition of done++- Scenarios A and B are `PASS` with real explorer-verifiable transactions, or clearly+ `BLOCKED` with the funding/credential gap named (never faked).+- Scenario C `PASS` (cancel is clean, re-run works).+- Zero console errors/warnings across the run. Network tab shows real 402 → 200 with real data.+- Result file written. Report the table back to the user. Run the **completionist** subagent if+ you changed any code to fix a bug you found.++<!-- 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 **verified+and any found bug is fixed and committed** per the repo-root `CLAUDE.md` definition of done,+remove it in the same change:++```bash+git rm "tasks/ibm-x402-demo/01-e2e-wallet-verification.md"+```++Stage the deletion alongside your work and include it in the completion commit. A file that+still exists is unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/ibm-x402-demo/02-csp-and-cross-origin-hardening.md b/tasks/ibm-x402-demo/02-csp-and-cross-origin-hardening.mdnew file mode 100644index 000000000..04dd0fdad--- /dev/null+++ b/tasks/ibm-x402-demo/02-csp-and-cross-origin-hardening.md@@ -0,0 +1,83 @@+# Task 02 — CSP + cross-origin hardening for live.ibm.com++## Context++three.ws workspace at `/workspaces/three.ws`. Deliverable + verified facts:+[00-PLAN.md](00-PLAN.md). The page is [`pages/ibm/x402-demo.html`](../../pages/ibm/x402-demo.html).++The demo will be hosted on **`live.ibm.com`**, a foreign origin whose **own+Content-Security-Policy governs the page**. The cross-origin API calls already work+(three.ws sends `access-control-allow-origin: *` — verified). The risk is the *outbound*+resources the page loads being blocked by IBM's CSP, and the page being embedded in an iframe.+This task makes the page robust under a realistic enterprise CSP and produces the exact CSP+header IBM should set.++## What the page currently loads (audit and confirm)++| Resource | Origin | Needed for | CSP directive |+|----------|--------|-----------|---------------|+| `x402.js` | `https://three.ws` | everything | `script-src` |+| 402 + paid fetch | `https://three.ws` | the data call | `connect-src` |+| IBM Plex fonts (CSS + woff2) | `fonts.googleapis.com`, `fonts.gstatic.com` | typography | `style-src`, `font-src` |+| `@solana/web3.js` | `https://esm.sh` | **Solana path only** | `script-src` (dynamic import) |+| `/api/x402-checkout` POST | `https://three.ws` | **Solana path only** | `connect-src` |+| keccak (`@noble/hashes`) | `https://esm.sh` | **Solana SIWX only** | `script-src` |++## Do this++1. **Remove the Google Fonts dependency.** Self-host IBM Plex (it is open source — `@ibm/plex`)+ by inlining a minimal `@font-face` set served from the **same origin** as the page, or fall+ back cleanly to a system stack (`'IBM Plex Sans', system-ui, -apple-system, Segoe UI, Roboto,+ sans-serif`). The page must render correctly with **no** `fonts.googleapis.com` request, so a+ `style-src 'self'` CSP doesn't break it. If self-hosting the woff2, place the files under+ `pages/ibm/fonts/` and reference them relatively so they travel with the file to IBM's host.+2. **Make the Base path the zero-third-party default.** Confirm the full Base pay flow needs+ only `three.ws` (script + connect) — no `esm.sh`. The Solana path needs `esm.sh` + the+ checkout helper. Add a small, honest UI note (or graceful degradation) so that if `esm.sh` is+ blocked, the Solana button fails with a clear message and the Base button still works. Do not+ hide Solana — just ensure a strict-CSP host degrades to Base gracefully instead of throwing.+3. **Test as a top-level document on a foreign origin.** Serve `pages/ibm/x402-demo.html` from a+ port that is NOT three.ws (e.g. `npx http-server pages/ibm -p 8088`) and load+ `http://localhost:8088/x402-demo.html`. Then re-test with a locally-enforced CSP that mimics a+ strict IBM policy (use a `<meta http-equiv="Content-Security-Policy">` injected via a tiny+ proxy, or browser DevTools "Content-Security-Policy" override). Confirm: Base flow works under+ `script-src 'self' https://three.ws; connect-src https://three.ws; style-src 'self' 'unsafe-inline'; font-src 'self'`.+4. **Test embedded in an `<iframe>`** on a foreign origin (IBM may iframe this, as the existing+ IBM landing page iframes other tools). Confirm the wallet modal still opens and is usable+ inside the iframe, popups/wallet extensions aren't blocked, and there's no `X-Frame-Options`+ / `frame-ancestors` conflict. If wallet extensions can't inject into a cross-origin iframe in+ some browsers, document it and recommend top-level hosting in the handoff.+5. **No mixed content, no console CSP violations** in any configuration.++## Output (required)++Add a recommended CSP to the handoff (task 09 will package it). Two tiers:++- **Strict (Base-only):** `script-src 'self' https://three.ws; connect-src https://three.ws; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' data:;`+- **Full (Base + Solana):** add `https://esm.sh` to `script-src` and `https://three.ws` (already present) to `connect-src`.++Write these into a short note `pages/ibm/HOSTING.md` (task 09 will expand it).++## Definition of done++- The page renders and the **Base pay flow works with no resource outside `'self'` + `three.ws`** —+ verified under an enforced strict CSP, served from a non-three.ws origin.+- The Solana path works when `esm.sh` is allowed and degrades with a clear message when it isn't.+- Works both as a top-level page and inside a cross-origin iframe (or the iframe limitation is+ documented).+- Zero console errors / CSP violations in every configuration tested. Fonts load self-hosted (no+ Google Fonts request).+- `pages/ibm/HOSTING.md` contains the two CSP tiers. Run the **completionist** subagent.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++```bash+git rm "tasks/ibm-x402-demo/02-csp-and-cross-origin-hardening.md"+```++Stage the deletion in the same commit as the implementation. A file that still exists is+unfinished work; a file that is gone has shipped. Do not delete early.diff --git a/tasks/irl-floor-anchor/04-placement-ux-polish.md b/tasks/irl-floor-anchor/04-placement-ux-polish.mdnew file mode 100644index 000000000..7bbb7f8b7--- /dev/null+++ b/tasks/irl-floor-anchor/04-placement-ux-polish.md@@ -0,0 +1,85 @@+# 04 — Placement UX polish (reticle, shadow, confirm, haptics)++> Epic IRL/floor-anchor · Size **M** · Depends on 01/02; parallel with 03.+> Turns a functional placement into one people screenshot and share.++## Goal++Raise the moment-to-moment feel of placing an agent to the bar of the best mobile+AR apps: a reticle that reads as "searching" vs "locked," a grounded preview that+casts a contact shadow (so the agent sits *on* the floor, not floats), a crisp+confirm beat with haptics when the anchor takes, and copy/motion that respects+accessibility. Everything here is feel — but feel is the product.++## Why it matters++Right now placement is: a static purple ring appears, you tap, text changes. It+works, but nothing signals "found it," nothing grounds the avatar, and the commit+moment is silent. These micro-interactions are precisely what make AR feel solid+versus janky. This is the screenshot-and-share task.++## Current state (real lines)++- Reticle is a single static ring, visible/invisible only:+ [src/ar/webxr.js:225-236](../../src/ar/webxr.js#L225-L236) (`_buildReticle`,+ color `0x9b8cff`), toggled at [171-184](../../src/ar/webxr.js#L171-L184).+- Hit transitions already fire a host callback on change only:+ [src/ar/webxr.js:246-251](../../src/ar/webxr.js#L246-L251) `_setHit` → `onHit`.+- Host hint copy: [src/irl.js:1596-1603](../../src/irl.js#L1596-L1603) and the+ `setXrHint` states through [src/irl.js:1668-1684](../../src/irl.js#L1668-L1684).+- The previewed avatar follows the reticle but has no shadow:+ [src/ar/webxr.js:176-178](../../src/ar/webxr.js#L176-L178).+- Overlay + hint styles: [pages/irl.html:448-511](../../pages/irl.html#L448-L511).++## What to build++1. **Reticle states.**+ - *Searching* (no hit): dimmer, slow breathing scale/opacity pulse.+ - *Locked* (hit found): brighter, snaps to full size with a quick scale-in,+ subtle continuous rotation or inner-dot fill so "ready to place" is obvious.+ Drive purely off the existing `_setHit` transition — no new per-frame branching+ beyond a lerp. Respect `prefers-reduced-motion`: no pulse/spin, just a static+ color/opacity swap.++2. **Contact shadow.** Add a soft radial shadow quad (or `ShadowMaterial` plane)+ under the previewed avatar and the placed agent so it reads as grounded. Lives+ in the XR scene, follows the reticle pre-tap and the anchor post-tap; disposed in+ `_handleEnd`. Keep it cheap (single transparent plane, no real shadow map).++3. **Confirm beat.** On successful `_handleSelect` anchor:+ - a one-shot reticle "pulse-out" ring animation,+ - `navigator.vibrate?.(15)` (guarded; iOS ignores it harmlessly),+ - the hint transitions to the existing "Anchored…" copy with a brief check/✓+ affordance in `.irl-xr-hint`.++4. **Copy pass.** Tighten the four hint states for clarity and warmth without+ jargon (searching → aiming → placed → saved). Keep `aria-live="polite"` on+ `#irl-xr-hint` ([pages/irl.html:1660](../../pages/irl.html#L1660)) so each state+ is announced. Ensure the exit affordance keeps its focus ring+ ([pages/irl.html:500](../../pages/irl.html#L500)).++5. **Reduced-motion + contrast.** Gate every animation behind+ `prefers-reduced-motion: reduce`. Verify reticle/hint contrast against bright and+ dark real-world backgrounds (the overlay sits over live camera) — add a subtle+ scrim behind the hint text if it fails on a white floor.++## Acceptance checklist++- [ ] Reticle visibly distinguishes searching vs locked; reduced-motion path is+ static and calm.+- [ ] Avatar shows a contact shadow both as preview and once anchored; no float.+- [ ] Anchor commit gives a visual pulse + haptic (where supported) + ✓ copy.+- [ ] All four hint states are clear, announced via `aria-live`, readable over both+ light and dark camera backgrounds.+- [ ] No per-frame allocations added; disposed cleanly on exit; no console noise.++## Out of scope++Occlusion (03), iOS parity (06). Don't change the anchoring math or persistence.++## Verify++WebXR device: sweep the phone across floor and away — watch searching↔locked;+confirm the shadow grounds the avatar; tap and feel the haptic + see the pulse ++✓. Re-run with reduced-motion enabled in OS settings and confirm calm static+states. Check the hint over a white floor and a dark rug.diff --git a/tasks/irl-hardening/H4-placement-consent-approximate.md b/tasks/irl-hardening/H4-placement-consent-approximate.mdnew file mode 100644index 000000000..c0884e1b7--- /dev/null+++ b/tasks/irl-hardening/H4-placement-consent-approximate.md@@ -0,0 +1,105 @@+# H4 — Placement consent + approximate-placement control++> Epic IRL-Hardening · Size **M** · Touches `src/irl.js` (placement flow),+> `pages/irl.html`, `api/irl/pins.js` (POST), and `data/changelog.json`.++## Goal++Make the privacy consequence of placing an agent **legible and controllable at+the moment of placement.** Today a tap-to-place drops the agent at the user's+exact spot with no disclosure and no option to fuzz it. Add: (1) a clear,+friendly disclosure of what placing means, (2) an **"approximate placement"**+option that stores a deliberately fuzzed coordinate for users who want plausible+deniability, and (3) a visible indicator of whether a pin is precise or+approximate. Privacy becomes a designed, first-class part of the UX — not a thing+the user has to infer.++## Why it matters++The single most dangerous moment in `/irl` is placement: that coordinate *is* the+user's real location, and it persists (7 days anon, forever signed-in) for anyone+nearby to read. A great product tells the user exactly what's about to happen and+gives them a safer default if they want it. "Approximate placement" lets someone+drop an agent "around here" — on a block, in a park — without publishing their+doorstep. This is the difference between a tool people trust and one they don't.++## Current state (verified)++- `src/irl.js` captures the fix (`gpsState.lat/lng/accuracy`) and `savePin()`+ POSTs `{ lat, lng, heading, … }` to `api/irl/pins.js`.+- `api/irl/pins.js` POST validates coords, runs content/coin/URL gates, density ++ per-owner caps, then inserts. It already stores `gps_accuracy_m`. The public+ read now coarsens output to ~1.1 m (`roundCoord`, shipped) — but the **stored**+ coordinate is still the precise fix.+- No disclosure UI, no approximate option, no precise/approximate flag exists.++## What to build++### 1. Placement consent sheet (designed, one-time + re-openable)++Before the first placement (and available behind an "i" affordance after), show a+short sheet via the existing sheet/state-kit components:++> **Heads up — this is a real-world spot.** Your agent will be visible to anyone+> who physically walks within ~40 m of here. We never show a list or map of+> locations, and we never reveal who placed it — but the spot itself is public.+> Want to place it exactly here, or approximately?+> `[ Place exactly here ] [ Place approximately ▾ ]`++Persist "don't show every time" but keep the choice (exact vs approximate)+explicit per placement. No dark patterns — both options are equally prominent.++### 2. Approximate placement (client + server)++When the user picks approximate, offer a small radius choice (e.g. ~30 m / ~100 m /+~250 m). The client fuzzes the coordinate by a uniform random offset within the+chosen radius **before** POSTing, and sends `placement: 'approximate'` ++`fuzz_radius_m`. The server (`api/irl/pins.js` POST) validates `fuzz_radius_m`+against an allow-list, stores a new `placement_kind` column (`'precise'` |+`'approximate'`) and `fuzz_radius_m`, and — importantly — **never stores the+original precise fix** for an approximate placement. The agent renders at the+fuzzed spot for everyone, including the owner, so the true location is never+persisted at all.++### 3. Visible indicator++On the owner's pin cards (`irl-placements.js`) and in the pin inspect sheet, show a+small badge: `📍 Exact` / `≈ Approximate (~100 m)`. The owner always knows how+exposed each pin is. Re-placing/relocating (C5) preserves the chosen kind.++### 4. Copy + changelog++Plain, calm, non-alarmist language (see `public-copy-tone` memory: literal, no+sci-fi). Add a `data/changelog.json` entry (tag `security`, `improvement`).++## Data / API changes++- `irl_pins`: `ALTER TABLE ADD COLUMN IF NOT EXISTS placement_kind TEXT DEFAULT 'precise'`+ and `fuzz_radius_m DOUBLE PRECISION`. Lazy-migrate in `ensureTable()` (same+ pattern as the existing `ALTER … ADD COLUMN IF NOT EXISTS` block).+- POST accepts `placement` + `fuzz_radius_m` (validated against an allow-list).+- Nearby projection surfaces `placement_kind` so viewers/owners can show the badge.++## Acceptance checklist++- [ ] Consent sheet appears before first placement, re-openable via an "i" control,+ both options equally weighted, "don't show again" respected.+- [ ] Approximate placement fuzzes client-side; server stores only the fuzzed+ coordinate + `placement_kind='approximate'` + `fuzz_radius_m`; the precise+ fix is never persisted.+- [ ] Exact/Approximate badge shows on owner cards + inspect sheet.+- [ ] `placement_kind` migrates lazily; old pins read as `'precise'`; no 500.+- [ ] Designed states; 320/768/1440; keyboard + screen-reader labels; no console errors.+- [ ] Changelog entry added; `npm test` + `npm run typecheck` green.++## Out of scope++The privacy center (unpublish/delete/forget — **H5**) and proof-of-presence on the+read (**H3**). This task is the *placement-time* consent + fuzz only.++## Verify++`npm run dev` → `/irl`: first placement shows the consent sheet; choosing+approximate (~100 m) drops the agent visibly offset; the Network tab POST body+carries the fuzzed coord + `placement: 'approximate'`; the owner card shows the+`≈ Approximate` badge.diff --git a/tasks/irl-location-control/L1-simulated-location-dev.md b/tasks/irl-location-control/L1-simulated-location-dev.mdnew file mode 100644index 000000000..16eeca46e--- /dev/null+++ b/tasks/irl-location-control/L1-simulated-location-dev.md@@ -0,0 +1,125 @@+# L1 — Simulated location for testing (DEV-only)++> Epic · Size **S** · Touches `src/irl.js` only. DEV-gated, tree-shaken — never ships.+> The direct fix for "I want to test `/irl` on my iPhone without leaking my real spot."++## Goal++Let a developer or QA run the **entire** real `/irl` flow — place a pin, see the+nearby read, lock/anchor — at **any chosen coordinate**, with zero dependency on+the device's real GPS. Enabled two ways, both gated behind `import.meta.env.DEV`+so they are stripped from production bundles exactly like the existing+`__irlSeed*` harness (`src/irl.js:4405`):++- **URL param:** `…/irl?mockLoc=37.7749,-122.4194` (optionally `&mockAcc=8`).+- **Console:** `__irlMockLocation(37.7749, -122.4194)` to set, `__irlMockLocation(null)` to clear.++While active, a persistent on-screen **"SIMULATED LOCATION"** badge is shown so a+fake fix can never be mistaken for a real one, and the real `watchPosition` is+suppressed so no real coordinate is ever read or transmitted.++## Why it matters++Two hard blocks make on-device testing leak the tester's real location today:++1. **iOS Safari cannot spoof location** — no DevTools Sensors panel, and Web+ Inspector has no geolocation override. The only system-wide spoof is a paid+ third-party tool. So a real-device test writes the tester's true coordinates+ into the public `irl_pins` feed.+2. **A LAN dev build can't read GPS at all.** `navigator.geolocation` requires a+ secure context; over `http://<lan-ip>:3000` it's blocked, so `onGPSPosition`+ (`src/irl.js:1227`) never fires and the place flow is untestable.++Seeding `gpsState` directly sidesteps both: the flow runs on the fake fix, real+GPS is never touched, and it works over plain-http LAN. This is the foundation+that lets L2–L5 be exercised on a real phone safely.++## Current state (real lines)++- `src/irl.js:1123` `const gpsState = { lat: null, lng: null, ready: false, watchId: null, accuracy: null, altitude: null }`.+- `src/irl.js:1336` `initGPS()` starts the single `watchPosition` (idempotent on `gpsState.watchId`).+- `src/irl.js:1227` `onGPSPosition(pos)` is the only writer of `gpsState.lat/lng/ready`; on the **first** fix it calls `revealMyPinsBtn()` and `startPinSync()`, and resolves a `_pendingGpsLock`.+- `src/irl.js:4405` `if (import.meta.env.DEV) { window.__irlSeedPins = …; window.__irlPerf = …; window.__irlSeedRoom = …; }` — the established DEV-only window-API pattern to mirror.++## What to build++### 1. A single `applyMockFix(lat, lng, accuracy)` path++Reuse the real first-fix sequence rather than duplicating it. Factor the body of+`onGPSPosition`'s first-fix branch (seed `gpsState.lat/lng`, `ready = true`, then+`revealMyPinsBtn()` + `startPinSync()` + resolve `_pendingGpsLock`) into a small+helper, and have both `onGPSPosition` and `applyMockFix` call it, so a simulated+fix exercises the identical downstream code as a real one.++```js+// DEV-only. Seeds a synthetic fix and stops the real watch so no real coord is read.+function applyMockFix(lat, lng, accuracy = 10) {+ if (gpsState.watchId != null) { navigator.geolocation.clearWatch(gpsState.watchId); gpsState.watchId = null; }+ _mockLocation = true;+ gpsState.accuracy = accuracy;+ gpsState.altitude = null;+ onFirstOrBlendedFix(lat, lng); // the extracted shared helper+ showMockBadge(lat, lng);+}+```++`initGPS()` must early-return when `_mockLocation` is set so a later call can't+re-attach the real watch and overwrite the fake fix.++### 2. URL-param entry (parse once at boot, DEV-only)++Inside the existing `if (import.meta.env.DEV) { … }` block, parse `mockLoc`+(`"lat,lng"`, both finite, lat ∈ [-90,90], lng ∈ [-180,180]) and optional+`mockAcc`. On a valid value call `applyMockFix(...)` and skip `initGPS()`. On a+malformed value, `log.warn` and fall through to real GPS — never throw.++### 3. Console entry + badge++```js+window.__irlMockLocation = (lat, lng, acc = 10) => {+ if (lat == null) { /* clear: hide badge, _mockLocation=false, initGPS() to resume real */ return 'cleared'; }+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return 'usage: __irlMockLocation(lat, lng[, accuracyM])';+ applyMockFix(lat, lng, acc);+ return { mocked: { lat, lng, acc } };+};+```++The **badge** is a fixed-position pill (top-center, high z-index, `pointer-events:none`)+reading `📍 SIMULATED LOCATION · 37.7749, -122.4194`. Style it unmistakably (amber+border, mono coords) — its entire job is to prevent confusing a fake fix for real.+Tapping it does nothing; clearing the mock removes it.++### 4. Persist nothing, ship nothing++`_mockLocation` lives in module scope only (no localStorage — a refresh without the+param returns to real GPS). The whole feature sits inside `import.meta.env.DEV`+guards so Vite tree-shakes it out of the production build. **Verify the prod bundle+contains neither `__irlMockLocation` nor `SIMULATED LOCATION`.**++## Data / API changes++None. Client-only. No new endpoint, no schema change. The real `POST /api/irl/pins`+runs unchanged — it simply receives the simulated coordinate.++## Acceptance checklist++- [ ] `?mockLoc=37.7749,-122.4194` makes `gpsState.ready` true at that point with **no** real GPS prompt; My-pins reveals; nearby read fires for the fake spot.+- [ ] `__irlMockLocation(lat,lng)` sets, `__irlMockLocation(null)` clears and resumes real GPS.+- [ ] The real `watchPosition` is cleared/never started while mock is active; `initGPS()` is a no-op under mock.+- [ ] Placing a pin while mocked writes the **simulated** coordinate (confirm the POST body in the Network tab).+- [ ] The "SIMULATED LOCATION" badge shows the active coords and disappears on clear.+- [ ] Malformed `mockLoc` logs a warning and falls back to real GPS — no throw, no console error.+- [ ] **Production bundle (`npm run build`) contains no `__irlMockLocation` / `SIMULATED LOCATION` / `mockLoc` strings.**++## Out of scope++A user-facing "set my location" UI (that's L2's map picker). Persisting the mock+across reloads. Faking compass/heading (the magnetometer is untouched — heading+still reflects the real device, which is fine for placement testing).++## Verify++`npm run dev`, then:+1. Desktop: open `/irl?mockLoc=37.7749,-122.4194` → badge shows, no location prompt, place a pin → POST body carries `37.7749/-122.4194`.+2. Real iPhone over LAN: connect the phone to the same network, open `http://<your-lan-ip>:3000/irl?mockLoc=…` → the flow runs even though plain-http GPS is blocked; the pin lands at the fake spot, not your home.+3. `npm run build` → `grep -r "__irlMockLocation\|SIMULATED LOCATION" dist/` returns nothing.diff --git a/tasks/irl-location-control/README.md b/tasks/irl-location-control/README.mdnew file mode 100644index 000000000..e11f67e80--- /dev/null+++ b/tasks/irl-location-control/README.md@@ -0,0 +1,94 @@+# IRL — Location Control & Safe Testing++The program that makes **placing, testing, and living with a real-world location**+in `three.ws/irl` feel safe and intentional — for the developer testing on a+phone, and for the real user who does not want their home address written into a+public feed.++Today `/irl` reads your live GPS (`navigator.geolocation.watchPosition`) and, the+moment you lock/place an agent, writes your **exact standing coordinates** to the+public `irl_pins` table. That is correct for the AR product — but it leaves two+gaps this epic closes:++1. **No safe way to test.** On a real iPhone you cannot spoof Safari's location,+ and a dev build served over LAN can't even read GPS (geolocation is blocked on+ non-secure origins). So testing the place-a-pin flow means leaking your real spot.+2. **No user control over the placement leak.** A user can only pin where they+ physically stand, has no plain-language picture of what is shared or who can+ see it, and no fast way to purge what they dropped.++This epic delivers a **production-ready, fully-designed Location Control system**:+choose where you place (precise GPS *or* a point on a map), understand and control+what's shared, harden the proximity read so browsing doesn't broadcast your exact+position, manage/purge your pins, and a DEV-only simulated-location mode so QA can+exercise the whole flow on a real device without ever touching a real coordinate.++---++## What already exists (do NOT rebuild — extend)++Grounded in the current tree:++| Piece | Location | State |+|---|---|---|+| IRL AR client | `src/irl.js` | `gpsState` (`:1123`), `onGPSPosition` (`:1227`), `initGPS`/`watchPosition` (`:1336`), `savePin` POST (`:1351`/`:1370`), `anchorGpsPin` (`:1313`), caption-confirm save (`:1456`), `loadNearbyPins` w/ caller coords (`:2009`/`:2016`) |+| My-pins management | `src/irl.js` | `openMyPinsSheet` (`:2514`), `loadMyPins` (`:2476`), `renderMyPins` (`:2501`), `deleteMyPin` (`:2531`), `revealMyPinsBtn` (`:2555`), button (`:2561`) |+| Presence opt-in (ghost) | `src/irl.js` | `getShareGhost`/`setShareGhost` (`:1820`), toggle (`:2578`), `syncGhostToggle` (`:2568`) — default **off** |+| DEV perf harness | `src/irl.js:4405` | `import.meta.env.DEV`-gated `__irlSeedPins` / `__irlSeedRoom` / `__irlPerf` — the pattern every dev-only tool in this epic mirrors |+| Pins API + table | `api/irl/pins.js` | `irl_pins` schema + `ensureTable` (`:167`), GET nearby (`:467`, radius clamp `:473`, IP rate-limit `:415`, owner-id-stripped projection `:504`), POST (`:554`, anon 7-day expiry `:668`), PATCH/calibrate (`:756`), DELETE (`:847`) |+| Permission / first-run | `src/irl/onboarding.js` | Single source of truth — `PERMS.location` (`:22`), designed prompt/granted/denied/unsupported states, persisted outcomes, state-kit |+| Map + geocode (reuse) | `src/dashboard-next/pages/irl-placements.js` | Leaflet lazy-loaded from `https://esm.sh/[email protected]` (`:1083`), dark theme (`:339`), `reverseGeocode` via Nominatim (`:111`) — the canonical map approach to copy |+| Shared UI states | `src/shared/state-kit.js` | Skeleton / empty / error / retry shells — use everywhere |++---++## Task index++- **L1** `L1-simulated-location-dev.md` — DEV-gated simulated location (`?mockLoc=`+ + `__irlMockLocation()`) that bypasses geolocation and the insecure-context block.+ *The direct answer to "test on my iPhone without leaking my real location."* **S**+- **L2** `L2-map-placement-picker.md` — "Use my location" **or** "Pick a spot on a+ map" when placing. Leaflet picker + search. The real-user privacy + UX win. **M**+- **L3** `L3-location-privacy-center.md` — One designed in-app surface: what's+ stored, who sees it, precise/approximate discovery, presence opt-in, first-run+ disclosure. **M**+- **L4** `L4-proximity-read-hardening.md` — Coarsen the caller's coords on the+ nearby read (approximate discovery) + no exact-coordinate logging server-side.+ Closes the browsing-leak vector. **M**+- **L5** `L5-my-pins-management-upgrade.md` — Map overview of your pins, expiry+ countdown, and a guarded "Remove all from this device" purge. **S**++## Run order++```+L1 (independent — ship first; unblocks safe testing of everything below)+L3 (privacy control surface) ─> L4 (the approximate-discovery behavior it toggles)+L2 (placement picker — independent of L3/L4)+L5 (pin management — independent; nicer once L2 exists)+```++Suggested: **L1 → L2 → L3 → L4 → L5.** L1 first so every later task can be+exercised on a real device without leaking. L3 before L4 (L3 owns the toggle, L4+implements what it does).++---++## Ground rules for every task++- **$THREE is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`).+ None of these tasks touch tokens; keep it that way.+- **No mocks / fake data in production.** L1's simulated location is a **DEV-only,+ tree-shaken harness** (gated behind `import.meta.env.DEV`, exactly like the+ existing `__irlSeed*` tools) — it must never exist in a production bundle. Every+ other task uses real GPS, real DB, real Leaflet/Nominatim.+- **Every state designed** — loading / empty / error / permission-denied /+ unsupported via `src/shared/state-kit.js`. No blank screens, no silent failures.+- **Errors at boundaries** — every `fetch` / sensor / map-load call fails into a+ retryable, human state. Rule 9: never let an error stand without a fallback.+- **Mobile-first** — this is a phone product. Test at 320 / 768 / 1440px; mind iOS+ Safari quirks (motion gesture, no WebXR, geolocation needs HTTPS or localhost).+- **Changelog** — L2, L3, L5 are user-visible → add a `data/changelog.json` entry+ (`feature`/`improvement`) and run `npm run build:pages`. L1 and L4's server log+ change are internal → no entry.+- **Each task file is self-contained** — copy its prompt into a fresh agent and it+ executes without this README.diff --git a/tasks/irl-privacy/03-proximity-arrival-cue.md b/tasks/irl-privacy/03-proximity-arrival-cue.mdnew file mode 100644index 000000000..c5cb58694--- /dev/null+++ b/tasks/irl-privacy/03-proximity-arrival-cue.md@@ -0,0 +1,76 @@+# 03 — Proximity-arrival cue + non-map directional hint++> Size **M** · `src/irl.js` (`loadNearbyPins`/`refreshKnownPin`, spawn path,+> `onGPSPosition`, compass heading), a small pure module `src/irl/proximity-cue.js`,+> `src/irl.css`. The delight that makes serendipity actually work.++## Goal++Make the moment an agent enters your ~40 m bubble **felt**: a subtle haptic + soft+chime + a brief on-screen "an agent is near — look around," plus a gentle,+**non-map** directional nudge (an edge glow pointing toward the agent's bearing)+so the user knows which way to turn their camera. Discovery without a radar only+works if arrival is sensed.++## Why it matters++We removed the list and the radar on purpose. The cost: a user can be standing 15 m+from an agent, facing the wrong way, and never know. A single ambient "something is+here, turn around" cue — the way a notification buzz makes you look at your phone —+is what converts "empty screen" into "oh!". This is the difference between a privacy+feature that feels dead and one that feels magical. Crucially, the hint points a+*direction*, never reveals a list/coordinates — it's the in-world equivalent of+hearing a sound nearby.++## Current state (real lines)++- New pins enter via `loadNearbyPins()` → `spawnNearbyPin(entry)`. Known pins go+ through `refreshKnownPin`. There is **no** signal fired on first arrival today.+- The viewer's compass bearing is available (`currentHeadingDeg()`,+ `lastCompassHeading`); a pin's world position comes from `pinWorldPos(pin)` →+ `{x,y,z}` in metres relative to the viewer, so its **screen-relative bearing** is+ derivable (`atan2(x, -z)`) without exposing any coordinate.++## What to build++1. **`src/irl/proximity-cue.js`** — pure, unit-testable: given the set of currently+ in-range pin ids and the previously-seen set, return the newly-arrived ids+ (debounced so GPS-edge churn — see task 04 — doesn't double-fire). No DOM.+2. **Arrival cue** fired from `loadNearbyPins` when `proximity-cue` reports a new+ arrival:+ - `navigator.vibrate?.(...)` (guarded; many browsers/iOS ignore it — never assume).+ - A short, quiet chime via WebAudio (preloaded, user-gesture-unlocked on the+ same tap that started the camera). Respect a **mute toggle** (persist in+ `localStorage`) and the OS reduced-motion/`prefers-reduced-motion` for the visual.+ - A transient banner: *"An agent is near — look around."* aria-live polite.+3. **Directional nudge** — a soft glow/arrow at the screen edge toward the agent's+ current screen-relative bearing (recomputed as the user rotates, from compass ++ `pinWorldPos`). Fades once the agent is on-screen/in view frustum. **Never** a+ minimap, never a distance readout that could be triangulated — just "that way."+ When multiple agents are in range, nudge toward the nearest only.+4. Cap frequency: at most one chime/haptic per arrival, and a short global cooldown+ so a busy spot isn't a slot machine.++## Acceptance checklist++- [ ] `proximity-cue.js` is pure + unit-tested (new arrivals, debounce, no re-fire+ on a pin that merely refreshed).+- [ ] Arrival fires haptic (where supported) + optional chime + aria-live banner,+ exactly once per arrival, with a cooldown.+- [ ] Mute toggle persisted; `prefers-reduced-motion` disables the animated glow.+- [ ] Directional nudge points toward the nearest in-range agent and updates as the+ device rotates; disappears when the agent is in view. No map, no coordinates.+- [ ] WebAudio unlocked on the existing camera-start gesture; no autoplay warning.+- [ ] No console errors; clean at 320/768/1440; holder changelog entry + `build:pages`.++## Out of scope++Membership churn / hysteresis at the radius edge (task 04 — this task consumes its+debounced arrival signal). The empty-state explainer (task 02).++## Verify++`npm run dev` → /irl, seed a pin just inside range behind the camera+(`__irlSeedPins`): confirm the haptic/chime/banner fire once and the edge glow+points toward it; rotate to face it and confirm the glow fades. Toggle mute and+reduced-motion and re-confirm.diff --git a/tasks/irl-room-anchor/R2-room-alignment-and-calibrate.md b/tasks/irl-room-anchor/R2-room-alignment-and-calibrate.mdnew file mode 100644index 000000000..e5271d0e2--- /dev/null+++ b/tasks/irl-room-anchor/R2-room-alignment-and-calibrate.md@@ -0,0 +1,107 @@+# R2 — Cross-user room alignment + one-gesture room calibrate++> Epic R · Size **M** · Edits `src/irl.js`, `api/irl/pins.js`, `src/irl/room-anchor.js` (+ test).+> Depends on R1 (a room session exists). See `tasks/irl-room-anchor/README.md`.++## Goal++Make "shared at this location" **correct and honest** at room scale, and let an+owner **align an entire room with a single gesture** instead of nudging each+agent. When you arrive at a room someone placed, your phone aligns its local+frame to the room (compass north + your GPS offset from the origin) so the+cluster lands in front of you with its internal layout intact; if the whole+cluster is shifted a couple of metres from reality (GPS origin error), you grab+it and slide/rotate it onto its true spot **once**, moving every agent together.++## Why it matters++The room frame already guarantees exact *relative* geometry for everyone (R1 ++the engine). What's left is the *placement of the whole cluster in the viewer's+world* and the *cross-user agreement on north*. GPS gives the origin ±5–15 m and+compass gives north ±a few degrees, so without an alignment step the layout is+right but can sit a few metres off or rotated. Per-agent calibrate (already+shipped, A3) fixes one pin at a time — tedious and it can shear the layout.+Because every agent is rigidly tied to the origin, **calibrating the origin once+moves them all rigidly** — the correct, fast, layout-preserving tool.++## Current state (real symbols)++- **Render already aligns per-frame:** `pinWorldPos(pin)` →+ `roomOriginWorld(gpsState.lat, gpsState.lng, origin…)` + `agentWorldPosition`,+ recomputed in the `onGPSPosition` reprojection loop. So origin/viewer GPS and+ compass already drive the cluster; R2 adds the *correction* layer on top.+- **Per-pin calibrate (A3) shipped:** client gesture (long-press own agent →+ drag ±3 m / two-finger twist ±45° / height slider) → `PATCH /api/irl/pins`+ `{ id, deviceToken, calibrate:{ lat, lng, anchorYawDeg, anchorHeightM } }`,+ bounds-checked server-side (`handleCalibrate`, `CAL_MAX_MOVE_M=5`,+ `CAL_MAX_YAW_DEG=46`). Reuse this machinery, scoped to the origin.+- **Origin lives on every pin** (`origin_lat/lng`, `origin_yaw_deg`) — denormalized+ across the cluster, so a room calibrate is one `UPDATE … WHERE room_id = …`.++## What to build++### 1. Frame alignment on arrival (viewer side, `src/irl.js`)++- When the nearby read returns pins with a `room_id`, group them by room and+ treat each as a cluster sharing one origin. Rendering already uses the origin;+ ensure the **whole cluster is reprojected together** when the viewer's GPS+ origin blends (it is, via the loop — confirm room pins are included and not+ double-corrected during an active calibrate).+- **Compass-north alignment:** for a true-north room (`origin_yaw_deg === 0`),+ the viewer's live compass already aligns the frame — verify a room placed on+ one device renders on the correct bearings on another (two contexts / R5).+- **Relative-frame rooms** (`origin_yaw_deg !== 0`, placed without an absolute+ compass): the viewer cannot recover true north from GPS alone. Render using the+ stored `origin_yaw_deg` and **prompt a one-time "face the room's front and tap"+ alignment** so the viewer's frame is rotated to match. Down-weight/flag these+ (they're the `gyro-gps:rel` degradation path) and prefer absolute-compass rooms.++### 2. One-gesture room calibrate (the headline tool)++- **Enter room-calibrate** from the room badge/management sheet ("Align this+ room"). Show the whole cluster highlighted as one rig.+- **Drag** to translate the origin (N/E, bounded ±5 m to match server); **two-+ finger twist** to rotate the cluster about its origin (bounded ±45°); optional+ height. The whole cluster moves rigidly and live — reuse the A3 gesture math,+ applied to `roomOriginWorld` rather than a single pin.+- **Live readout** in honest units ("1.2 m N · 0.4 m E · 8°") and a confirm.++### 3. Server: room-scoped calibrate (`api/irl/pins.js`)++Add a PATCH branch, owner-gated and bounds-checked, that moves every pin in a+room the caller owns:++```jsonc+PATCH /api/irl/pins+{ "calibrateRoom": { "roomId": "living-room-7",+ "dEastM": 1.2, "dNorthM": -0.4, "dYawDeg": 8 } ,+ "deviceToken": "<uuid>" }+```++- Resolve the new origin via the same geodesy (`localToGeo` / `room-anchor.js`);+ rotating the cluster about its origin re-derives each pin's absolute `lat/lng`+ from its unchanged `rel_east_m/rel_north_m` (`agentWorldPosition` /+ `localToTrueNorth` semantics) so the index stays consistent.+- **Bounds:** reuse `CAL_MAX_MOVE_M` / `CAL_MAX_YAW_DEG`; reject larger with the+ existing designed 422 codes. **Ownership:** every pin in the room must belong to+ the caller (`user_id` or `device_token`); deny otherwise — never move a stranger's+ agent. One `UPDATE … WHERE room_id = … AND <owner>` sets `origin_lat/lng/yaw`+ for the cluster; recompute and persist each pin's `lat/lng` so nearby reads stay+ correct. Add a unit test for the cluster-rotation math in `room-anchor.js`.++### 4. Honest confidence UI++- Keep the existing per-pin confidence ring; add a **room-level confidence**+ affordance (origin GPS accuracy) so users understand "the room is anchored to+ about ±N m — align it if it's off." Amber when loose; never imply cm precision.++## Definition of done++- A second device renders a placed room on the correct bearings/positions; a+ rotated/relative-frame room prompts the one-tap alignment and then matches.+- An owner aligns a whole room in one gesture; every agent moves rigidly and+ persists; a non-owner cannot; bounds enforced client + server with the existing+ 422 codes. Cluster-rotation math unit-tested.+- No owner identifiers leak. `typecheck` clean, `npm test` green, `vite build`+ clean, no console noise. Changelog entry (tag `improvement`). On-device+ cross-user alignment handed to R5.