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
Extend IRL, wallet, and IBM x402 task/prompt backlogs
nirholasa233eac0e02b
diff --git a/prompts/avatar-animation-hardening/04-regression-corpus-and-runtime-guard.md b/prompts/avatar-animation-hardening/04-regression-corpus-and-runtime-guard.mdnew file mode 100644index 000000000..b5a0c0c19--- /dev/null+++ b/prompts/avatar-animation-hardening/04-regression-corpus-and-runtime-guard.md@@ -0,0 +1,68 @@+# Task 4 — Cross-rig regression corpus + runtime "fallen pose" guard++> Read [00-README.md](./00-README.md) first. **Depends on Task 1** (benefits from Task 2). Follow+> [CLAUDE.md](../../CLAUDE.md).++This is the "zero error, stays shipped" guarantee. The lying-down bug shipped because nothing+asserted that an animated avatar stays upright. This task locks that invariant in tests across a+corpus of rig conventions **and** adds a runtime guard that catches any future regression in+production and degrades gracefully instead of showing a body on its back.++## What to build++### 1. A deterministic cross-rig regression corpus+- New test suite (e.g. `tests/animation-upright-invariant.test.js`) that, for a corpus of rig+ conventions × the `FEATURED` clips ([src/animation-presets.js](../../src/animation-presets.js)),+ retargets and asserts the **upright invariant**: the Hips world up-axis stays within a small+ tolerance of vertical at **every keyframe** (not just frame 0). Use the world-matrix+ reconstruction technique from the diagnosis (raw GLB parse → Bone graph → compose) so it runs in+ Node with no browser.+- Corpus must include the two committed real GLBs — **cz.glb** (Avaturn, identity convention) and+ **michelle.glb** (Mixamo, `−90°X` Hips) — plus synthetic rigs covering: a non-`±90` armature+ rotation, `DEF-`/snake_case bone names, and a missing-bones rig (coverage below+ `MIN_COVERAGE`). The michelle + celebrate case is the **named regression lock** for this bug.+- Assert the no-regression invariant too: cz.glb retarget output is byte-for-byte equal to the+ verbatim path.++### 2. Runtime "fallen pose" guard+- In [src/animation-manager.js](../../src/animation-manager.js) (or the viewer), after a clip is+ bound/first played, sample the rig's root/Hips world up-axis. If it tilts beyond a threshold at+ rest (a sign the retarget produced a fallen pose), treat it as a failure: skip/disable that+ action and fall back to the authored bind pose (the viewer already prefers the authored pose+ over a broken retarget — reuse that path), and report once via the existing client-error channel+ (`/api/client-errors`, logged `[client-error]`) with enough context (avatar id/url, clip,+ measured tilt) to diagnose. **No console spam, no per-frame checks** — sample once per+ attach/clip, debounced.+- The guard must never fire for healthy rigs (cz, michelle-post-fix). Make the threshold generous+ (e.g. > 45°) so it only catches genuine catastrophes, and prove it stays silent on the corpus.++### 3. Make it a gate+- Ensure the new suite runs under `npm test` and therefore gates the Vercel build (the only+ automated gate per repo memory). Keep it fast (raw parse, no GLTFLoader).++## Definition of done+- Cross-rig upright-invariant suite covering ≥4 conventions × featured clips, with michelle ++ celebrate as an explicit named regression test; all green.+- cz.glb byte-for-byte no-regression assertion present and green.+- Runtime fallen-pose guard wired: detects, falls back to bind pose, reports once via+ `/api/client-errors`; proven silent on healthy rigs.+- `npm test` + `npm run typecheck` green; suite is part of the gate.+- Changelog entry if user-visible (reliability/self-healing). `completionist` run; findings fixed.+- Handoff note for Task 6 (which surfaces to spot-check live).++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/04-regression-corpus-and-runtime-guard.md"+```++Stage the deletion in the completion commit. A file that still exists is unfinished work.diff --git a/tasks/agent-wallet-trading/06-sniper-arming-ui.md b/tasks/agent-wallet-trading/06-sniper-arming-ui.mdnew file mode 100644index 000000000..28aff9154--- /dev/null+++ b/tasks/agent-wallet-trading/06-sniper-arming-ui.md@@ -0,0 +1,107 @@+# Task: Sniper arming UI + live positions / PnL dashboard++## Context++Every sniper API exists and reads real data, but there is no UI to arm a strategy+or watch it work:++- `POST /api/sniper/strategy` — arm/upsert a strategy (budget, filters, exits);+ `GET` lists strategies + live position summary (`api/sniper/strategy.js`).+- `GET /api/sniper/history` — closed trades with realized PnL (`history.js`).+- `GET /api/sniper/stream` — live SSE of buy/sell/position updates (`stream.js`).+- `GET /api/sniper/leaderboard` — realized-PnL ranking (`leaderboard.js`).+- `GET /api/sniper/trader` — agent's public trader profile/stats (`trader.js`).+- Schema: `api/_lib/migrations/20260615020000_agent_sniper.sql` (strategies ++ positions ledger with entry/exit PnL).+- The worker that consumes the armed strategy is deployed in task 05.++This task builds the **Snipe** tab of the wallet hub (shell from task 01): arm a+strategy on a funded agent wallet, then watch live positions and PnL — to the+`CLAUDE.md` UX bar.++## Goal++The owner can arm, edit, pause, and disarm a sniper strategy from the UI+(entry trigger, budget, per-trade size, filters, exit rules), then watch live+positions stream in with realized/unrealized PnL — backed entirely by the existing+APIs and the deployed worker.++## Files to Read First++- `api/sniper/strategy.js` — strategy GET/POST shape, validation, position summary+- `api/sniper/stream.js` — SSE event shape (buy/sell/update) for the live view+- `api/sniper/history.js`, `api/sniper/leaderboard.js`, `api/sniper/trader.js`+- `api/_lib/migrations/20260615020000_agent_sniper.sql` — strategy fields + exit+ knobs (stop-loss, trailing-stop, take-profit, timeout), entry triggers+ (`new_mint`, `first_claim`, `intel_confirmed`), `min_oracle_score`+- `workers/agent-sniper/scorer.js:21`, `claim-scorer.js`, `oracle-gate.js:33` — what+ each filter actually does, so the form labels/help match real behavior+- Task 01 hub shell (Snipe tab), task 02 deposit (link when budget > balance)+- `vercel.json` (~lines 1998-2027) — confirm the sniper routes are wired++## What to Build / Do++1. **Strategy arming form** in the hub Snipe tab:+ - Entry trigger selector (`new_mint` / `first_claim` / `intel_confirmed`) with+ plain-language help for each (drawn from the real scorer behavior).+ - Budget controls: total daily budget, per-trade size, max concurrent positions+ — shown against the agent's real wallet balance (warn / link to deposit if the+ budget exceeds funds).+ - Scoring filters that map to the real scorer knobs (market-cap bands, creator+ history, socials required, optional `min_oracle_score`).+ - Exit rules: stop-loss, trailing-stop, take-profit, timeout.+ - Simulate vs live toggle (honoring the worker's `SNIPER_MODE` gating from task+ 05); arm in paper mode first by default.+ - Arm / Pause / Disarm actions via `POST /api/sniper/strategy`.+2. **Live positions + PnL dashboard**: subscribe to `GET /api/sniper/stream` (SSE)+ for real-time buy/sell/position updates; show open positions (entry, current+ quote, unrealized PnL, exit reason when it fires) and closed trades from+ `history.js` with realized PnL. Aggregate stats (win rate, realized PnL, best/+ worst). Reconnect the SSE on drop.+3. **Trader profile + leaderboard surfacing**: render the agent's `trader.js`+ profile and a link into `leaderboard.js` so a sniping agent has a public,+ shareable track record (ties into reputation surfaces).+4. **States**: not-armed (clear CTA explaining what arming does + funding+ prerequisite), armed-but-no-fills-yet (waiting), active (live positions), paused,+ error (strategy validation errors from the API surfaced inline; SSE-disconnected+ banner with auto-retry). Underfunded → link to the deposit panel (task 02).++## Constraints++- Drive everything off the real APIs and the deployed worker — no fabricated+ positions, no fake PnL, no simulated stream. The SSE view reflects real worker+ events; before the worker is live in an env, the empty/waiting state is honest.+- Validation errors from `POST /api/sniper/strategy` surface inline and actionable;+ never a raw error or silent no-op. Don't let a user arm a live strategy with a+ budget exceeding the wallet balance without a clear warning.+- Owner-only writes; a visitor may view the public trader profile/leaderboard but+ not arming controls.+- Mobile-responsive (320/768/1440), keyboard-operable, ARIA, focus rings, designed+ empty/loading/error states. SSE handled with backoff + visible reconnect state.++## Success Criteria++- `npm run dev`: arm a strategy in simulate on a funded agent, see it persist via+ `GET /api/sniper/strategy`; with the worker running (task 05), watch real+ scored-launch activity stream into the positions view.+- Edit / pause / disarm all work and reflect immediately.+- Closed trades show realized PnL from `history.js`; aggregate stats compute from+ real data; the trader profile + leaderboard render.+- Every state (not-armed, waiting, active, paused, validation-error,+ SSE-disconnected, underfunded) renders and looks premium.+- 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/06-sniper-arming-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/ibm-x402-demo/03-error-states-and-resilience.md b/tasks/ibm-x402-demo/03-error-states-and-resilience.mdnew file mode 100644index 000000000..3007c33a8--- /dev/null+++ b/tasks/ibm-x402-demo/03-error-states-and-resilience.md@@ -0,0 +1,75 @@+# Task 03 — Error states + resilience (every failure mode designed)++## 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).++A demo on an IBM property must never show a broken or dead UI. The widget+([`public/x402.js`](../../public/x402.js)) handles in-modal wallet errors (reject, wrong chain,+verify/settle failure) with its own retry UI. This task hardens the **page-level** surface+around it so every failure resolves to a designed, actionable state — not a stuck spinner, a+silent no-op, or a raw exception.++## Enumerate and design every failure mode++Walk each, force it, and confirm the resulting state is clear and recoverable:++1. **402 preview fetch fails** (endpoint 5xx, DNS, offline) — the preview already shows an error+ label; confirm it's friendly, doesn't block the pay button, and auto-retries or offers retry.+2. **Widget script not yet loaded** when the button is clicked — currently guarded with a+ message; confirm it's graceful and that a late-loading `x402.js` recovers (retry succeeds).+3. **Empty / invalid ticker** — sanitizes to A–Z0–9; empty input shows an inline error, never+ fires a payment.+4. **User cancels in wallet** (`code === 'cancelled'`) — return to idle quietly, no error banner.+5. **Payment fails after signing** — facilitator verify/settle error, endpoint 5xx *after*+ payment, network drop mid-flight. Surface the widget's error message in the page's error+ state with a working **Try again**.+6. **Insufficient USDC balance** — confirm the message the visitor sees (from the wallet or+ facilitator) is comprehensible; if it's cryptic, add page-level guidance ("top up USDC on+ <network> and retry").+7. **Wrong network in wallet** — the widget asks to switch chains; confirm the page doesn't+ double-fire and the modal handles it.+8. **Double-click / rapid re-click** on the pay button — disable it (and show an in-flight+ state) while a `pay()` promise is pending; re-enable on resolve/reject.+9. **Offline** — detect `navigator.onLine === false` (and `offline`/`online` events); show a+ non-broken state and re-enable when back online.+10. **Malformed / partial result body** — the result renderer must be defensive: missing+ `recommendation`, empty `exact_matches`/`similar`, missing `payment.transaction` or+ `payment.network` must all render cleanly (no `undefined`, no thrown error).+11. **Clipboard unavailable** (the embed snippet copy) — already has a catch; confirm the+ fallback message shows.+12. **Global safety net** — add `window.addEventListener('error', …)` and+ `'unhandledrejection'` handlers so an unexpected throw shows a graceful inline notice and is+ (optionally, task 09) reported, rather than leaving a half-rendered panel.++## Method++- `npx http-server pages/ibm -p 8088` and force each case: block the endpoint in DevTools+ (request blocking / offline), point `ENDPOINT` at a 500/404 URL temporarily, throttle the+ network, decline in the wallet, etc. Revert any temporary `ENDPOINT` change before finishing.+- Every error state must: name what went wrong in plain language, offer the next action (retry /+ top up / reconnect), and keep the rest of the page usable.++## Definition of done++- Every failure mode above produces a **designed, on-brand, actionable** state — no stuck+ spinners, silent failures, raw stack traces, or `undefined` in the UI.+- Pay button is disabled while a payment is in flight; cancel returns to idle cleanly.+- Defensive result rendering proven against missing/partial fields.+- Global error/unhandledrejection net in place.+- Zero console errors in the happy path; forced errors log nothing alarming. Run the+ **completionist** subagent.++<!-- AUTO:self-delete-on-complete -->++---++## ✅ On completion — delete this file++```bash+git rm "tasks/ibm-x402-demo/03-error-states-and-resilience.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/05-session-lifecycle-hardening.md b/tasks/irl-floor-anchor/05-session-lifecycle-hardening.mdnew file mode 100644index 000000000..698af70c2--- /dev/null+++ b/tasks/irl-floor-anchor/05-session-lifecycle-hardening.md@@ -0,0 +1,102 @@+# 05 — Session lifecycle & error hardening (zero dead ends)++> Epic IRL/floor-anchor · Size **M** · Depends on 01. Run before 03/04.+> Where "zero error, production-ready" is actually earned.++## Goal++Make the AR session survive everything the real world throws at it —+backgrounding, an incoming call, tracking loss, camera contention, a rejected+anchor, a tap during GPS warm-up — with a designed, recoverable outcome every+time. No frozen overlays, no silent failures, no console noise, no state where the+user is stuck looking at a glued avatar with no way forward.++## Why it matters++The happy path already works. Production readiness is entirely about the unhappy+ones, and AR has many: phones lock, permissions get revoked mid-session, ARCore+loses tracking under low light, the OS reclaims the camera. Each must resolve to a+clear next action. This is the task that makes the difference between "demo" and+"shippable."++## Current state (real lines)++- Start path catches and shows a designed error with Retry / Use Pin:+ [src/irl.js:1564-1585](../../src/irl.js#L1564-L1585) (`showXrError`),+ [src/irl.js:1598-1626](../../src/irl.js#L1598-L1626) (`enterFloorAnchor` try/catch).+ Good baseline — extend it, don't rewrite.+- Camera contention with the getUserMedia passthrough is half-handled: `disableAR()`+ before entering ([src/irl.js:1591](../../src/irl.js#L1591)); exit restores clear+ color/background ([src/irl.js:1612-1614](../../src/irl.js#L1612-L1614)) but does+ **not** re-enable the passthrough the user had on.+- Anchor-creation rejection already falls back to frozen pose:+ [src/ar/webxr.js:213-219](../../src/ar/webxr.js#L213-L219) — but the user is never+ told the placement is degraded.+- Pre-GPS replay path exists but is untested:+ [src/irl.js:1640-1651](../../src/irl.js#L1640-L1651) (`onFloorAnchored` holds+ `_pendingXrAnchorPose`), dropped on exit ([src/irl.js:1607-1611](../../src/irl.js#L1607-L1611)).+ The actual replay on first fix lives in `onGPSPosition` — find and verify it.+- **No handling at all** for `XRSession.visibilitychange`, `inputsourceschange`,+ tracking loss (a frame with no viewer pose), or `session.end` originating from the+ OS rather than our exit button.++## What to build++1. **Visibility / interruption.** Listen for `session.addEventListener('visibilitychange', …)`+ in `WebXRSession`. On `hidden`/`blurred`, pause non-essential work and show a+ "Paused — bring the app forward" hint via the `onHit(false)`-style host callback;+ on `visible`, resume. Ensure an OS-initiated `end` runs the exact same+ `_handleEnd` restoration as our button (it already binds `end` →+ [src/ar/webxr.js:106](../../src/ar/webxr.js#L106) — verify the host `onEnd`+ cleanup at [src/irl.js:1605-1617](../../src/irl.js#L1605-L1617) is idempotent).++2. **Tracking loss.** In `_tick`, when `frame.getViewerPose(localSpace)` is null for+ N consecutive frames, surface a "Move to a brighter, more textured area" hint+ (new `onTracking(false)` callback) and hide the reticle; clear it when pose+ returns. Don't spam — transition-only, like `_setHit`.++3. **Degraded-anchor honesty.** When `createAnchor` returns/throws null+ ([src/ar/webxr.js:213-219](../../src/ar/webxr.js#L213-L219)), tell the host so the+ hint can say "Placed (this device can't lock it perfectly — it may drift)."+ Still persists the pin; just stops pretending it's rock-solid.++4. **Camera passthrough restore.** In the `onEnd` handler+ ([src/irl.js:1605-1617](../../src/irl.js#L1605-L1617)) re-enable the passthrough+ if `arActive` was on before entering (track the prior state in `enterFloorAnchor`).+ The user who was in camera-AR should return to camera-AR, not a black/gradient view.++5. **Pre-GPS replay correctness.** Confirm the `_pendingXrAnchorPose` set at+ [src/irl.js:1646](../../src/irl.js#L1646) is actually consumed by `onGPSPosition`+ on the first fix and routed through `persistFloorAnchor` (task 01's module). Add+ the missing wiring if it's not. Cover it in tests (07 harness / unit): tap →+ pose held → first fix → pin saved once, not zero or twice.++6. **Console hygiene.** Audit per the console-audit baseline: the only logging on+ failure should be the intentional `log.error('[irl] WebXR start failed', …)`+ ([src/irl.js:1622](../../src/irl.js#L1622)). No uncaught rejections, no warnings+ from feature probes ([src/ar/webxr.js:77-83](../../src/ar/webxr.js#L77-L83) already+ swallows correctly — match that everywhere).++## Acceptance checklist++- [ ] Backgrounding / locking the phone mid-session pauses cleanly and resumes (or+ exits) with full restoration — no frozen overlay.+- [ ] OS-initiated session end restores render loop, background, controls, and+ passthrough identically to the exit button (idempotent `_handleEnd`/`onEnd`).+- [ ] Tracking loss shows a recoverable hint and self-clears; never a dead reticle.+- [ ] Degraded anchor (no `XRAnchor`) is disclosed honestly and still saves a pin.+- [ ] Tap-during-GPS-warmup persists exactly once on the first fix (test-proven).+- [ ] Returning from AR restores prior camera passthrough state.+- [ ] Zero uncaught errors/warnings across the full lifecycle (console audit clean).++## Out of scope++Occlusion (03), cosmetic reticle states (04), iOS (06). This is correctness and+recovery only.++## Verify++WebXR device: enter AR, lock the phone, unlock → clean resume. Enter, get a call /+switch apps → clean exit + full restore. Cover a camera with your hand to force+tracking loss → recoverable hint. Tap immediately on entry before GPS locks, wait+for the fix → exactly one pin saved (check Network + `/api/irl/pins`).diff --git a/tasks/irl-hardening/H5-privacy-center-forget-me.md b/tasks/irl-hardening/H5-privacy-center-forget-me.mdnew file mode 100644index 000000000..b5721d5cb--- /dev/null+++ b/tasks/irl-hardening/H5-privacy-center-forget-me.md@@ -0,0 +1,105 @@+# H5 — Privacy center: visibility, export, delete / forget device++> Epic IRL-Hardening · Size **L** · New `api/irl/privacy.js`, a privacy panel in+> `src/dashboard-next/pages/irl-placements.js` (or a new `irl-privacy.js`), and an+> anonymous-device entry point on `/irl`.++## Goal++Give every user — signed-in **and** anonymous — full control and full visibility+over the location data `/irl` holds about them: see exactly what's stored,+temporarily **unpublish** a pin without deleting it, **delete** individual pins,+**remove everything**, and **"forget this device"** (purge all rows tied to the+anonymous device token). This is right-to-be-forgotten as a polished product+surface, not a support-ticket.++## Why it matters++Trust requires an exit. A location product that can collect but can't forget is a+liability. Anonymous testers (the common case early on) have no account to manage —+yet their device token ties together a history of real places they stood. They+must be able to wipe it themselves, instantly, with one tap. A great privacy+center is also a *feature*: it signals that the platform takes this seriously,+which is exactly the bar the founder set.++## Current state (verified)++- Pins carry `user_id` (signed) **or** `device_token` (anonymous). `hidden_at`+ already exists on `irl_pins` (moderation column) — reuse it for owner-initiated+ **unpublish** (a hidden pin is filtered out of every nearby/mine read already).+- `DELETE /api/irl/pins?id=` exists, owner/device-gated. There is no bulk delete,+ no "forget device," no data-summary read, and no unpublish/republish for owners.+- `irl_interactions` rows store `viewer_device` + the pin's `lat`/`lng`; deleting a+ pin today leaves its interactions behind (retention gap — see **H6**, which this+ task's deletes must also trigger).+- `src/dashboard-next/pages/irl-placements.js` lists owned pins with remove wired.++## What to build++### 1. `api/irl/privacy.js` — the control endpoint (auth OR device-token via H2 header)++- `GET /api/irl/privacy` → a plain-language **data summary**: pin count, oldest/+ newest placement, how many are precise vs approximate, interaction count,+ retention/expiry, and the literal list of what's stored ("approximate or exact+ coordinates you placed; an anonymous device id; messages visitors left"). No raw+ coordinates of other people; only the caller's own.+- `PATCH /api/irl/privacy { pinId, action: 'unpublish' | 'republish' }` → set/clear+ `hidden_at` on a pin the caller owns. Unpublished = invisible to everyone,+ recoverable by the owner.+- `DELETE /api/irl/privacy { scope: 'pin' | 'all' | 'device' }` →+ - `pin`: delete one owned pin (+ its interactions).+ - `all`: delete every pin owned by this user/device (+ their interactions).+ - `device`: `all` **plus** purge every `irl_interactions` row authored by this+ `viewer_device` (taps/messages this device left on *others'* pins), so the+ device id is fully forgotten. Owner-gated and null-guarded exactly like the+ existing DELETE (an empty token must match nothing).++Every delete path also removes dependent `irl_interactions` (the cascade H6+formalizes). Return counts so the UI can confirm ("Deleted 4 pins and 12+interactions").++### 2. Privacy panel UI++A clear panel (in the dashboard for signed-in users; reachable from `/irl` via a+"Privacy & my data" affordance for anonymous devices). Render the data summary,+a per-pin **Unpublish / Republish** toggle, **Delete pin**, and two destructive+actions behind a typed/explicit confirm: **Remove all my pins** and **Forget this+device**. Use the existing confirm/sheet components; destructive buttons styled as+destructive; success + error states designed.++### 3. Export++A "Download my data" action that streams the caller's own pins + interactions as+JSON (the same data the summary describes, in full). Honest and complete.++## Data / API changes++- New `api/irl/privacy.js` (GET/PATCH/DELETE). Register in `vercel.json`.+- No new columns (reuses `hidden_at`). Deletes cascade to `irl_interactions`.+- Uses the `x-irl-device` header from **H2** for anonymous auth.++## Acceptance checklist++- [ ] `GET /api/irl/privacy` returns an accurate, plain-language summary of only+ the caller's own data; never another user's coordinates.+- [ ] Unpublish hides a pin from all reads and is reversible; republish restores it.+- [ ] `scope: pin | all | device` delete works, owner/device null-guarded, cascades+ to `irl_interactions`, returns deleted counts.+- [ ] "Forget this device" leaves zero rows referencing that `device_token` or+ `viewer_device` — verify with a follow-up `GET` returning empty.+- [ ] Export downloads complete, correct JSON of the caller's own data.+- [ ] Destructive actions require explicit confirm; all states designed; a11y clean.+- [ ] H1 suite extended for the ownership/null-guard paths; changelog entry (`security`).+- [ ] `npm test` + `npm run typecheck` green; no console errors.++## Out of scope++Retention *automation* (the reaper changes live in **H6**; this task triggers+cascading deletes on demand). Placement-time consent + fuzz is **H4**.++## Verify++`npm run dev`: as an anonymous device place 2 pins + tap someone's pin, open+"Privacy & my data", confirm the summary matches, unpublish one (it vanishes from+nearby), then "Forget this device" and confirm a subsequent summary is empty and+the Network calls carry the `x-irl-device` header (no token in any URL).diff --git a/tasks/irl-location-control/L2-map-placement-picker.md b/tasks/irl-location-control/L2-map-placement-picker.mdnew file mode 100644index 000000000..8e8b84b21--- /dev/null+++ b/tasks/irl-location-control/L2-map-placement-picker.md@@ -0,0 +1,119 @@+# L2 — "Choose where to place" map picker++> Epic · Size **M** · Touches `src/irl.js` + `pages/irl.html` (UI) · reuses the+> Leaflet/Nominatim approach from `src/dashboard-next/pages/irl-placements.js`.++## Goal++When a user places an agent, give them a real choice instead of silently writing+their exact GPS:++- **Use my location (precise)** — the current behavior: anchor at the live fix.+- **Pick a spot on a map** — open a Leaflet picker (search + draggable marker),+ confirm a chosen point, and `savePin` uses *that* coordinate.++This is both the headline **privacy** win for real users (place your agent at a+chosen public spot — a café, a plaza, a venue — without your home coordinates ever+entering the feed) and a UX upgrade (place an agent somewhere you're planning to+be, or somewhere meaningful, not only where you're standing right now).++## Why it matters++The product premise is "agents anchored to real places," but forcing precise GPS+means the *only* place a user can pin is wherever they currently are — usually+home. That is a privacy non-starter for a public feed and it caps the product:+people want to place an agent at a landmark, an event, a storefront. A map picker+removes the leak and unlocks intentional placement. It mirrors how every mature+location product (Find My, Airbnb, Uber) lets you confirm/adjust a point rather+than trusting a raw fix.++## Current state (real lines)++- `src/irl.js:1313` `anchorGpsPin()` and `src/irl.js:1454` `openCaptionPanel()` both+ end at `savePin(lat, lng, heading, caption, anchor)` (`:1351`) which POSTs to+ `/api/irl/pins`. Placement coordinates today come straight from `gpsState`.+- `api/irl/pins.js:554` POST already validates and stores arbitrary `lat`/`lng`+ (range-checked `:566`), so **no server change is required** to accept a picked point.+- `src/dashboard-next/pages/irl-placements.js:1083` lazy-loads Leaflet from+ `https://esm.sh/[email protected]` + CSS from unpkg (`ensureLeafletCss`/`loadLeaflet`),+ dark-themed (`:339`); `reverseGeocode` (`:111`) hits Nominatim. **Copy this loader+ and theme verbatim** — do not introduce a second map stack.++## What to build++### 1. Placement-source chooser++Before the caption panel opens, present two clear choices (a small designed+sheet, not a browser confirm):++```+How should we place this agent?+ ◉ Use my location ~precise · within {accuracy}m+ ○ Pick a spot on a map choose any point+```++Default to "Use my location" when `gpsState.ready`; default to (and only offer)+the map when there's no fix. Selecting the map opens the picker; selecting precise+goes straight to the existing caption/anchor flow unchanged.++### 2. Leaflet picker sheet++A full-width bottom sheet (mobile-first) containing:++- A Leaflet map, dark theme, centered on `gpsState` if available else a sensible+ default, zoom ~16. Lazy-load via the dashboard's `loadLeaflet()`/`ensureLeafletCss()`+ pattern — **with a designed loading skeleton and a retry error state** if the CDN+ fails (Rule 9: never a blank map).+- A **draggable center marker** (or tap-to-move) — the agent drops where the marker+ sits. Show the live `lat, lng` + a debounced `reverseGeocode` label under the map.+- A **search box** (Nominatim `/search?q=`) so a user can type "Dolores Park, SF"+ and fly the map there. Debounce input; handle empty/no-results/error states.+- **Confirm** ("Place here") and **Cancel**. Confirm closes the picker and calls+ the normal caption flow with the chosen `{ lat, lng }`; heading falls back to the+ device compass or 0.++### 3. Wire chosen coordinate through `savePin`++Thread the picked point so `savePin` posts it instead of `gpsState`. A map-picked+pin is **not** GPS-anchored, so set the anchor pose `source` accordingly — pass+`source: 'map'` (the server already normalizes unknown sources; extend the+`anchor_source` allow-list note in `api/irl/pins.js:688` to record `'map'` so the+viewer/A3 knows this pin's bearing isn't compass-trustworthy). Caption/avatar/x402+flow is unchanged.++### 4. Designed states + a11y++Loading (map tiles), empty (search no-results), error (CDN/tiles/Nominatim+failure → retry), and a clear "you're placing remotely" hint. Keyboard: search+focusable, Confirm/Cancel reachable, `Esc` cancels. Marker has an ARIA label.+Respect 320 / 768 / 1440px.++## Data / API changes++- **No schema change.** POST already accepts arbitrary in-range `lat`/`lng`.+- Add `'map'` to the recognized `anchor_source` values (doc + the normalize line at+ `api/irl/pins.js:688`) so a map-placed pin is distinguishable from a `gyro-gps` one.+- New external calls: Nominatim `/search` (in addition to the existing `/reverse`).+ Reuse the dashboard's memoized client + a short timeout; never block placement on it.++## Acceptance checklist++- [ ] Placement offers "Use my location" vs "Pick a spot on a map"; precise path is byte-for-byte the current flow.+- [ ] Map picker lazy-loads Leaflet (dashboard pattern), dark theme, draggable marker, working search, live reverse-geocode label.+- [ ] Confirm places the agent at the **picked** coordinate (verify POST body); Cancel returns with nothing written.+- [ ] Map load failure / no GPS / no search results each render a designed, retryable state — never a blank map.+- [ ] `anchor_source` records `'map'` for map-placed pins.+- [ ] 320 / 768 / 1440px clean; keyboard + ARIA pass; no console errors/warnings.+- [ ] `data/changelog.json` entry added (`feature`); `npm run build:pages` passes.++## Out of scope++Moving/relocating an *existing* pin (that's the dashboard's remote-location+management + L5). Precise-vs-approximate *discovery* of nearby agents (L3/L4).+A custom tile server — OSM tiles via Leaflet default are fine.++## Verify++`npm run dev` → `/irl`: place via "Pick a spot on a map," search a landmark, drag+the marker, Place here → Network tab shows the POST with the picked coords and+`anchor_source:'map'`; the agent renders; your real GPS never entered the request.diff --git a/tasks/irl-privacy/04-gps-edge-hysteresis.md b/tasks/irl-privacy/04-gps-edge-hysteresis.mdnew file mode 100644index 000000000..e0927bc83--- /dev/null+++ b/tasks/irl-privacy/04-gps-edge-hysteresis.md@@ -0,0 +1,69 @@+# 04 — GPS-edge hysteresis / anti-flicker++> Size **S–M** · `src/irl.js` (`loadNearbyPins`, `refreshKnownPin`, despawn path,+> `NEARBY_RADIUS`), small pure helper. A real correctness + zero-jank bug, not polish.++## Goal++Stop agents near the radius boundary from popping in and out as consumer GPS+jitters, and stop avatars from "swimming" frame-to-frame. Discovery must be rock+steady: once an agent appears, it stays put until you genuinely walk away.++## Why it matters++Consumer GPS is ~5–30 m noisy; our discovery gate is 40 m. An agent sitting at+~38–42 m will cross the threshold on *every* fix, so the server returns it, then+drops it, then returns it — the avatar spawns, disposes its GPU resources, and+respawns repeatedly. That's visible flicker, wasted GLB loads, and a janky,+unprofessional feel — exactly what "best UX" rules out. The origin low-pass+(`blendOrigin`) smooths the *viewer* origin but does nothing for *set membership*+churn at the edge.++## Current state (real lines)++- `api/irl/pins.js` nearby GET hard-caps the requested radius:+ `Math.min(60, Math.max(10, parseFloat(req.query.radius ?? '40')))`. The client+ requests `NEARBY_RADIUS = 40`.+- `src/irl.js` `loadNearbyPins()` rebuilds the set every 10 s: pins absent from the+ response are removed via `disposePin(p)`; new ones are `spawnNearbyPin`-ed. There+ is **no hysteresis** — membership is whatever the last poll returned.+- `pinWorldPos` already resolves room-anchored clusters exactly; standalone pins+ use their own lat/lng, which is where edge jitter shows.++## What to build++1. **Asymmetric radius (hysteresis).** Discover at 40 m, but only *drop* a pin once+ it's clearly gone — e.g. request a slightly wider read radius (client asks for+ the cap, ~55–60 m) and apply the **enter** threshold (40 m) only to pins not+ already rendered, while keeping an already-rendered pin until it exceeds an+ **exit** threshold (e.g. 55 m). Compute distance client-side from `pinWorldPos`+ (already done each GPS fix) so the band is enforced locally regardless of the+ server's coarse set. Keep the server cap intact — never widen past 60 m.+2. **Despawn debounce.** A pin must be out-of-band for N consecutive polls (or T+ seconds) before `disposePin` — so a single bad fix never evicts a stable agent.+3. **Spawn/despawn transitions.** Fade/scale in on spawn, fade out on despawn+ (respect `prefers-reduced-motion`) so even a legitimate arrival/exit is smooth,+ not a pop.+4. Keep the per-fix reposition (`pinWorldPos`) — that's correct; this task governs+ *membership*, not position.++## Acceptance checklist++- [ ] A pin held at ~40 m with simulated ±10 m GPS noise stays rendered without a+ single dispose/respawn cycle (assert in a unit test on the pure band helper).+- [ ] Exit requires sustained out-of-band (debounced), not one poll.+- [ ] Spawn/despawn are animated; `prefers-reduced-motion` falls back to instant.+- [ ] Server radius cap unchanged (still `Math.min(60, …)`); no roster widening.+- [ ] No extra GLB refetches on a stable pin (watch the Network tab); no console noise.+- [ ] Unit test for the hysteresis band (enter/exit/debounce) added to the suite.++## Out of scope++The arrival cue (task 03) consumes the *stable* arrival signal this produces — keep+the "newly stable in-band" event clean so 03 doesn't double-fire. No server change.++## Verify++`npm run dev` → /irl with `__irlSeedPins` + a scripted GPS wobble around a pin at+the boundary (dev harness per [memory: irl-perf-e2]); confirm the avatar holds+steady and `__irlPerf()` shows no churn in load/evict counts.diff --git a/tasks/irl-room-anchor/R3-webxr-floor-refine.md b/tasks/irl-room-anchor/R3-webxr-floor-refine.mdnew file mode 100644index 000000000..520834e63--- /dev/null+++ b/tasks/irl-room-anchor/R3-webxr-floor-refine.md@@ -0,0 +1,80 @@+# R3 — WebXR floor-anchor precision refine (Android) + graceful iOS fallback++> Epic R · Size **M** · Edits `src/irl.js`, `src/ar/webxr.js`. Depends on R1.+> See `tasks/irl-room-anchor/README.md`. This is the precision layer — optional+> per device, never required.++## Goal++Where the device supports WebXR (Android Chrome), use **real AR plane detection**+to place and refine room agents on the actual floor with centimetre precision —+a hit-test reticle on the real ground, tap to drop — and bind that precision to+the room frame so it survives. On iOS Safari (no `immersive-ar`) and any+unsupported device, **fall back cleanly** to the R1 gyro+GPS aim flow with zero+console noise and no dead buttons.++## Why it matters++Gyro+GPS + the room frame already nails the *layout* and the turn-to-see feel.+WebXR adds what only on-device SLAM can: the agent's feet on the real floor at+the real spot, stable as you walk around it. Doing this as a *refinement layer*+(not a replacement) is what makes the system "every option, fused" — best+available precision per device, graceful everywhere else.++## Current state (real symbols)++- **WebXR session module exists:** `src/ar/webxr.js` (floor-anchor / hit-test+ session). `src/irl.js` has `detectFloorAnchorSupport()` (reveals the entry only+ when `immersive-ar` + hit-test are available — iOS never sees it) and a+ `persistFloorAnchor(pose)` path that converts an `XRAnchor` placement into a+ durable pin, including a `_pendingXrAnchorPose` deferral until the first GPS fix+ lands. Placement pose is tagged `anchor_source: 'webxr'` (A1).+- **Room engine** (R1): `placeAround`, `pinWorldPos`, room session `activeRoom`.+- **Reserved DB columns:** `anchor_quat` (JSONB `[x,y,z,w]`), `anchor_source`,+ `vps_provider`/`vps_id` (reserved) already exist on `irl_pins`.++## What to build++### 1. WebXR placement writes the room frame++- In room mode on a WebXR-capable device, the floor hit-test reticle replaces (or+ augments) the R1 distance slider: the reticle rides the detected floor; tap to+ drop the agent there.+- Convert the hit pose to a **room-relative offset**: take the XR-space position+ relative to the established room origin and express it as `relEast/relNorth`+ (+ `anchor_height_m` from the real floor height) so it persists in the room+ exactly like a gyro placement — same `room` block, `anchor_source: 'webxr'`,+ and store the orientation `quat`. The agent then renders for *all* viewers via+ the same `pinWorldPos` path; WebXR only improved *where* it was captured.+- If the room origin itself was established under WebXR, record the floor height /+ quat on the origin so R2's alignment starts from a better anchor.++### 2. Per-device refine++- On a WebXR device viewing an existing room, offer "refine on floor": re-run a+ hit-test for the agent the user is looking at and update its `rel_*`/height via+ the room-aware PATCH (reuse R2's calibrate path, bounds still enforced). This+ sharpens the local view without changing the shared origin unless the owner+ also calibrates the room (R2).++### 3. Graceful fallback (the non-negotiable half)++- iOS Safari / unsupported: `detectFloorAnchorSupport()` already hides the entry —+ confirm room mode silently uses the R1 gyro+GPS aim flow, **no WebXR button, no+ console errors, no "unsupported" toast**. The room a WebXR device created still+ renders perfectly on iOS via the room frame (that's the point of storing+ `rel_*`, not raw XR space).+- Session loss / hit-test unavailable mid-placement: drop back to the slider flow+ with a one-line, designed notice; never strand the user.++## Definition of done++- On Android Chrome, a user drops a room agent on the real floor via hit-test; it+ persists as a room pin (`anchor_source: 'webxr'`, height + quat stored) and+ renders for everyone via the shared frame.+- On iOS Safari, the same room renders correctly and placement uses the R1 flow+ with zero WebXR references and zero console noise.+- "Refine on floor" sharpens a single agent via the bounds-checked PATCH without+ corrupting the shared origin.+- `typecheck` clean, `npm test` green, `vite build` clean. Changelog entry (tag+ `feature`). On-device WebXR + iOS-fallback matrix handed to R5.