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
Remove completed task backlog files
nirholase34ee261031e
diff --git a/tasks/commit-push-pending-changes.md b/tasks/commit-push-pending-changes.mddeleted file mode 100644index a5215aeec..000000000--- a/tasks/commit-push-pending-changes.md+++ /dev/null@@ -1,89 +0,0 @@-# Task: Commit + Push All Pending Working-Tree Changes--## Context--The repo has uncommitted changes from one or more concurrent agents. These need to be staged,-committed, and pushed to BOTH remotes before Vercel can deploy them.--**Always push to both remotes per CLAUDE.md:**-- `threews` → `github.com/nirholas/three.ws` (canonical, Vercel deploys from here)-- `threeD` → `github.com/nirholas/3D-Agent` (push-only mirror)--Never pull from `threeD`. Never use `git add -A` or `git add .` (other agents may be-touching files concurrently). Stage only the files listed below.--## Current pending files--Run `git status --short` first to confirm these are still the modified/untracked files.-Then stage, commit, and push ONLY these:--```-M my-agents/index.html-M public/my-agents/index.html-M src/trades.js-```--If the status shows additional files from concurrent agents, check `git diff <file>` before-staging — don't commit another agent's in-progress work.--Untracked task files to also commit (these are safe to include):-```-?? tasks/rotate-replicate-token.md-?? tasks/x-post-mcp-text-to-3d.md-?? tasks/commit-push-pending-changes.md-?? tasks/verify-nvidia-trellis-artifact-fix.md-?? tasks/fix-forge-seed-circuit-breaker.md-?? tasks/fix-register-prep-rpc-chain.md-```--## Steps--```bash-# 1. Confirm state-git status --short--# 2. Read the diffs to write an accurate commit message-git diff my-agents/index.html public/my-agents/index.html src/trades.js--# 3. Stage explicit files only-git add my-agents/index.html public/my-agents/index.html src/trades.js-git add tasks/rotate-replicate-token.md tasks/x-post-mcp-text-to-3d.md \- tasks/commit-push-pending-changes.md tasks/verify-nvidia-trellis-artifact-fix.md \- tasks/fix-forge-seed-circuit-breaker.md tasks/fix-register-prep-rpc-chain.md--# 4. Verify staged diff before committing-git diff --staged --stat--# 5. Commit with a message that names what actually changed-git commit -m "$(cat <<'EOF'-<describe what my-agents + trades.js changes do>--Co-Authored-By: Claude Sonnet 4.6 <[email protected]>-EOF-)"--# 6. Push to BOTH remotes-git push threeD main-git push threews main-```--## Acceptance criteria--- `git status` is clean (no modified or untracked files from this list)-- `git log --oneline -1` shows the commit with a meaningful message-- Both pushes succeeded with no errors-- Vercel dashboard shows a new deployment triggered from the push--<!-- 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/commit-push-pending-changes.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/fix-forge-seed-circuit-breaker.md b/tasks/fix-forge-seed-circuit-breaker.mddeleted file mode 100644index 46ec53dac..000000000--- a/tasks/fix-forge-seed-circuit-breaker.md+++ /dev/null@@ -1,144 +0,0 @@-# Task: Forge Seed Cron — Circuit Breaker for Provider Outages--## Problem--`api/cron/forge-seed-cron.js` fires every 60 seconds and calls `/api/forge` to start a new-draft-tier 3D generation. When the free NVIDIA lane is broken (wrong artifact schema, network-blip, etc.) AND Replicate is rate-limited, every tick:--1. Creates a synthetic user in the `users` table-2. POSTs to `/api/forge` and gets a 429 back-3. Deletes the user (`delete from users where id = ${user.id}`)-4. Returns `{ ok: false, reason: "forge submit 429: ..." }`--This burns DB writes, usernames from the OG pool, and fills logs with failure noise every-minute for the entire duration of any provider outage — which can last hours (Replicate) or-days (NVIDIA API change).--## What needs to change--Add a lightweight consecutive-failure circuit breaker to `startNextJob()` in-`api/cron/forge-seed-cron.js`. When N consecutive ticks have returned `ok: false`, skip-submitting a new job for a cooldown window, then probe once before resuming.--### Implementation plan--**Option A — DB-side counter (preferred, survives lambda restarts)**--Add a `forge_seed_state` table (or use `app_config` / `kv_store` if one exists):--```sql-create table if not exists forge_seed_state (- key text primary key,- value jsonb not null,- updated_at timestamptz not null default now()-);-```--In `startNextJob()`, before creating the user:--```js-// Read current failure streak-const [state] = await sql`- select value from forge_seed_state where key = 'circuit'-`;-const circuit = state?.value ?? { consecutive_failures: 0, open_until: null };--if (circuit.open_until && new Date(circuit.open_until) > new Date()) {- return { skipped: true, reason: `circuit open until ${circuit.open_until}` };-}-```--After a failure (when `submit.status !== 200`):--```js-const failures = (circuit.consecutive_failures || 0) + 1;-const openUntil = failures >= 3- ? new Date(Date.now() + failures * 10 * 60_000).toISOString() // 30m, 40m, 50m …- : null;-await sql`- insert into forge_seed_state (key, value, updated_at)- values ('circuit', ${JSON.stringify({ consecutive_failures: failures, open_until: openUntil })}::jsonb, now())- on conflict (key) do update set value = excluded.value, updated_at = now()-`;-```--After a success (inside the `submit.body?.status === 'done'` branch and the `submit.body?.job_id`-branch), reset the counter:--```js-await sql`- insert into forge_seed_state (key, value, updated_at)- values ('circuit', '{"consecutive_failures":0,"open_until":null}'::jsonb, now())- on conflict (key) do update set value = excluded.value, updated_at = now()-`.catch(() => {}); // non-critical-```--**Option B — process-wide Map (simpler, lost on cold start)**--If you don't want a migration, a module-level `let _seedCircuit = { failures: 0, openUntil: 0 }`-works within a warm lambda but resets on every cold start. Acceptable for a background cron-since it self-heals on redeploy.--```js-// top of forge-seed-cron.js, outside the handler:-const _circuit = { failures: 0, openUntil: 0 };-```--In `startNextJob()` before creating the user:-```js-if (_circuit.openUntil > Date.now()) {- return { skipped: true, reason: `circuit open for ${Math.ceil((_circuit.openUntil - Date.now()) / 60_000)}m more` };-}-```--After failure:-```js-_circuit.failures++;-if (_circuit.failures >= 3) {- _circuit.openUntil = Date.now() + _circuit.failures * 10 * 60_000;-}-```--After success:-```js-_circuit.failures = 0;-_circuit.openUntil = 0;-```--## Relevant files--- `api/cron/forge-seed-cron.js` — the cron handler; `startNextJob()` is at line ~158-- `api/_lib/db.js` — `sql` tagged-template import for DB queries-- `api/forge.js` — the `/api/forge` endpoint the cron calls; `isUpstreamUnavailable()` at ~line 400 defines what counts as a provider failure--## Acceptance criteria--- When forge returns non-200 three times in a row, the circuit opens for ≥30 minutes-- During an open circuit, `startNextJob()` returns `{ skipped: true, reason: "circuit open …" }`-- No synthetic user is created or deleted during circuit-open ticks-- First successful generation resets the counter and closes the circuit immediately-- The `new_job` field in the cron response JSON shows the circuit state when open-- No new DB migrations needed if you take Option B (process-level Map)--## Notes--- If you take Option A, run the migration as a one-time SQL statement in the Vercel console- or via `psql $DATABASE_URL -c "..."` — no migration framework in this project.-- The threshold (3 failures → open) and window (10m × failures) are suggestions; tune to taste.-- Do NOT add a circuit breaker to `pollPending()` — polling already-submitted jobs is cheap- and should keep running even when new submissions are blocked.--<!-- 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/fix-forge-seed-circuit-breaker.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/fix-register-prep-rpc-chain.md b/tasks/fix-register-prep-rpc-chain.mddeleted file mode 100644index ea8bcc5ae..000000000--- a/tasks/fix-register-prep-rpc-chain.md+++ /dev/null@@ -1,134 +0,0 @@-# Task: Register-Prep — Use Full RPC Fallback Chain--## Problem--`api/agents/solana/_handlers.js` → `handleRegisterPrep` (around line 555) resolves the RPC-endpoint like this:--```js-const configuredRpc = network === 'devnet'- ? (process.env.SOLANA_RPC_URL_DEVNET || PUBLIC_RPC.devnet)- : (process.env.SOLANA_RPC_URL || PUBLIC_RPC.mainnet);-const publicRpc = PUBLIC_RPC[network] || PUBLIC_RPC.mainnet;-```--Then builds a UMI client from `configuredRpc` with:--```js-const buildTx = async (rpc) => {- const umi = createUmi(rpc).use(mplCore());- ...-};--let txBytes;-try {- txBytes = await buildTx(configuredRpc);-} catch (rpcErr) {- if (configuredRpc === publicRpc) {- // already on public, give up- return error(res, 503, ...);- }- // retry on public- try {- txBytes = await buildTx(publicRpc);- } catch (fallbackErr) {- return error(res, 503, ...);- }-}-```--### Why this is suboptimal--- `configuredRpc` resolves to `SOLANA_RPC_URL` (typically Helius or Alchemy). When Helius hits- its quota (6h cooldown in the process-wide `_endpointCooldown` map), `createUmi(configuredRpc)`- builds a bare `@solana/web3.js Connection` with NO rotating fetch — it sends every request- directly to Helius and gets 429s until the cooldown expires, causing user-facing 503s.--- The fallback to `publicRpc` (`api.mainnet-beta.solana.com`) goes to the most aggressively- rate-limited endpoint without trying Alchemy or Ankr first.--- The `catch` path generates two log lines per failure (`configured RPC failed, retrying with- public RPC` + `public RPC fallback also failed`) even when the issue is a known-cooling provider- that should have been skipped silently.--### What to use instead--`solanaConnection()` from `api/_lib/solana/connection.js` wraps a `Connection` with-`makeRotatingFetch` — it automatically rotates through the full Helius → Alchemy → Ankr →-public chain and skips cooling providers. UMI accepts any RPC URL string; passing the primary-endpoint and relying on the rotating fetch gives full failover transparently.--## Fix--In `handleRegisterPrep`, replace the manual two-RPC try/catch with a single-`solanaConnection()`-backed UMI call:--```js-import { solanaConnection } from '../../_lib/solana/connection.js';--// Inside handleRegisterPrep, replacing the configuredRpc / publicRpc block:-const rpcUrl = network === 'devnet'- ? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com')- : (process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');--// solanaConnection wraps the URL with makeRotatingFetch (Helius → Alchemy → Ankr → public)-// and disableRetryOnRateLimit:true — no manual fallback needed.-const conn = solanaConnection({ url: rpcUrl, network, commitment: 'confirmed' });--const buildTx = async () => {- const umi = createUmi(conn.rpcEndpoint).use(mplCore());- // ... rest of buildTx unchanged-};--let txBytes;-try {- txBytes = await buildTx();-} catch (rpcErr) {- console.error('[solana/register-prep] RPC error after all fallbacks:', rpcErr.message);- return error(res, 503, 'rpc_unavailable', 'Solana RPC temporarily unavailable — try again in a moment.');-}-```--**Note**: UMI takes an RPC URL string as the first argument to `createUmi()`, not a-`Connection` object. The rotating fetch is attached to the underlying `Connection` but UMI-doesn't see it directly. The correct pattern is to pass the primary URL string to `createUmi`-AND also pass the `Connection` as a custom endpoint if UMI's `@solana/web3.js` adapter accepts-it. Check `createUmi` signature — some versions accept a `Connection`, some accept a URL string.--If UMI doesn't support `Connection` objects, use the two-step approach:-1. Build a `solanaConnection()` and call `.getLatestBlockhash()` as an RPC probe BEFORE calling- `createUmi()` — this exercises the rotating fetch so a cooling endpoint gets skipped.-2. Read `conn.rpcEndpoint` (which will be the rotating fetch's currently-selected live endpoint)- and pass THAT URL string to `createUmi()`.--## Relevant files--- `api/agents/solana/_handlers.js` — `handleRegisterPrep` at line ~490; the RPC resolution- block at line ~555; the `buildTx` try/catch at line ~630-- `api/_lib/solana/connection.js` — `solanaConnection()`, `makeRotatingFetch()`, `solanaRpcEndpoints()`-- `api/_lib/solana/rpc-fallback.js` — `RpcFallback` / `rpcFallbackFromEnv()` (alternative if- UMI integration is simpler with a raw `Connection`)--## Acceptance criteria--- `handleRegisterPrep` has one RPC error path, not two nested try/catches-- When Helius is in the process-wide `_endpointCooldown` map, register-prep succeeds by- routing through Alchemy/Ankr without the user seeing a 503-- No `[solana/register-prep] configured RPC failed, retrying with public RPC` log lines- during Helius outages — failures are absorbed by the rotating fetch silently-- Existing register-prep tests (if any) still pass; manual test: register an agent on devnet- while `SOLANA_RPC_URL_DEVNET` points to a non-responsive URL--<!-- 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/fix-register-prep-rpc-chain.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/A1-webxr-world-anchor.md b/tasks/irl-live/A1-webxr-world-anchor.mddeleted file mode 100644index c599129cf..000000000--- a/tasks/irl-live/A1-webxr-world-anchor.md+++ /dev/null@@ -1,162 +0,0 @@-# IRL-Live A1 — WebXR world anchor (hit-test reticle + XRAnchor)--**Epic A · Effort: L · Depends on:** A2 (anchor pose schema)--## Goal--On WebXR-capable devices (primarily Android Chrome), let the user tap a real-floor point through a hit-test reticle to anchor the placed agent there. The-agent is bound to an `XRAnchor` so it stays glued to that world point as the-phone moves — no drift, no camera-relative slide. If WebXR is absent (iOS-Safari), defer cleanly to the gyro+GPS fallback in **A4**.--## Why it matters (user value)--Tap-to-place today (`spawnNearbyPin` / GPS-derived world position) jitters with-GPS noise and is camera-relative until locked. A real WebXR anchor makes the-agent sit on the actual floor where the user pointed — the difference between a-floating sticker and an agent that *belongs* in the room. This is the bar set by-Pokémon GO / Niantic Lightship; we should meet it where the hardware allows.--## Current state (real files + lines)--- `src/ar/webxr.js` — `WebXRSession` already runs `immersive-ar` with- `requiredFeatures: ['hit-test']`, follows a hit-test surface in `_tick()`- (lines 124–134), and anchors on first `select` by flipping `this._anchored`- (`_handleSelect`, line 140). It does **not** create a real `XRAnchor`, draw a- reticle, or report the anchored pose back for persistence.-- `src/irl.js` — IRL uses gyro+GPS only; it never calls `navigator.xr`.- `arActive` (line 185), `gpsToWorld()` (line 778), `setLocked()` (line 682).-- `src/shared/state-kit.js` — `errorStateEl`, `emptyStateEl` for designed- unsupported / permission states.--## What to build--### 1. Capability detect + entry button (`src/irl.js`)--Add a WebXR path alongside the existing camera button. Gate on real support, not-UA sniffing:--```js-import { WebXRSession } from './ar/webxr.js';-const xrSupported = await WebXRSession.isSupported(); // navigator.xr immersive-ar-if (xrSupported) {- anchorBtn.hidden = false; // "Place on floor" entry-} else {- // No WebXR → A4 gyro+GPS lock is the anchor path. Leave the Pin button as-is.-}-```--### 2. Reticle + real XRAnchor (`src/ar/webxr.js`)--Extend `WebXRSession` with a ring reticle that tracks the hit-test surface, and-on `select` create a persistent anchor instead of just setting a flag:--```js-// In start(): build a thin TorusGeometry ring, add to scene, hide until a hit.-async _handleSelect(/* event */) {- if (!this._latestHit) return;- // Real anchor — survives small tracking corrections the raw pose does not.- this._anchor = await this._latestHit.createAnchor?.(); // feature-detect- this._anchored = true;- this._reticle.visible = false;- this._onAnchored?.(this._readAnchorPose()); // hand pose to A2 persistence-}-```--In `_tick()`, when anchored, drive `viewer.content` from the live anchor pose-each frame so it stays glued as the camera moves:--```js-if (this._anchor && frame) {- const pose = frame.getPose(this._anchor.anchorSpace, this._localSpace);- if (pose) viewer.content.matrix- .fromArray(pose.transform.matrix), viewer.content.matrix.decompose(- viewer.content.position, viewer.content.quaternion, viewer.content.scale);-}-```--Request `anchors` in optional features so devices without it still run:-`optionalFeatures: ['anchors', 'dom-overlay']`. If `createAnchor` is missing,-fall back to the existing hit-pose-follow (already implemented at lines 124–134)-— degraded but never broken.--### 3. Convert anchor pose → GPS pin (bridge to A2)--The reticle hit gives a *local* XR pose (metres from session origin). Convert-the horizontal offset to a GPS pin using the same metre-per-degree math IRL-already uses in `setLocked()` (lines 714–717), and capture the extra pose-fields A2 adds:--```js-const { position, quaternion } = anchorPose; // local-space, metres-const mLat = 110540, mLng = 111320 * Math.cos(gpsState.lat * Math.PI/180);-const pinLat = gpsState.lat + (-position.z / mLat);-const pinLng = gpsState.lng + ( position.x / mLng);-savePin(pinLat, pinLng, headingFromQuat(quaternion), caption, {- anchorHeightM: position.y, // floor height vs eye origin- anchorYawDeg: yawFromQuat(quaternion),- gpsAccuracyM: gpsState.accuracy, // from watchPosition coords.accuracy- altitudeM: gpsState.altitude ?? null,-}); // extra-pose object consumed by A2's savePin signature-```--### 4. Designed states--- **Unsupported** (no WebXR): show nothing broken — the existing Pin button +- A4 still work. Optionally a one-line chip "Floor anchoring unavailable on this- browser — using compass lock."-- **Permission denied / session failed**: `errorStateEl({ title: 'Camera AR- couldn't start', body, actions:[{label:'Retry'}] })`; never a blank canvas.-- **Searching for surface**: reticle hidden + status "Point at the floor and- move your phone slowly." (real hit-test state, no fake spinner).--## Data / API changes--No new endpoint. `savePin()` (A2) gains an optional 5th arg carrying anchor pose-fields; POST body in `api/irl/pins.js` (A2) accepts them. Reads back via the-existing nearby-pins GET.--## Acceptance criteria--- [ ] `WebXRSession.isSupported()` gates the floor-anchor entry; iOS Safari- never sees it and silently uses A4.-- [ ] A ring reticle tracks the real floor and hides once anchored.-- [ ] First tap creates a real `XRAnchor` (feature-detected); agent stays glued- to that world point as the phone moves/walks.-- [ ] Devices without `createAnchor` fall back to hit-pose-follow — no error.-- [ ] Anchor pose is converted to a GPS pin and persisted via A2 (height, yaw,- gps accuracy captured).-- [ ] Unsupported / permission-denied / searching states all designed via- `state-kit.js`; no blank or frozen screen.-- [ ] No console errors; exiting AR restores the pre-AR transform (already in- `_handleEnd`).--## Out of scope--- Cross-user pose agreement and nudge calibration → **A3**.-- iOS gyro dead-reckoning → **A4**.-- Visual/VPS relocalization → noted as future in A3.--## Verify--- Android Chrome on a real phone: enter, see reticle on floor, tap, walk a metre- in each direction — agent holds its spot. Reload, confirm the pin reloads near- the same place via nearby GET.-- Toggle airplane mode mid-session → error state with Retry, not a freeze.-- iOS Safari: floor-anchor entry absent; Pin (A4) still works.-- Desktop Chrome (no XR): `isSupported()` false, no entry, no console noise.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/A1-webxr-world-anchor.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/A2-anchor-persistence-schema.md b/tasks/irl-live/A2-anchor-persistence-schema.mddeleted file mode 100644index 5c53c0319..000000000--- a/tasks/irl-live/A2-anchor-persistence-schema.md+++ /dev/null@@ -1,159 +0,0 @@-# IRL-Live A2 — Anchor pose persistence schema--**Epic A · Effort: M · Depends on:** nothing (foundation; A1/A3/A4 depend on it)--## Goal--Extend `irl_pins` so a placement stores a full, reproducible **anchor pose** —-not just `lat/lng/heading`. Add columns for vertical offset, orientation, and-sensor-accuracy metadata so any later session or any other user can reconstruct-where the agent stands in the real world. Migrate `savePin()` to capture and-send the pose; update the POST handler in `api/irl/pins.js` to store it.--## Why it matters (user value)--Today a pin is a 2D dot with a compass heading. That loses the floor height-(agent floats or sinks indoors / on slopes), loses precise orientation, and-keeps no record of how trustworthy the GPS fix was. Persisting the full pose is-the prerequisite for A1 (WebXR anchors), A3 (everyone sees it in the same spot),-and A4 (gyro lock reproducing the placement). Without it, multiplayer anchoring-is guesswork.--## Current state (real files + lines)--- `api/irl/pins.js` — `ensureTable()` (lines 29–51) idempotently creates- `irl_pins` with `id, user_id, agent_id, device_token, lat, lng, heading,- avatar_url, avatar_name, caption, x402_endpoint, placed_at, expires_at`. POST- (lines 130–167) inserts those. Nearby GET selects `heading` (lines 107–116).-- `src/irl.js` — `savePin(lat, lng, heading=0, caption='')` (line 837) POSTs- `{ lat, lng, heading, caption, avatarUrl, avatarName, deviceToken, agentId }`.- GPS accuracy/altitude are available on `pos.coords` in `onGPSPosition`- (line ~794) but currently discarded; `EYE_HEIGHT = 1.6` (line 766).--## What to build--### 1. Idempotent migration (`api/irl/pins.js`, inside `ensureTable()`)--Keep the existing `CREATE TABLE IF NOT EXISTS`, then add columns with the same-idempotent pattern so it is safe on every cold start:--```js-async function ensureTable() {- if (_tableReady) return;- await sql`CREATE TABLE IF NOT EXISTS irl_pins ( /* …existing columns… */ )`;- // Anchor pose — added 2026-06 for IRL-Live world anchoring (A2).- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_height_m DOUBLE PRECISION`;- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_yaw_deg DOUBLE PRECISION`;- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_quat JSONB`; // [x,y,z,w], optional richer orientation- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS gps_accuracy_m DOUBLE PRECISION`;- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS altitude_m DOUBLE PRECISION`;- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS anchor_source TEXT`; // 'webxr' | 'gyro-gps'- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS vps_provider TEXT`; // reserved for visual positioning- await sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS vps_id TEXT`; // reserved- await sql`CREATE INDEX IF NOT EXISTS irl_pins_lat_lng ON irl_pins (lat, lng)`;- await sql`CREATE INDEX IF NOT EXISTS irl_pins_expires ON irl_pins (expires_at)`;- _tableReady = true;-}-```--`anchor_yaw_deg` is the canonical orientation A3/A4 read; `anchor_quat` is an-optional full-orientation upgrade for WebXR. `vps_provider/vps_id` are reserved-nullable columns — no provider is wired yet; they exist so A3's future-visual-positioning path needs no further migration. They reference no coin and-no third-party token; $THREE remains the only coin this platform references.--### 2. POST accepts pose (`api/irl/pins.js`, lines 130–167)--```js-const pose = body.anchor ?? {};-const [pin] = await sql`- INSERT INTO irl_pins- (user_id, agent_id, device_token, lat, lng, heading,- avatar_url, avatar_name, caption, x402_endpoint, expires_at,- anchor_height_m, anchor_yaw_deg, anchor_quat,- gps_accuracy_m, altitude_m, anchor_source)- VALUES (- ${userId}, ${body.agentId ?? null}, ${body.deviceToken ?? null},- ${lat}, ${lng}, ${parseFloat(body.heading) || 0},- ${body.avatarUrl ?? null}, ${body.avatarName ?? null},- ${body.caption ?? null}, ${body.x402Endpoint ?? null}, ${expiresAt},- ${Number.isFinite(pose.heightM) ? pose.heightM : null},- ${Number.isFinite(pose.yawDeg) ? pose.yawDeg : null},- ${Array.isArray(pose.quat) ? JSON.stringify(pose.quat) : null},- ${Number.isFinite(pose.gpsAccuracyM) ? pose.gpsAccuracyM : null},- ${Number.isFinite(pose.altitudeM) ? pose.altitudeM : null},- ${pose.source === 'webxr' ? 'webxr' : 'gyro-gps'}- )- RETURNING *-`;-```--Validate softly: a missing `anchor` object inserts NULLs and the pin still-works (back-compat with old clients). Clamp `gps_accuracy_m` to a sane range-(0–500 m); reject absurd `height_m` (> ±50 m) to NULL rather than store noise.--### 3. Read pose back (nearby + mine GETs)--Add `anchor_height_m, anchor_yaw_deg, anchor_quat, gps_accuracy_m, altitude_m,-anchor_source` to the SELECT column lists in the nearby GET (line 108) and the-`?mine=1` GET (line 84) so A3/A4 and the dashboard can consume them.--### 4. Capture pose in the client (`src/irl.js`)--- In `onGPSPosition` (line ~794), retain `gpsState.accuracy = pos.coords.accuracy`- and `gpsState.altitude = pos.coords.altitude ?? null`.-- Change the signature to `savePin(lat, lng, heading=0, caption='', anchor=null)`- and merge `anchor` into the POST body as `anchor: { heightM, yawDeg, quat,- gpsAccuracyM: gpsState.accuracy, altitudeM: gpsState.altitude, source }`.-- For the existing gyro path (`setLocked`, line 713), pass- `{ heightM: EYE_HEIGHT - <floor offset, default 0>, yawDeg: headingDeg,- gpsAccuracyM: gpsState.accuracy, source: 'gyro-gps' }` so even today's- placements persist real accuracy metadata.--## Data / API changes--- `irl_pins`: +`anchor_height_m, anchor_yaw_deg, anchor_quat, gps_accuracy_m,- altitude_m, anchor_source, vps_provider, vps_id`. All nullable, additive.-- `POST /api/irl/pins`: optional `anchor` object in body.-- Nearby + mine GETs return the new fields.--## Acceptance criteria--- [ ] `ensureTable()` runs the `ADD COLUMN IF NOT EXISTS` migration idempotently;- safe on a populated table and on repeat cold starts.-- [ ] POST stores pose when present; old clients (no `anchor`) still create a- valid pin (NULL pose).-- [ ] Nearby + mine GETs return the new pose fields.-- [ ] `savePin()` captures and sends `gpsAccuracyM` + `altitudeM` from- `pos.coords` for both gyro and (later) WebXR placements.-- [ ] Out-of-range height / accuracy values coerce to NULL, not stored.-- [ ] No other token referenced; `vps_*` columns are reserved + empty.--## Out of scope--- Using the pose to render (A1/A4) or to reconcile across users (A3).-- Any actual VPS provider integration — columns are reserved only.--## Verify--- Hit `POST /api/irl/pins` with and without an `anchor` body via a local mock- `req/res` (dev proxies `/api` to prod, so exercise the handler directly per- the `pump [action] shadows` memory note) — both 201.-- `SELECT column_name FROM information_schema.columns WHERE table_name='irl_pins'`- shows the new columns after one request.-- Place a pin in `/irl` on a phone; confirm the row has non-NULL- `gps_accuracy_m` and `anchor_yaw_deg`.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/A2-anchor-persistence-schema.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/A3-cross-user-anchor-consistency.md b/tasks/irl-live/A3-cross-user-anchor-consistency.mddeleted file mode 100644index f27c134eb..000000000--- a/tasks/irl-live/A3-cross-user-anchor-consistency.md+++ /dev/null@@ -1,164 +0,0 @@-# IRL-Live A3 — Cross-user anchor consistency--**Epic A · Effort: L · Depends on:** A2 (pose schema), A1 + A4 (the two render paths it reconciles)--## Goal--Make **every** viewer see a placed agent in the **same** real-world spot. Align-each viewing device's compass heading and GPS to the stored pose, compensate for-GPS drift, and add a lightweight "nudge to calibrate" gesture: the owner (or a-trusted viewer) drags the agent a few centimetres / degrees and the corrected-pose re-saves for everyone. Be honest about GPS accuracy limits and lay the-explicit path to visual/VPS anchoring.--## Why it matters (user value)--Multiplayer is the whole point of IRL-Live: "anyone at the location sees-anyone's placed agent, live." If two phones disagree by 8 metres, the illusion-breaks and the social moment (meet at the agent, pay it, screenshot it) dies.-Cross-user consistency is what turns placed agents from a private AR toy into a-shared layer of the world.--## Current state (real files + lines)--- `src/irl.js` — every viewer already loads foreign pins (`loadNearbyPins`- line 901) and positions them with `gpsToWorld()` (line 778), which is- **relative to the viewer's own GPS origin** (`gpsState`, line 774). Heading is- applied per-pin in `spawnNearbyPin` (line 955: `g.rotation.y = -(heading…)`).- There is no compass-frame alignment between devices and no drift handling.-- A2 adds `anchor_height_m`, `anchor_yaw_deg`, `gps_accuracy_m`, `altitude_m`.-- `src/shared/state-kit.js` for the calibration affordance's states.--## What to build--### 1. Stored-pose frame alignment (read path)--When rendering a foreign pin, place it in the viewer's local frame from the-**stored absolute pose**, not the viewer's incidental heading:--```js-// gpsToWorld already maps lat/lng → local metres around the viewer.-const wp = gpsToWorld(pin.lat, pin.lng);-pin.group.position.set(wp.x, pin.anchor_height_m ?? 0, wp.z);-// Orientation is absolute compass yaw (stored), independent of viewer facing:-pin.group.rotation.y = -((pin.anchor_yaw_deg ?? pin.heading ?? 0) * Math.PI/180);-```--Because both the placing device and the viewer reference **absolute** compass-yaw (the client already prefers `deviceorientationabsolute`, `src/irl.js`-line 670) and a shared geodetic frame (lat/lng), the agent lands in the same-bearing for everyone. Use `anchor_height_m` so it sits on the floor, not at the-viewer's incidental eye height.--### 2. GPS drift compensation--GPS jitters frame-to-frame. Smooth the *viewer's* origin, not the pin, so pins-don't swim:--```js-// Low-pass the viewer origin; ignore fixes worse than the stored pin accuracy.-function blendOrigin(prev, fix) {- if (fix.accuracy > 35) return prev; // reject very noisy fixes- const k = Math.min(0.4, 12 / fix.accuracy); // trust tighter fixes more- return { lat: prev.lat + (fix.lat-prev.lat)*k, lng: prev.lng + (fix.lng-prev.lng)*k };-}-```--Render a **confidence ring** under each agent scaled by-`max(viewer_accuracy, pin.gps_accuracy_m)` so users *see* the uncertainty-instead of being misled into thinking it's centimetre-perfect.--### 3. "Nudge to calibrate" UI--A small, deliberate affordance — not free-drag (which would let anyone move-anyone's agent). Long-press a pin the device owns (or that the user placed →-`device_token`/`user_id` match) to enter calibrate mode:--```js-// Drag = horizontal nudge in metres; two-finger rotate = yaw nudge in degrees.-// Clamp to small corrections so this is calibration, not relocation.-const dLat = clamp(dragNorthM, -3, 3) / 110540;-const dLng = clamp(dragEastM, -3, 3) / (111320*Math.cos(lat*Math.PI/180));-const newYaw = (storedYaw + clamp(rotateDeg, -45, 45) + 360) % 360;-// On release, re-save the corrected pose for everyone:-await fetch('/api/irl/pins', { method:'PATCH', credentials:'include',- headers:{'Content-Type':'application/json'},- body: JSON.stringify({ id, calibrate:{ lat:lat+dLat, lng:lng+dLng,- anchorYawDeg:newYaw, anchorHeightM:newHeight } }) });-```--Extend the PATCH handler in `api/irl/pins.js` (currently caption-only,-lines 170–182) to accept a `calibrate` object **only** when-`user_id = session.id` (owner-gated; anonymous device-token owners may calibrate-their own via `device_token` match). Validate the nudge is within bounds server-side too (reject deltas > a few metres / 45°) so calibration can never be abused-to teleport an agent.--### 4. Honest accuracy + the VPS path--- Show a one-line note in the inspect/calibrate UI: "Position is GPS-accurate to- ~Xm. Drag to fine-tune." using `pin.gps_accuracy_m`.-- Document the ceiling: consumer GPS is ~5–15 m open-sky, far worse in urban- canyons / indoors — sub-metre cross-user agreement needs **visual positioning- (VPS)**. A2 already reserved `vps_provider` / `vps_id`. The future path:- capture a feature snapshot at placement, relocalize viewers against it, and- store the VPS frame in those columns. Build the nudge + confidence ring now so- the UX degrades gracefully until VPS lands. No coin is involved anywhere here.--### 5. Designed states--- **Low accuracy** (`gps_accuracy_m > 25`): amber confidence ring + "Find a spot- with clearer sky for a tighter lock" tip — never silently misplace.-- **Calibration denied** (not owner): inline "Only the owner can calibrate this- agent" via `errorStateEl`, no drag.-- **Save failed**: revert the nudge optimistically-undo + retry chip; never- leave a half-applied local-only correction.--## Data / API changes--- `PATCH /api/irl/pins` accepts `{ id, calibrate: { lat, lng, anchorYawDeg,- anchorHeightM } }`, owner-gated, server-side bounds-checked; updates the A2- pose columns. No new table.--## Acceptance criteria--- [ ] Foreign pins render from stored absolute yaw + `anchor_height_m`, so two- devices at the same place see the same bearing/floor position.-- [ ] Viewer GPS origin is low-pass smoothed; noisy fixes (>35 m) ignored; pins- don't swim frame-to-frame.-- [ ] A confidence ring communicates real uncertainty from `gps_accuracy_m`.-- [ ] Long-press calibrate is owner-gated; nudge is clamped to small deltas and- re-saves the pose for all viewers via PATCH.-- [ ] PATCH rejects out-of-bounds calibrate deltas and non-owners server-side.-- [ ] Accuracy is stated honestly in copy; VPS path documented and its reserved- columns referenced, not faked.-- [ ] Low-accuracy / denied / save-failed states all designed.--## Out of scope--- Implementing an actual VPS provider (reserved columns only).-- Realtime propagation of a calibration to already-loaded viewers → that rides- on **D1** realtime pin sync; here a re-fetch suffices.--## Verify--- Two phones at one location: place on phone A, confirm phone B shows the agent- in the same real spot and bearing (within the displayed accuracy ring).-- Calibrate-nudge on the owner phone, re-fetch on the other → corrected pose.-- Attempt calibrate from a non-owner device → blocked client + 403/404 server.-- Indoors / urban canyon: confidence ring widens, copy warns; agent still- placed, just honestly uncertain.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/A3-cross-user-anchor-consistency.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/A4-ios-gyro-anchor-fallback.md b/tasks/irl-live/A4-ios-gyro-anchor-fallback.mddeleted file mode 100644index bbd73bd8c..000000000--- a/tasks/irl-live/A4-ios-gyro-anchor-fallback.md+++ /dev/null@@ -1,168 +0,0 @@-# IRL-Live A4 — iOS gyro + GPS world-lock fallback--**Epic A · Effort: M · Depends on:** A2 (pose schema) · pairs with A1 for full device coverage--## Goal--On iOS Safari — which has **no WebXR** — world-lock the placed avatar using gyro-orientation plus GPS dead-reckoning. When locked, the avatar's world transform is-fixed at its GPS+pose anchor; the camera's rotation (`cameraYaw`/`cameraPitch`-from `onDeviceOrientation`) and GPS translation drive the *view*, so the avatar-**stays in its real spot** when the user pans the phone or walks, instead of-following the camera.--## Why it matters (user value)--iOS Safari is the single biggest slice of mobile traffic and gets zero WebXR.-Without a solid fallback, half the audience sees a floating, camera-glued avatar-— the exact thing IRL-Live exists to fix. This task makes the iPhone experience-feel anchored too, so "anyone at the location" genuinely includes iPhone users.-(See the `ios-safari-desktop-fallback` memory note — iOS Safari quirks are real;-design for them.)--## Current state (real files + lines)--- `src/irl.js` already has most of the machinery:- - `onDeviceOrientation()` (line 654) converts gyro alpha/beta deltas into- `cameraYaw`/`cameraPitch` once locked, preferring `deviceorientationabsolute`- (line 670).- - `setLocked(next)` (line 682) requests iOS motion permission- (`DeviceOrientationEvent.requestPermission`, line 684), captures a gyro- baseline, derives a GPS pin from `avatarRig.position` (lines 714–717), sets- `gpsModeActive` (line 718), and saves via `openCaptionPanel` → `savePin`.- - `gpsToWorld()` (line 778) maps lat/lng → local metres around the viewer.- - `tick()` GPS-mode branch (lines 1352–1366): camera sits at- `(0, EYE_HEIGHT, 0)`, rotation driven by `cameraYaw/Pitch`; the avatar is- re-positioned from its GPS pin in `onGPSPosition` (lines 803–806).-- **Gap:** the avatar's anchor doesn't use A2's `anchor_height_m`/`anchor_yaw_deg`,- GPS translation isn't applied to the *locked own* avatar as the user walks, and- there is no designed state when motion permission is denied or absolute- heading is unavailable.--## What to build--### 1. Fix the avatar to a full pose anchor, not just lat/lng--When `setLocked(true)` on iOS, store the same A2 pose the WebXR path stores so-the placement is reproducible and consistent with A1/A3:--```js-const headingDeg = ((cameraYaw * 180/Math.PI) % 360 + 360) % 360;-savePin(pinLat, pinLng, headingDeg, caption, {- heightM: 0, // avatar feet on ground plane (y=0 in IRL scene)- yawDeg: headingDeg,- gpsAccuracyM: gpsState.accuracy,- altitudeM: gpsState.altitude ?? null,- source: 'gyro-gps',-});-```--Keep the existing `avatarYaw = -(headingDeg…)` snap (line 725) so the locked-avatar faces the stored bearing — matching how `spawnNearbyPin` rotates foreign-avatars (A3 §1).--### 2. Camera-relative → world-relative while locked--The view must update from the device, leaving the avatar planted. The GPS-mode-camera branch already does the rotation half (lines 1352–1366). Add the-**translation** half so walking moves the *camera through the world*, not the-avatar:--```js-if (gpsModeActive && avatarLocked && arActive) {- // Avatar stays at its anchored GPS world point (set in onGPSPosition).- const me = gpsToWorld(gpsState.lat, gpsState.lng); // viewer's live position- camera.position.set(me.x, EYE_HEIGHT, me.z); // walk = camera moves- camera.rotation.order = 'YXZ';- camera.rotation.y = cameraYaw; // pan = gyro yaw- camera.rotation.x = -cameraPitch;- camera.rotation.z = 0;- // camLookCurrent recomputed from yaw/pitch as today (lines 1362–1366)-}-```--The locked avatar's world position is already refreshed from its GPS pin each-fix (`onGPSPosition`, lines 803–806). Net effect: pan the phone → avatar slides-across the frame to stay on its real bearing; walk toward it → it grows and-holds its spot. Apply `anchor_height_m` to the avatar's `y` for floor-correct-placement on slopes/indoors.--### 3. Heading-frame correctness--Dead-reckoning is only consistent across users if yaw is **absolute** (compass),-not page-relative. Track which source fired:--```js-// prefersAbsOrientation already set (line 671). If only relative is available,-// the agent still locks locally but cross-user bearing (A3) degrades — flag it.-if (!prefersAbsOrientation) {- setStatus('Compass heading unavailable — others may see this agent rotated',- { warn: true });-}-```--Store the absolute-vs-relative distinction so A3 can weight it (reuse-`anchor_source = 'gyro-gps'`; optionally append `:rel` when only page-relative).--### 4. Designed states (the iOS-critical ones)--- **Motion permission denied** (`requestPermission()` ≠ 'granted', line 687):- already sets an error status — upgrade to an `errorStateEl` with a "How to- enable Motion & Orientation in Settings > Safari" action; the lock must not- silently no-op.-- **GPS not ready** (`!gpsState.ready`): the lock currently still flips on but- has no anchor — show "Waiting for location to pin precisely…" and defer the- save until the first fix, rather than pinning at a default origin.-- **No absolute compass**: warn as in §3; still allow the lock (local view works).-- **Permission re-grant**: a tap on the locked state re-runs- `requestPermission()` so a user who declined can recover without reload.--## Data / API changes--None new. Uses A2's `savePin(…, anchor)` signature + pose columns. No coin-referenced anywhere.--## Acceptance criteria--- [ ] On iOS Safari, locking pins the avatar; panning the phone leaves it on its- real-world bearing (it does **not** follow the camera).-- [ ] Walking moves the camera through the world; the locked avatar grows/holds- its spot rather than translating with the user.-- [ ] Placement persists the A2 pose (`yawDeg`, `gpsAccuracyM`, `source`),- consistent with A1/A3.-- [ ] `anchor_height_m` is applied so the avatar sits on the ground plane.-- [ ] Motion-permission-denied, GPS-not-ready, and no-absolute-compass states- are all designed and recoverable (re-tap re-requests permission).-- [ ] Absolute-vs-relative heading distinction recorded for A3 weighting.-- [ ] No console errors; unlocking restores normal follow camera (existing path).--## Out of scope--- WebXR floor anchoring (Android) → **A1**.-- Cross-user reconciliation + nudge calibration → **A3** (this task only ensures- the iOS placement *produces* a correct, consistent pose to reconcile).--## Verify--- Real iPhone (Safari), not headless WebKit (the memory note: the iOS layout/- sensor quirks only repro on device): lock, pan ±90° → avatar holds its spot;- walk 3 m toward it → it enlarges and stays put.-- Decline the motion prompt → designed error with Settings guidance; re-tap →- re-prompts.-- Lock before first GPS fix → "Waiting for location…", then auto-pins on fix.-- Confirm the saved row has `anchor_source='gyro-gps'` and a real- `gps_accuracy_m`.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/A4-ios-gyro-anchor-fallback.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/B1-camera-aware-lookat.md b/tasks/irl-live/B1-camera-aware-lookat.mddeleted file mode 100644index bbe54979d..000000000--- a/tasks/irl-live/B1-camera-aware-lookat.md+++ /dev/null@@ -1,142 +0,0 @@-# B1 — Camera-aware look-at (agents notice the viewer)--## Goal--Nearby placed agents become **aware of the viewer**: each loaded agent smoothly-turns its head/torso (or whole body) to face the phone camera as the user walks-around it — the AR analog of the desktop "avatar follows the mouse cursor"-trick, where here the cursor *is* the phone. Add idle micro-behaviours when-nobody is close and a subtle "notice" reaction when the viewer gets near.--## Why it matters--A locked GLB that stares blankly at a fixed heading reads as a prop. An agent-that catches your eye when you walk up to it reads as *present* — this is the-moment IRL stops being a sticker on the world and becomes a being in it. It is-the single cheapest thing that makes someone screenshot the feature.--## Current state (real lines)--`src/irl.js`:-- `loadPinGLB(pin)` ~990 swaps the beacon for `gltf.scene`, re-applies- `pin.group.rotation.y = -(pin.heading * Math.PI / 180)` ~1002, sets- `pin.glbLoaded = true`. The whole model is parented under `pin.group`.-- `nearbyPins` entries carry `{ ...pin, group, labelEl, glbLoaded, distance_m }`- (created in `spawnNearbyPin` ~924).-- `tick()` ~1295 is the single rAF loop. After `animMgr.update(dt)` ~1383 it- calls `updateLabels()` ~1395 / `updateRadar()` ~1396 then renders. The viewer- camera world position is `camera.position` (in GPS mode pinned to- `(0, EYE_HEIGHT, 0)` ~1357).-- `lerpAngle(a, b, t)` ~1289 already exists for shortest-arc yaw easing — reuse it.--There is **no** per-frame orientation logic for nearby agents today; heading is-applied once at load.--## What to build--A `updateAgentAwareness(dt)` step, called from `tick()` right after-`animMgr.update(dt)`, that turns loaded agents toward the camera.--1. **Cache the head/spine bone on load.** In `loadPinGLB`, after the model is- added, traverse for a head/neck bone and store it on the pin so we don't walk- the tree every frame:- ```js- pin.headBone = null; pin.spineBone = null; pin.baseYaw = pin.group.rotation.y;- model.traverse(n => {- if (!n.isBone) return;- const nm = n.name.toLowerCase();- if (!pin.headBone && /head|neck/.test(nm)) pin.headBone = n;- if (!pin.spineBone && /spine|chest|torso/.test(nm)) pin.spineBone = n;- });- pin.restHeadQuat = pin.headBone?.quaternion.clone() || null;- ```-2. **Per-frame, cheap, gated.** Only process agents that are loaded AND within- `AWARE_RADIUS_M` (e.g. 12 m via `pin.distance_m`) AND on-screen (reuse the- `_lblVec.project(camera)` test from `updateLabels`). Cap to the nearest ~5.- ```js- const AWARE_RADIUS_M = 12, NOTICE_RADIUS_M = 4;- const HEAD_CLAMP = 0.7, BODY_SLERP = 0.05, HEAD_SLERP = 0.12; // ~rad, eased- ```-3. **Aim the body (yaw only) toward the camera ground projection**, eased with- `lerpAngle` so it never snaps:- ```js- const dx = camera.position.x - pin.group.position.x;- const dz = camera.position.z - pin.group.position.z;- const wantYaw = Math.atan2(dx, dz);- pin.group.rotation.y = lerpAngle(pin.group.rotation.y, wantYaw, BODY_SLERP);- ```- When the viewer is outside `AWARE_RADIUS_M`, ease `rotation.y` back to- `pin.baseYaw` instead so it returns to its placed heading.-4. **Layer head tracking on top, clamped to a natural neck cone.** If a head- bone exists, slerp it toward a target that looks at the camera, but clamp the- relative yaw/pitch to `±HEAD_CLAMP` so it never does an owl-twist; fall back- to body-only turn when the bone is missing. Build the target with a temp- `Quaternion`/`Matrix4.lookAt`, decompose relative to the parent, clamp, slerp- from `pin.restHeadQuat`.-5. **Idle micro-behaviour (not engaged).** When no viewer is within- `AWARE_RADIUS_M`, drive a slow sine-based head drift + occasional weight- shift so the agent looks alive, not frozen:- ```js- pin.idleT = (pin.idleT || 0) + dt;- const driftYaw = Math.sin(pin.idleT * 0.4) * 0.12;- ```-6. **"Notice" reaction on approach.** The first frame `pin.distance_m` crosses- below `NOTICE_RADIUS_M` (track `pin.noticed`), trigger a one-shot: snap the- head-slerp speed up for ~400 ms and, if the AnimationManager exposes a- greet/wave clip, `animMgr` crossfade to it then back to idle; otherwise a- small +Y scale pop (1.0→1.04→1.0) on `pin.group`. Reset `pin.noticed=false`- when they leave so re-approach re-greets.--`tick()` wiring:-```js-animMgr.update(dt);-updateAgentAwareness(dt); // ← new, before label projection-updateLabels();-```--## Data / API changes--None. Pure client render logic over data already in `nearbyPins`. No new fields,-no endpoint, no DB.--## Acceptance checklist--- [ ] Loaded agents within ~12 m visibly turn to face the phone camera as the- user circles them; motion is eased (no snapping) via slerp/lerp.-- [ ] Head/neck turn is clamped to a natural cone; no owl-head over-rotation.-- [ ] Agents with no head bone fall back to whole-body yaw cleanly.-- [ ] Outside the aware radius, agents ease back to their placed `heading`.-- [ ] Idle agents show subtle gaze drift, not a frozen stare.-- [ ] Crossing the notice radius fires a one-shot greet/pop exactly once per- approach; leaving + re-approaching re-fires it.-- [ ] Only loaded, on-screen, nearest-N agents are processed each frame; no- measurable FPS drop with 5 agents on a mid-tier phone.-- [ ] No console errors; no per-frame allocations (reuse temp vectors/quats).--## Out of scope--- Cross-user broadcast of where an agent is looking (single-viewer only here).-- Gaze toward *other* agents or full IK. Real animation-clip authoring.-- Eye-bone / blendshape tracking (head-bone granularity is enough).--## Verify--`npm run dev`, open `/irl` on a phone (or device-emulated viewport), place/lock-an agent, then move the camera around it. Confirm the agent tracks you, eases-back when you back off, idles when you leave the radius, and greets once on-approach. Profile a frame in DevTools to confirm `updateAgentAwareness` stays-sub-millisecond with 5 loaded agents.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/B1-camera-aware-lookat.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/B2-inspect-card-v2.md b/tasks/irl-live/B2-inspect-card-v2.mddeleted file mode 100644index 81133b66d..000000000--- a/tasks/irl-live/B2-inspect-card-v2.md+++ /dev/null@@ -1,165 +0,0 @@-# B2 — Inspect card v2 (rich tap card with reputation + services)--## Goal--Tapping a nearby agent opens a **rich card** that replaces today's thin-interaction sheet: avatar name, a short bio/info line, reputation (a derived-score + attestation count + tier badge), and the **services it provides** (the-agent's skills with their x402 prices) plus primary CTAs. The client makes **one-call** to a new aggregation endpoint that joins the agent record + Solana-reputation + skills/prices into a single payload.--## Why it matters--The current sheet shows a name, a caption, and two buttons — it tells the viewer-nothing about *why* they'd trust or pay this agent. A card that surfaces-reputation and a real service menu turns a tap into a decision. One aggregation-call (instead of three round-trips from a phone on cellular) is the difference-between an instant card and a janky one.--## Current state (real lines)--`src/irl.js`:-- `openPinSheet(pin)` ~1135 fills `#irl-sheet-name`, `#irl-sheet-dist`,- `#irl-sheet-caption`, toggles `#irl-sheet-pay` on `pin.x402_endpoint`, stashes- `pin.agent_id`/`pin.avatar_name` on `sheet.dataset`, adds `.is-open`.-- The pin object carries `agent_id, avatar_name, caption, x402_endpoint,- distance_m, avatar_url`. Markup `#irl-sheet*` lives in `pages/irl.html`.--Data sources to join (all real, already deployed):-- Agent record: `GET /api/agents/:id` → `agent.name`, `agent.description`,- `agent.meta.sol_mint_address` / `agent.meta.solana_address`,- `agent.skill_prices` (`{ skill: { amount, currency_mint, chain } }`),- avatar thumbnail keys. (`handleGetOne` in `api/agents.js` ~314.)-- Reputation: `GET /api/agents/solana-reputation?asset=<sol_mint_address>` →- `feedback.{total,score_avg,unique_attesters}`, `validation.*`,- `tasks.{offered,accepted}`, `stake.unique_stakers` (raw aggregates, **no tier- field** — derive tier client/server here). (`_handlers.js` ~900.)-- Skills catalog: `GET /api/skills` → `{ skills:[{ id,name,slug,description,- price_per_call_usd,category }] }` for service descriptions/prices.--## What to build--### 1. New aggregation endpoint `GET /api/irl/agent-card?agent_id=<uuid>`--A single Vercel function (`api/irl/agent-card.js`, `cors`/`json`/`wrap` like-`api/irl/pins.js`) that fans out server-side and returns one merged payload.-Resolve the agent's `sol_mint_address` from the agent record, then fetch-reputation with it; **derive a tier + a 0–100 score** from the raw aggregates so-the client renders a badge without re-implementing the formula:--```jsonc-{- "agent": {- "id": "uuid",- "name": "Atlas",- "bio": "Trip-planning agent for…", // agent.description, trimmed- "thumbnail_url": "/cdn/<thumbnail_key>", // null-safe- "profile_url": "/agents/uuid"- },- "reputation": {- "asset": "<sol_mint_address>|null",- "score": 78, // 0–100 derived- "tier": "trusted", // new|emerging|trusted|elite- "attestation_count": 23, // feedback.total + validation passes- "unique_attesters": 9,- "tasks_accepted": 14,- "available": true // false when no on-chain asset- },- "services": [ // skill_prices ∪ skills catalog- { "skill": "route-plan", "name": "Route planning",- "description": "…", "price_usd": 0.05,- "currency": "USDC", "chain": "base",- "x402_endpoint": "https://…/x402/route-plan" }- ],- "x402_endpoint": "<pin-level fallback endpoint|null>"-}-```--Tier derivation (server, explicit and documented in-file):-`score = clamp(round(60*scoreAvgNorm + 20*log-scaled(attesterCount) +-20*validationPassRate))`; `tier`: `score>=85 elite`, `>=60 trusted`,-`>=30 emerging`, else `new`. When `sol_mint_address` is absent, return-`reputation.available=false` and omit the score (card shows "No on-chain-reputation yet").--Services merge: start from `agent.skill_prices`, enrich each with-name/description from the skills catalog (match on slug), express price in USDC-(amount is already USDC-denominated atomics → format to `price_usd`), and carry-through the per-skill x402 endpoint. Cap the list (e.g. 6) and order by price.--Error boundaries: agent 404 → `404 {error}`. Reputation fetch failure must-**not** fail the card — degrade to `reputation.available=false` with a flag, so-the menu still renders. Cache `Cache-Control: public, max-age=30`.--### 2. Card UI in `src/irl.js` (replace the thin sheet body)--Render into the existing `#irl-sheet` (keep id/open mechanics) or a new-`#irl-card`, using `src/shared/state-kit.js` for every state:--- **Loading skeleton** — on tap, show the card frame immediately with- `skeletonHTML()` rows for name/rep/services while `/api/irl/agent-card`- resolves. Never a blank sheet.-- **Populated** — header (thumbnail + name + tier badge with score), bio line,- a reputation strip (`★ score · N attestations · tier`), then a **services- list**: each row = name, one-line description, price pill (`$0.05 USDC`), and a- per-service "Use" CTA. Footer CTAs: **View profile** and **Pay / use service**- (wired in B3).-- **Empty services** — `emptyStateHTML({ title:'No paid services yet', body:'This- agent is here to meet, not to sell.' })`; still show profile CTA.-- **No-reputation** — show a muted "New here — no on-chain reputation yet" chip- instead of a fake score.-- **Error** — `errorStateHTML({ title:"Couldn't load this agent", … })` +- `attachRetry()` re-calling the endpoint.--Fetch with `AbortController`; tapping a different agent aborts the in-flight-card so stale data never lands. Designed transitions on open/close (opacity +-translateY), focus the card on open, Escape/backdrop closes, ARIA `role="dialog"`.--## Data / API changes--- **New:** `api/irl/agent-card.js` + a `vercel.json` functions entry + route- `"/api/irl/agent-card"` (per the `[action].js` shadowing trap — give it its- own explicit route or it 404s in prod).-- No schema changes; reads existing tables via existing endpoints.--## Acceptance checklist--- [ ] `GET /api/irl/agent-card?agent_id=<real uuid>` returns the merged shape- with real reputation + real services in one response.-- [ ] Card opens with a skeleton, then populates; switching agents aborts the- prior fetch.-- [ ] Tier badge + score derive from real aggregates; agents with no on-chain- asset show the muted "no reputation yet" chip, never a fabricated number.-- [ ] Services list shows real skill names/descriptions and real USDC prices.-- [ ] Empty / no-rep / error states all designed via state-kit; error retries.-- [ ] Reputation-endpoint failure degrades gracefully (services still render).-- [ ] `role="dialog"`, focus management, Escape/backdrop close, no console errors.--## Out of scope--- Wiring the CTAs to real navigation/payment — that is **B3**.-- Editing which services an agent offers (owner-side) — that is **C2**.-- Realtime reputation updates while the card is open — **D3**.--## Verify--`npm run dev`; locally exercise `api/irl/agent-card.js` with a mock `req/res`-(dev proxies `/api` to prod, so test the new handler directly) against a real-agent uuid that has a `sol_mint_address` and at least one `skill_price`. Open-`/irl`, tap an agent, confirm skeleton→populated, switch agents to confirm-abort, and force the reputation fetch to fail to confirm graceful degrade.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/B2-inspect-card-v2.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/B3-real-interactions-profile-pay.md b/tasks/irl-live/B3-real-interactions-profile-pay.mddeleted file mode 100644index 87d7fb0ec..000000000--- a/tasks/irl-live/B3-real-interactions-profile-pay.md+++ /dev/null@@ -1,166 +0,0 @@-# B3 — Real interactions: view profile + x402 pay (+ ask)--> **Supersedes `tasks/irl/02-view-agent-profile.md` and-> `tasks/irl/03-x402-payment.md`.** Those described the thin sheet; this wires-> the B2 card's CTAs for real. Treat the old files as reference only.--## Goal--Make every CTA on the inspect card do something real:-- **View profile** → opens the agent's actual profile at `/agents/<agent_id>`.-- **Pay / use service** → a real x402 payment via `wrapFetch` with the- connected wallet, handling `402 → sign → retry`, with designed success and- error states (per-service prices are **USDC over x402** — fine; the only coin- the platform promotes is **$THREE**).-- **Ask** (optional) → a lightweight chat hook to `/api/chat` for the agent.-- Every completed interaction **POSTs an interaction event** (forward-reference- C4's `/api/irl/interactions`).--## Why it matters--A card full of dead buttons is a brochure. The whole point of IRL agents is that-a stranger can walk up, see what an agent offers, and *pay it on the spot*. This-task is where the loop closes: discovery → trust (B2) → transaction (B3).--## Current state (real lines)--`src/irl.js`:-- View handler `#irl-sheet-view` ~1157 already does- `window.open('/agents/'+agentId,'_blank','noopener')` with a `/walk?agent=`- name fallback — keep this behaviour, move it onto the card's button.-- Pay handler `#irl-sheet-pay` ~1169 is **already a real x402 flow**: gates on- `window.ethereum` → `eth_requestAccounts` → dynamic-imports- `../packages/x402-fetch/dist/index.esm.js` `withX402(window.ethereum,- { maxPaymentUsd })` → `pay(endpoint,{method:'POST'})` → `Paid ✓` / error via- `setStatus`. This is the canonical pattern to reuse per-service.-- `src/marketplace.js` ~2340 / ~3407 shows the documented public form- `wrapFetchWithPayment(fetch, wallet)` from `@three-ws/x402-fetch` — same- protocol; match whichever the card already imports via- `src/shared/x402-loader.js`.--The card (B2) provides per-service `x402_endpoint` + `price_usd`, plus a-pin-level fallback `x402_endpoint`.--## What to build--### 1. View profile--On the card's **View profile** button:-```js-agentId- ? window.open(`/agents/${agentId}`, '_blank', 'noopener')- : window.open(`/walk?agent=${encodeURIComponent(name)}`, '_blank', 'noopener');-```-Fire-and-forget `postInteraction({ agent_id, kind: 'view_profile' })`.--### 2. Pay / use service (per service row + footer CTA)--Reuse the existing pay flow, parameterised per service:-```js-async function payService({ endpoint, priceUsd, agentId, skill, btn }) {- if (!endpoint) return setStatus('This service has no endpoint yet', { error: true });- if (!window.ethereum) return setStatus('Connect a wallet (MetaMask) to pay via x402', { error: true });-- const orig = btn.textContent;- btn.disabled = true; btn.textContent = 'Connecting…';- const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }).catch(() => null);- if (!accounts?.length) { resetBtn(btn, orig); return setStatus('Connect your wallet to pay', { error: true }); }-- btn.textContent = 'Paying…';- try {- const { withX402 } = await import('../packages/x402-fetch/dist/index.esm.js');- const pay = withX402(window.ethereum, { maxPaymentUsd: Math.max(priceUsd, 0.01) });- const r = await pay(endpoint, { method: 'POST' }); // 402 → sign → retry inside- if (!r.ok) throw new Error(await r.text().catch(() => r.status));- btn.textContent = 'Used ✓'; btn.disabled = true;- setStatus('Service paid — response delivered');- postInteraction({ agent_id: agentId, kind: 'pay', skill, amount_usd: priceUsd });- } catch (err) {- const m = err?.message ?? String(err);- setStatus(/reject|denied|4001|cancel/i.test(m) ? 'Payment cancelled' : `Payment failed — ${m}`, { error: true });- resetBtn(btn, orig);- }-}-```-- Cap `maxPaymentUsd` at the service price (small guard) so a misconfigured- endpoint can't over-charge.-- Per-row buttons stay independent (only the clicked one shows in-flight state).-- On success, show the returned service result inline in the card when the body- is small (JSON/text), not just a toast — that is the value the user paid for.--### 3. Ask (optional chat hook)--If the card shows an **Ask** affordance, POST the user's prompt to `/api/chat`-with the agent id, stream/append the reply into a small thread inside the card,-designed loading + error states via `state-kit`. Log-`postInteraction({ agent_id, kind: 'message' })` on send. Keep it optional —-ship View + Pay first; Ask can be a follow-up if `/api/chat` wiring grows the-task.--### 4. Interaction event helper (forward-ref C4)--```js-function postInteraction(body) {- // best-effort; never block the UX on telemetry- fetch('/api/irl/interactions', {- method: 'POST', credentials: 'include',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ ...body, device_token: _deviceToken, at: Date.now() }),- }).catch(() => {});-}-```-Until C4 lands, this 404s harmlessly (swallowed). When C4 ships the-`/api/irl/interactions` endpoint + `irl_interactions` table, owner inboxes light-up with no client change. Document this contract here so C4 matches the shape:-`{ agent_id, kind: 'view_profile'|'pay'|'message', skill?, amount_usd?,-device_token, at }`.--## Data / API changes--- No new endpoint **owned by this task** (View + Pay use existing routes).-- Emits to `POST /api/irl/interactions` (defined by **C4**) — contract above.-- No schema changes here.--## Acceptance checklist--- [ ] View profile opens `/agents/<agent_id>` (name fallback when id missing).-- [ ] Pay performs a real x402 `402 → sign → retry` via `withX402`/`wrapFetch`- with the connected wallet — no mock, no raw `fetch` stub.-- [ ] `maxPaymentUsd` is bounded by the displayed price.-- [ ] Per-service buttons have independent loading/disabled/`✓`/error states.-- [ ] Wallet-not-connected, user-rejected, and endpoint-error paths each show a- distinct, recoverable message; buttons re-enable on failure.-- [ ] Paid service result is surfaced in the card when returned.-- [ ] Each completed action best-effort POSTs an interaction event; a 404/failure- never disrupts the user.-- [ ] No console errors; no leftover `// coming soon` / stub copy.--## Out of scope--- Building `/api/irl/interactions` + the owner inbox — that is **C4**.-- The card layout/skeleton itself — that is **B2** (this only wires its CTAs).-- Solana-wallet payment rails (this flow is EVM x402 via `window.ethereum`,- matching the existing IRL pay handler and `marketplace.js`).--## Verify--`npm run dev`, open `/irl`, tap an agent with a priced service. With a funded-test wallet, run a real x402 pay end-to-end (expect the `402` then the signed-retry succeeding) and confirm `Used ✓` + inline result. Decline the wallet-prompt to confirm the cancel path re-enables the button. Confirm View profile-opens the real `/agents/:id` page. Watch the network tab for the best-effort-`POST /api/irl/interactions` (404 pre-C4 is expected and silent).--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/B3-real-interactions-profile-pay.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/B4-raycast-tap-accuracy.md b/tasks/irl-live/B4-raycast-tap-accuracy.mddeleted file mode 100644index 36b0ab75e..000000000--- a/tasks/irl-live/B4-raycast-tap-accuracy.md+++ /dev/null@@ -1,128 +0,0 @@-# B4 — Raycast tap accuracy + proximity focus--## Goal--Make tapping an agent reliable. Raycast against **both** the floating billboard-label and the agent's 3D mesh, pick the nearest hit, expand hit targets for-touch, and add a proximity **focus highlight** on the nearest agent so the user-knows what they'll tap before they tap. Handle overlapping agents and small-on-screen targets gracefully.--## Why it matters--Right now you can only open an agent by hitting its tiny HTML name label — the-3D body itself is dead to touch, and labels overlap when agents cluster. On a-phone, a 24 px label is a frustrating target. Reliable tapping is the floor for-every interaction in Epic B; if the tap misses, none of B2/B3 matters.--## Current state (real lines)--`src/irl.js`:-- The only tap path today is `el.addEventListener('click', () =>- openPinSheet(pin))` on each label in `spawnNearbyPin` ~976. The 3D group- (`pin.group`, holding the beacon then the GLB) has **no** pointer handling.-- `updateLabels()` ~1254 already projects each `pin.group` to screen space with- `_lblVec.project(camera)` — reuse that projected position for label hit-tests- and for placing a focus ring.-- No `Raycaster` is instantiated for nearby pins yet. `camera`, `scene`, and- `nearbyPins[].group` are all in scope.--## What to build--### 1. Unified tap handler (mesh ∪ label, nearest wins)--Add one `pointerup`/`click` handler on the renderer canvas (not per-label) that:--1. **Mesh ray:** build a screen-space NDC from the touch point, `raycaster- .setFromCamera(ndc, camera)`, intersect against the loaded agent groups- (`raycaster.intersectObjects(loadedGroups, true)`), map the hit back to its- pin via `object.parent` walk (cache `pin` on the group: `g.userData.pin =- pin` in `spawnNearbyPin`). Nearest intersection = `meshHit { pin, distance }`.-2. **Label ray (2D):** for each on-screen label, compute pixel distance from the- tap to the label centre; any within an **expanded touch radius**- (`TAP_SLOP = 28px`, larger than the label box) is a `labelHit { pin,- pxDist }`. Nearest = best label hit.-3. **Resolve:** prefer the mesh hit when present (you tapped the body); else the- nearest label hit within slop. Open `openPinSheet(pin)` / the B2 card.- ```js- const TAP_SLOP = 28;- function handleTap(clientX, clientY) {- const meshPin = raycastNearestMesh(clientX, clientY);- const labelPin = nearestLabelWithinSlop(clientX, clientY, TAP_SLOP);- const pin = meshPin || labelPin;- if (pin) openPinSheet(pin);- }- ```- Keep the existing per-label `click` as a fallback for accessibility, but make- the canvas handler the primary path (remove the per-label one if it- double-fires).--### 2. Overlapping agents--When two agents project to nearly the same pixel, the raycaster's nearest-intersection (closest to camera) already disambiguates the body tap. For label-ties (both within slop), pick the one with the **smaller `distance_m`** (front-agent), and nudge the focus ring so the user can re-aim. No multi-select popup-needed.--### 3. Touch-friendly hit expansion--- Bump label CSS hit area: invisible padding / `::before` expanding the touch- box to ≥44 px (Apple HIG min) without changing the visible label.-- Treat `pointerdown`→`pointerup` within a small move threshold (~10 px) as a- tap; ignore drags (so panning/looking doesn't trigger taps).--### 4. Proximity focus highlight--Each frame (cheap; reuse the `updateLabels` projection loop), mark the **nearest-on-screen agent within reach** (smallest `distance_m`, on-screen) as focused:-- Add a CSS class to its label (e.g. `.irl-agent-label--focus`: brighter ring,- subtle scale) and/or draw a thin reticle ring at the projected screen pos.-- Only one agent is focused at a time; transitions are eased (opacity/transform).-- This gives the "you'll tap this" affordance and doubles as a target for the- overlap case.--## Data / API changes--None — pure client-side raycasting and CSS. One `Raycaster` instance reused-across taps; cache `g.userData.pin`; no per-frame allocations beyond the existing-projection vector.--## Acceptance checklist--- [ ] Tapping an agent's 3D body opens its card (mesh raycast works).-- [ ] Tapping near (within ~28 px of) a name label also opens it.-- [ ] Overlapping agents resolve to the nearest (front) agent, not a random one.-- [ ] Label touch area is ≥44 px; visible label unchanged.-- [ ] Dragging to look/pan does **not** register as a tap.-- [ ] The nearest reachable agent shows an eased focus highlight; only one at a- time; it updates as the user moves.-- [ ] No double-open from label + canvas handlers firing together.-- [ ] No console errors; no measurable FPS cost from focus tracking.--## Out of scope--- The card contents themselves (**B2**) and CTA wiring (**B3**).-- Look-at / awareness behaviour (**B1**) — independent.-- Multiplayer presence markers (**D2**).--## Verify--`npm run dev`, open `/irl` on a touch device/emulated viewport with 2–3-overlapping placed agents. Confirm body taps and near-label taps both open the-right agent, the front agent wins on overlap, a look-drag never opens a card,-and the focus ring tracks the nearest agent as you move.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/B4-raycast-tap-accuracy.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/C2-skills-services-management.md b/tasks/irl-live/C2-skills-services-management.mddeleted file mode 100644index 9500999e6..000000000--- a/tasks/irl-live/C2-skills-services-management.md+++ /dev/null@@ -1,131 +0,0 @@-# C2 — Skills & services management for an IRL agent--> Epic C · Size **M** · Opens from the C1 card "Skills" link.-> Depends on C1 (overview), pairs with B2 (the inspect card that renders these).--## Goal--Let an owner, from the dashboard, choose which **skills** their placed agent-offers IRL and set the **x402 per-call price** for each. These are exactly the-services that B2's tap card lists and B3 lets a passer-by pay for. Designed-attach/detach forms with validation, save states, and real persistence.--## Why it matters--A placed agent is only interesting if it *does* something payable. The whole-loop — tap → see services → pay via x402 → owner earns — starts with the owner-declaring services and prices. Today there's no dashboard path to do that for an-IRL-placed agent, so every pin is mute.--## Current state (real lines)--- Skill catalog: `GET /api/skills/index.js` lists `marketplace_skills`- (`:84` `handleList`) with `price_per_call_usd` per skill (`:71`). Install state- via `skill_installs` (`:204`).-- Canonical prices live in **`agent_skill_prices`** — see- `api/agents/x402/[action].js:20` `priceFor()`:- `SELECT amount, currency_mint, chain FROM agent_skill_prices WHERE agent_id=… AND skill=… AND is_active=true`.-- Single-skill upsert already exists: `POST /api/agent-skill-price?agentId=:id`- (`api/agent-skill-price.js:31`) — body `{ skill, amount, currency_mint, chain }`,- `amount=0` deactivates, CSRF-guarded (`:38`), owner-checked (`:52`).-- Bulk endpoint referenced in its header: `PUT /api/agents/:id/skills-pricing`.--## What to build--A **Services** panel (modal or expandable card region, matching `widgets.js`-modal pattern `:537`). Two sections:--### 1. Attached services list--`GET /api/agents/:id` (agent record exposes `skills[]`) joined with-`agent_skill_prices` to show each currently-priced skill:--```-┌ web-search ────────────────────────────── active ┐-│ 0.05 USDC / call · Solana │-│ [edit price] [pause] [remove] │-└────────────────────────────────────────────────────┘-```--### 2. Add a service--A picker fed by `GET /api/skills?installed=true` (the owner's own skills) plus a-price form. Real currency only — default the mint to **$THREE**-(`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) or USDC; never a third token.--```js-const form = { skill, amount, currency_mint, chain: 'solana' };-// validate before submit-if (!form.skill) return invalid('Pick a skill');-if (!(Number(form.amount) >= 0)) return invalid('Price must be ≥ 0');-if (!BASE58_RE.test(form.currency_mint)) return invalid('Invalid mint');--const r = await fetch(`/api/agent-skill-price?agentId=${agentId}`, {- method:'POST', credentials:'include',- headers:{ 'content-type':'application/json', 'x-csrf-token': csrf },- body: JSON.stringify(form),-});-```--`amount` is integer atomic units (see `bodySchema` `:16` — `z.number().int()`),-so the form must convert the displayed decimal (e.g. `0.05 USDC`) to atomic-(`50000` at 6 decimals) using the mint's decimals, and back for display. Surface-the human value, store the atomic value.--### Save states--Per-row: idle → `Saving…` (button disabled) → success pulse / inline error.-"Pause" = re-POST with the same row but `amount` set to deactivate, or a-dedicated `is_active=false` path. "Remove" confirms via the shared confirm modal-(`widgets.js:537`) then deactivates.--### Validation rules--- Price `≥ 0`; `0` documented as "free / deactivate".-- Mint must pass `BASE58_RE` (`api/agent-skill-price.js:14`).-- Block skills the agent doesn't actually expose (`agent_identities.skills[]`).-- CSRF token required (cookie-session mutation) — read from the dashboard session.--## Data / API changes--- Reuse `POST /api/agent-skill-price?agentId=:id` (no change) for single upserts.-- Optional: add a **read** endpoint `GET /api/agents/:id/skills-pricing` returning- active `agent_skill_prices` rows so the panel can render current prices without- scraping the x402 manifest. If `PUT /api/agents/:id/skills-pricing` exists,- reuse it for bulk save; otherwise loop the single-skill POST.-- No schema change — `agent_skill_prices` already exists.--## Acceptance checklist--- [ ] Panel lists currently-priced services for the placed agent with human price.-- [ ] Add-service picker only offers skills the agent exposes; decimal↔atomic- conversion correct against the mint's decimals.-- [ ] Save → real `agent_skill_prices` row written; pause/remove deactivate.-- [ ] CSRF token sent; non-owner gets 403; validation errors shown inline.-- [ ] Mint defaults to $THREE/USDC; no other token referenced anywhere.-- [ ] Loading/empty/error via state-kit; save states designed; no console errors.--## Out of scope--Authoring brand-new skills (that's the skills marketplace), and the pay flow-itself (B3). This task only attaches existing skills and prices them.--## Verify--`npm run dev` → open Skills from a C1 card → add `web-search` at `0.05 USDC` →-confirm a real `agent_skill_prices` row, then `GET /api/agents/:id/x402/manifest`-(or B2's `agent-card`) reflects the new price.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/C2-skills-services-management.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/C3-reputation-surface.md b/tasks/irl-live/C3-reputation-surface.mddeleted file mode 100644index 795f6f817..000000000--- a/tasks/irl-live/C3-reputation-surface.md+++ /dev/null@@ -1,104 +0,0 @@-# C3 — Reputation surface for a placed agent--> Epic C · Size **S** · Opens from the C1 card "Reputation" link.-> Depends on C1. Read-only; links out to the full passport/manage flow.--## Goal--Show the placed agent's on-chain reputation inside the dashboard card: a headline-score, trust tier, and the list of attestations behind it — with a link to the-full agent passport for management. Mirrors what B2's tap card shows a passer-by,-so the owner sees exactly what the public sees.--## Why it matters--Reputation is the single strongest reason a stranger pays an IRL agent. The owner-needs to confirm their agent is accruing it, and jump to the passport to manage-attestations. This closes the trust loop the marketplace already established —-Solana attestations are the canonical reputation source (not the dormant EVM-ERC-8004 path).--## Current state (real lines)--- `GET /api/agents/solana-reputation?asset=<pubkey>&network=mainnet|devnet`- (`api/agents/solana/_handlers.js:902` `handleReputation`, routed in- `vercel.json:419`). It aggregates `solana_attestations` of kind- `threews.feedback.v1` / `validation.v1` / `accept.v1` / `stake.v1` into counts:- `total, verified, credentialed, score_avg_weighted, unique_attesters, …` (`:926`).- History sparkline: `GET /api/agents/solana-reputation-history?asset=&days=`.-- Trust tiers are documented in `api/agents/SOLANA_OPS.md:85` ("read by- solana-reputation").-- **Keying:** the endpoint wants the agent's Solana **asset** pubkey, not the- wallet. C1's `agent-summary` should also select `a.meta->>'solana_asset'`; pass- that as `?asset=`. If the agent has no asset, show the empty state, not an error.-- An existing client renders this shape already: `src/pump/agent-token-widget.js:403`- fetches the same endpoint — reuse its parsing as reference.--## What to build--A compact **Reputation** panel (use `compact` state-kit variant for the empty-case). Render:--```js-const asset = agent.solana_asset; // from C1 agent-summary-if (!asset) return emptyStateHTML({ compact:true,- title:'No on-chain identity yet',- body:'This agent has no Solana asset, so it can\'t accrue attestations.',- actions:[{ label:'Open passport', href:`/agents/${agent.id}`, primary:true }] });--const { data } = await get(`/api/agents/solana-reputation?asset=${asset}&network=mainnet`);-// score: data.score_avg_weighted (0–100 band per tiers doc)-// tier: derive from counts (verified/credentialed attesters) per SOLANA_OPS.md-// list: data.total / verified / credentialed / disputed breakdown-```--Layout: a score ring/number + tier badge, then a small breakdown-(`N verified · N credentialed · N disputed`), then a **"Manage on passport →"**-link to `/agents/:id` (the canonical attestation management surface). Optionally-fetch `…-history` for a tiny sparkline; skip silently if it 404s.--### States (all via state-kit, `compact: true`)--- **Loading** — `skeletonHTML(1, 'text')`.-- **Empty** — no asset, or `total === 0`: "No attestations yet — share this agent- to start earning reputation." with a "View in IRL" / passport CTA.-- **Error** — endpoint failure → `errorStateHTML` + Retry (`attachRetry`).--## Data / API changes--None. Pure read against the existing `solana-reputation` endpoint. The only-upstream dependency is C1 selecting `solana_asset` in `agent-summary`.--## Acceptance checklist--- [ ] Panel shows score, tier badge, and verified/credentialed/disputed counts- from real `solana-reputation` data.-- [ ] "Manage on passport →" links to `/agents/:id`.-- [ ] No-asset and zero-attestation cases render the designed empty state, not an- error.-- [ ] Error state retryable; loading skeleton; no console errors.--## Out of scope--Writing/disputing attestations (lives on the passport), and the reputation-*history* visualization beyond an optional sparkline.--## Verify--`npm run dev` → open Reputation from a C1 card whose agent has a Solana asset →-Network tab shows one `solana-reputation` call returning real counts; the passport-link resolves.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/C3-reputation-surface.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/C4-interaction-inbox-notifications.md b/tasks/irl-live/C4-interaction-inbox-notifications.mddeleted file mode 100644index 0f75b9320..000000000--- a/tasks/irl-live/C4-interaction-inbox-notifications.md+++ /dev/null@@ -1,169 +0,0 @@-# C4 — Interaction log, inbox & notifications--> Epic C · Size **L** · The feedback loop. Pairs with D3 (realtime broadcast).-> Depends on C1 (overview surfaces unread counts). New table + 2 endpoints + UI.--## Goal--Record every IRL interaction with a placed agent (view, tap, pay, message) and-give the owner an **inbox**: a chronological feed of who interacted, where, and-how much they paid — with unread counts and notification hooks (in-app, plus-optional push/Telegram via the existing alert plumbing). This is what makes the-dashboard feel alive and turns C1's "interaction count" into something readable.--## Why it matters--Right now an owner has zero feedback when a stranger across the city taps their-agent or pays it. No feedback = no reason to return. The inbox is the dopamine-loop and the audit trail for earnings. It also feeds C1's status/last-seen and-D3's realtime ambient reactions.--## Current state (real lines)--- No interaction storage exists. `irl_pins` (`api/irl/pins.js:32`) has no child- table.-- B3 (planned) performs the real x402 pay from the IRL client; B2's tap card is- where a `view`/`tap` originates. Those are the call sites that will POST here.-- Notifications: `api/_lib/notify.js:11` `insertNotification(userId, type, payload)`- already exists (in-app). Telegram ops alerts plumbing exists- (`TELEGRAM_ALERTS_CHAT_ID`, per memory) — reuse, don't reinvent.--## What to build--### 1. Table (idempotent `ensureTable`, mirror `api/irl/pins.js:29`)--```sql-CREATE TABLE IF NOT EXISTS irl_interactions (- id UUID DEFAULT gen_random_uuid() PRIMARY KEY,- pin_id UUID NOT NULL,- agent_id UUID,- owner_user_id UUID, -- denormalized for fast inbox query- actor_device TEXT, -- anon device token of the passer-by- actor_user_id UUID, -- set when the actor was signed in- type TEXT NOT NULL, -- view | tap | pay | message- amount NUMERIC, -- atomic units when type='pay'- currency_mint TEXT, -- $THREE / USDC mint when type='pay'- payload JSONB DEFAULT '{}'::jsonb, -- message body, tx sig, geo, etc.- read_at TIMESTAMPTZ, -- NULL = unread- created_at TIMESTAMPTZ DEFAULT NOW()-);-CREATE INDEX IF NOT EXISTS irl_ix_owner ON irl_interactions (owner_user_id, created_at DESC);-CREATE INDEX IF NOT EXISTS irl_ix_pin ON irl_interactions (pin_id, created_at DESC);-CREATE INDEX IF NOT EXISTS irl_ix_unread ON irl_interactions (owner_user_id) WHERE read_at IS NULL;-```--### 2. `POST /api/irl/interactions` (log; public, rate-limited)--Called by the IRL client (B2/B3). Resolve `pin_id → owner_user_id, agent_id` from-`irl_pins` server-side (never trust the client for ownership). Validate `type ∈-{view,tap,pay,message}`. De-dupe spammy `view`s (one per device per pin per-~60 s) so the feed isn't flooded.--```js-const TYPES = new Set(['view','tap','pay','message']);-if (!TYPES.has(body.type)) return json(res, 400, { error:'invalid type' });-const [pin] = await sql`SELECT user_id, agent_id FROM irl_pins WHERE id=${body.pinId}`;-if (!pin) return json(res, 404, { error:'pin not found' });-const [row] = await sql`- INSERT INTO irl_interactions- (pin_id, agent_id, owner_user_id, actor_device, actor_user_id, type, amount, currency_mint, payload)- VALUES (${body.pinId}, ${pin.agent_id}, ${pin.user_id}, ${body.deviceToken ?? null},- ${actorUserId}, ${body.type}, ${body.amount ?? null}, ${body.currencyMint ?? null},- ${JSON.stringify(body.payload ?? {})}::jsonb)- RETURNING id, created_at`;-// fan-out notifications for high-signal events-if (body.type === 'pay' || body.type === 'message') {- await insertNotification(pin.user_id, 'irl_interaction', { pin_id: body.pinId, type: body.type, amount: body.amount });- // optional: Telegram alert via existing plumbing (skip silently if creds absent)-}-```--For `pay`, only log after the x402 settlement is verified (B3 passes the tx-signature in `payload.signature`) — never record an unpaid "pay".--### 3. `GET /api/irl/interactions?mine=1` (owner inbox; auth)--```js-const rows = await sql`- SELECT i.*, p.avatar_name, p.lat, p.lng- FROM irl_interactions i- JOIN irl_pins p ON p.id = i.pin_id- WHERE i.owner_user_id = ${session.id}- ORDER BY i.created_at DESC LIMIT 100`;-const [{ unread }] = await sql`- SELECT COUNT(*)::int AS unread FROM irl_interactions- WHERE owner_user_id = ${session.id} AND read_at IS NULL`;-return json(res, 200, { interactions: rows, unread });-```--Add a `PATCH /api/irl/interactions { ids:[…] }` (or `?markRead=1`) to set-`read_at = NOW()` for the owner's rows.--### 4. Dashboard inbox UI--An **Inbox** surface (full modal like `widgets.js:574`, or a dashboard tab) and-an unread badge on each C1 card + the page header (`Inbox •3`). Each row:--```-💸 Someone paid 0.05 USDC · "Greeter" @ Dolores Park · 2m ago [view tx ↗]-👆 Tapped your agent · "Greeter" @ Dolores Park · 5m ago-💬 "is this the meetup?" · "Greeter" @ Dolores Park · 8m ago [reply]-```--Group by type with icons; `pay` rows link to the Solana explorer via-`payload.signature`; `message` rows can reply (writes a `message` interaction back-or routes to chat). Mark rows read on open. Poll `interactions?mine=1` every-~20 s now; D1/D3 upgrade this to realtime push later.--### States (state-kit)--- Loading → `skeletonHTML(5, 'row')`.-- Empty → "No interactions yet — when someone taps or pays your agent IRL, it- shows up here." + "View in IRL" CTA.-- Error → `errorStateHTML` + `attachRetry`.--## Data / API changes--- New table `irl_interactions` (idempotent ensure on first hit).-- New: `POST /api/irl/interactions` (public, rate-limited), `GET- /api/irl/interactions?mine=1` (auth), `PATCH /api/irl/interactions` (auth, mark- read). Register all three routes in `vercel.json`.-- Reuses `insertNotification` + existing Telegram alert plumbing.--## Acceptance checklist--- [ ] `irl_interactions` created idempotently; indexes present.-- [ ] POST resolves owner/agent server-side, validates `type`, de-dupes `view`,- only logs verified `pay`s.-- [ ] GET inbox returns rows + `unread`; PATCH marks read.-- [ ] `pay`/`message` trigger `insertNotification`; Telegram optional + silent- when creds absent.-- [ ] Dashboard inbox renders feed, unread badges on cards + header, explorer- links, reply affordance; marks read on open.-- [ ] $THREE/USDC only in any logged `currency_mint`; loading/empty/error designed;- no console errors.--## Out of scope--Realtime push (D1/D3 replaces the 20 s poll) and the co-located ambient reaction-animation (D3). Here the loop is poll-based but complete.--## Verify--`npm run dev` → POST a synthetic `pay` interaction for an owned pin (mock req/res-or curl) → confirm a notification row, the inbox shows it with the explorer link,-unread badge increments, and opening clears it.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/C4-interaction-inbox-notifications.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/C5-remote-location-management.md b/tasks/irl-live/C5-remote-location-management.mddeleted file mode 100644index 71aa1d9f8..000000000--- a/tasks/irl-live/C5-remote-location-management.md+++ /dev/null@@ -1,158 +0,0 @@-# C5 — Remote location management (map + draggable relocate)--> Epic C · Size **M** · Opens from the C1 card "Location" link.-> Depends on C1. Extends `api/irl/pins.js` PATCH.--## Goal--Give the owner a real **map** (Leaflet + OpenStreetMap tiles, no API key) with a-draggable marker for each placed agent, so they can **relocate** a pin (new-lat/lng + heading) or **remove** it from anywhere on earth — not just standing at-the spot. Reverse-geocode the new position to a human label, exactly as the list-already does.--## Why it matters--The list view (C1) tells you *where* an agent is but not visually, and gives no-way to move it. Placement happens at a physical spot via the IRL camera; nudging-it 30 m to the better corner, or moving it to a new venue, currently means-deleting and re-walking there. A map turns the dashboard into true remote control.--## Current state (real lines)--- `irl-placements.js:40` `reverseGeocode(lat,lng)` already hits Nominatim and- extracts a city/town label — reuse verbatim.-- `irl-placements.js:91` grabs the viewer's own GPS for distance labels.-- `api/irl/pins.js:170` PATCH currently accepts **only `{ id, caption }`** and- updates owner-scoped rows (`WHERE id=… AND user_id=…`). **Heading/lat/lng are- not yet patchable** — this task adds them.-- DELETE already works owner/device-scoped (`api/irl/pins.js:185`).-- Pins carry `heading` (`pins.js:39`, default 0); the IRL viewer applies it as- `-(heading·π/180)` on the group (`src/irl.js:958`).--## What to build--### 1. Extend PATCH in `api/irl/pins.js`--Accept optional `lat`, `lng`, `heading` alongside `caption`. Validate ranges,-update only provided fields, keep the owner scope.--```js-if (req.method === 'PATCH') {- const session = await getSessionUser(req).catch(() => null);- if (!session) return json(res, 401, { error: 'not authenticated' });- const { id, caption, lat, lng, heading } = req.body ?? {};- if (!id) return json(res, 400, { error: 'id required' });-- const hasGeo = lat !== undefined || lng !== undefined;- if (hasGeo) {- const nLat = parseFloat(lat), nLng = parseFloat(lng);- if (!isFinite(nLat) || !isFinite(nLng) ||- nLat < -90 || nLat > 90 || nLng < -180 || nLng > 180)- return json(res, 400, { error: 'invalid coordinates' });- }- // COALESCE keeps existing values when a field is omitted- const [row] = await sql`- UPDATE irl_pins SET- caption = ${caption === undefined ? sql`caption` : (caption ?? null)},- lat = ${hasGeo ? parseFloat(lat) : sql`lat`},- lng = ${hasGeo ? parseFloat(lng) : sql`lng`},- heading = ${heading === undefined ? sql`heading` : (parseFloat(heading) || 0)}- WHERE id = ${id} AND user_id = ${session.id}- RETURNING id, lat, lng, heading, caption`;- if (!row) return json(res, 404, { error: 'not found' });- return json(res, 200, { pin: row });-}-```--> Note: Neon's tagged template can't nest `sql` fragments inside one statement-> the way shown — if that bites, branch the UPDATE per "geo vs caption-only" (as-> `api/skills/index.js:177` branches its query) rather than COALESCE-composing.--### 2. Map UI (Leaflet, lazy-loaded)--Lazy-import Leaflet from a CDN/ESM only when the Location panel opens (perf —-don't ship it to every dashboard view). OSM tiles, no key:--```js-const L = await import('https://esm.sh/[email protected]');-const map = L.map(node).setView([pin.lat, pin.lng], 16);-L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',- { attribution: '© OpenStreetMap', maxZoom: 19 }).addTo(map);-const marker = L.marker([pin.lat, pin.lng], { draggable: true }).addTo(map);-marker.on('dragend', () => {- const { lat, lng } = marker.getLatLng();- pendingMove = { lat, lng };- showSaveBar(lat, lng); // reverse-geocode → label, "Save / Cancel"-});-```--Show **all** of the owner's pins as markers (overview), but only the focused-pin's marker is draggable; clicking another marker focuses it. A heading control-(compass dial or 0–359 input) sets `heading`. A "Remove from map" button calls-the existing DELETE and drops the marker.--### 3. Save flow--`dragend` (or heading change) reveals a save bar with the reverse-geocoded new-label and Save/Cancel. Save → PATCH with `{ id, lat, lng, heading }`:--```js-const r = await fetch('/api/irl/pins', { method:'PATCH', credentials:'include',- headers:{ 'content-type':'application/json' },- body: JSON.stringify({ id: pin.id, ...pendingMove, heading }) });-```--On success, update the C1 card's location label + heading in place; on failure,-snap the marker back to its last saved position and show an inline error.--### States (state-kit)--- Tiles loading → skeleton over the map node; if Leaflet/CDN import fails →- `errorStateHTML` with Retry and a fallback "edit coordinates manually" form- (lat/lng number inputs) so the feature still works offline-of-CDN.-- No pins → empty state (shouldn't reach here from a C1 card, but guard it).--## Data / API changes--- `api/irl/pins.js` PATCH extended to accept `lat`, `lng`, `heading` (owner-scoped,- validated). No schema change — columns already exist.-- No new endpoint. DELETE reused as-is.--## Acceptance checklist--- [ ] PATCH accepts `lat/lng/heading`, validates ranges, owner-scoped, omitted- fields unchanged.-- [ ] Leaflet map lazy-loads with OSM tiles (no key); owner's pins shown; focused- marker draggable.-- [ ] Drag → reverse-geocoded label + Save/Cancel; Save persists; failure snaps- back with inline error.-- [ ] Heading control persists; Remove deletes via existing DELETE.-- [ ] CDN-import failure falls back to a manual lat/lng form; loading/error states- designed; no console errors; works at mobile width.--## Out of scope--Realtime propagation of the move to live viewers (D1 pushes the updated pin;-otherwise viewers pick it up on the next `loadNearbyPins` poll). Anchor-pose-precision (Epic A) is separate from coarse GPS relocation.--## Verify--`npm run dev` → open Location from a C1 card → drag the marker → Save → confirm a-PATCH with new coords, the card label updates, and reloading `/irl` near the new-spot shows the agent moved.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/C5-remote-location-management.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/C6-remote-outfit-change.md b/tasks/irl-live/C6-remote-outfit-change.mddeleted file mode 100644index 39982bf70..000000000--- a/tasks/irl-live/C6-remote-outfit-change.md+++ /dev/null@@ -1,158 +0,0 @@-# C6 — Remote outfit change (propagates to all viewers)--> Epic C · Size **L** · Opens from the C1 card "Outfit" link.-> Depends on C1; persists on `irl_pins`; ties to D1 (realtime) for instant-> propagation, with a poll fallback. Uses the wardrobe/accessories system.--## Goal--Let an owner change a **placed agent's outfit** from the dashboard and have the-new look render on the avatar for **every** viewer at that location — not just on-the owner's own device. Persist the chosen outfit/appearance on the pin so-`spawnNearbyPin` / `loadPinGLB` render the updated GLB on the next fetch (or-instantly via D1).--## Why it matters--A static avatar is a statue. Seasonal outfits, event branding ("staff" vests at a-meetup), or just keeping it fresh are what make a placed agent feel maintained and-alive. Because IRL is multiplayer (Epic D), an outfit change must be a property of-the *pin*, server-side — otherwise only the owner's phone sees it.--## Current state (real lines)--- Wardrobe is the source of truth for the layer taxonomy:- `src/avatar-wardrobe.js` — `WARDROBE_SLOTS` (skin/hair/outfit/glasses/…), each- with material/mesh match patterns. Slot state round-trips through- `appearance.colors` (per-slot tint) + `appearance.hidden` (hidden slots), and- survives the save → validate → server-bake → viewer path (header docstring).-- `src/agent-accessories.js` is the accessory layer applied on the live scene.-- The baker that turns appearance into a served GLB: `api/_lib/bake.js`- (referenced by the wardrobe docstring); validation `api/_lib/accessories.js`.-- The IRL viewer loads each pin from its **`avatar_url`**: `src/irl.js:992`- `loadPinGLB` does `new GLTFLoader().loadAsync(pin.avatar_url)`. Pins are fetched- by `loadNearbyPins` (`src/irl.js:901`) which already diffs add/remove. The pin- carries no appearance/outfit data today — only `avatar_url`.-- `irl_pins` (`api/irl/pins.js:32`) has `avatar_url`, `avatar_name` but **no- appearance/manifest column**.--## What to build--### 1. Persist appearance on the pin (schema extension)--Add an idempotent column so a pin owns its look independent of the source avatar:--```sql-ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS avatar_manifest JSONB; -- {colors, hidden, accessories}-ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS avatar_version INTEGER DEFAULT 0; -- bumped on each change (cache-bust + D1 diff)-```--Run it in `ensureTable()` (`api/irl/pins.js:29`) so it self-migrates. `avatar_url`-remains the renderable GLB; `avatar_manifest` is the editable appearance;-`avatar_version` lets the viewer detect a change cheaply.--### 2. Outfit editor panel (dashboard)--Reuse the wardrobe UI machinery rather than rebuild it. Load the agent's avatar-GLB into an offscreen/preview viewer, render the `WARDROBE_SLOTS` controls the-GLB actually exposes (same detection contract the studio uses), and let the owner-recolor/hide/swap the outfit + accessories. Output is the same `appearance` shape-the studio produces (`{ colors, hidden, accessories }`).--### 3. Save → re-bake → persist (`PATCH /api/irl/pins`)--On save, send the appearance manifest. The server bakes a new GLB (the existing-`api/_lib/bake.js` path that the avatar editor already uses), stores it (R2 /-first-party `/cdn/<key>` per the CDN-proxy convention), then updates the pin:--```js-// PATCH /api/irl/pins { id, avatar_manifest }-const baked = await bakeAppearance(pin.avatar_url, body.avatar_manifest); // -> { url }-const [row] = await sql`- UPDATE irl_pins- SET avatar_manifest = ${JSON.stringify(body.avatar_manifest)}::jsonb,- avatar_url = ${baked.url},- avatar_version = avatar_version + 1- WHERE id = ${id} AND user_id = ${session.id}- RETURNING id, avatar_url, avatar_version`;-```--Validate the manifest with `api/_lib/accessories.js` before baking (reject invented-slots). Reuse — do not fork — the existing avatar-bake pipeline; an IRL outfit-change is just a bake targeting the pin's GLB.--### 4. Propagation to all viewers--Two paths, both server-authoritative:--- **Poll (always works):** `loadNearbyPins` (`src/irl.js:901`) already diffs- incoming vs `nearbyPins`. Add `avatar_version` to the nearby GET payload and the- diff: when a known pin's `avatar_version` changed, treat it like a re-spawn —- dispose the old GLB group and call `loadPinGLB` with the new `avatar_url`- (which is now versioned, so the GLTFLoader/CDN won't serve a stale cache).-- **Realtime (D1):** when D1 lands, emit a `pin_updated { id, avatar_url,- avatar_version }` event on the geohash room so co-located viewers swap the GLB- within seconds without waiting for the next poll. Until D1 exists, the poll path- is the contract.--Owner's own dashboard preview updates immediately from the PATCH response.--### States (state-kit)--- GLB/preview loading → skeleton over the editor viewport.-- Bake in progress → real async "Applying outfit…" disabled save button (no fake- timers — await the bake).-- Bake/save failure → `errorStateHTML` + Retry; keep the previous look intact.-- Agent has no GLB / no exposed outfit slots → empty state explaining why.--## Data / API changes--- `irl_pins` gains `avatar_manifest JSONB` + `avatar_version INTEGER` (idempotent- in `ensureTable`).-- `PATCH /api/irl/pins` accepts `avatar_manifest`; bakes via existing- `api/_lib/bake.js`, stores the GLB, bumps `avatar_version`, returns new- `avatar_url`.-- Nearby GET (`api/irl/pins.js:107`) adds `avatar_version` to its SELECT so the- viewer can diff.-- `src/irl.js` `loadNearbyPins` diff updated to re-load a pin whose- `avatar_version` changed.--## Acceptance checklist--- [ ] `irl_pins` self-migrates `avatar_manifest` + `avatar_version`.-- [ ] Editor renders only the slots the GLB exposes; produces the studio- `appearance` shape; manifest validated before bake.-- [ ] Save bakes a real GLB via the existing pipeline, stores it, bumps version,- returns new `avatar_url`; dashboard preview updates from the response.-- [ ] Nearby GET returns `avatar_version`; `loadNearbyPins` swaps the GLB for any- viewer when version changes (poll path proven).-- [ ] D1 hook stubbed: a `pin_updated` emit point exists for when realtime lands.-- [ ] No fake loaders — bake is awaited; loading/error/empty designed; no console- errors.--## Out of scope--The realtime transport itself (D1 owns the WS/geohash rooms; this task only-defines the event payload + the poll fallback). Authoring new accessories assets-(that's the wardrobe/marketplace).--## Verify--`npm run dev` → open Outfit from a C1 card → recolor the outfit + save → confirm a-new baked `avatar_url`, `avatar_version` incremented, and the dashboard preview-updates. Then load `/irl` near the pin in a second browser and confirm the avatar-renders the new look after a `loadNearbyPins` cycle.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/C6-remote-outfit-change.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/D1-realtime-pin-sync.md b/tasks/irl-live/D1-realtime-pin-sync.mddeleted file mode 100644index 19be8d1c7..000000000--- a/tasks/irl-live/D1-realtime-pin-sync.md+++ /dev/null@@ -1,199 +0,0 @@-# D1 — Realtime pin sync (the core multiplayer task)--## Goal--Replace the one-shot/poll `loadNearbyPins()` fetch with **live** sync: when anyone-places, moves, or removes a pin near you, it appears / updates / disappears on-your screen within ~1s, no reload. This is the keystone of Epic D — D2 (presence)-and D3 (interaction broadcast) ride the same channel.--## Why it matters--Today the data layer is *already* multiplayer (`GET /api/irl/pins` returns every-user's nearby pins), but the client only learns about new pins on the next fetch.-A shared world that updates only on reload doesn't feel shared. Liveness is the-difference between "an AR toy" and "a place where things are happening."--## Current state (real lines)--- `src/irl.js:901` `loadNearbyPins()` — fetches `/api/irl/pins?lat&lng&radius`,- diffs against the in-memory `nearbyPins` array, removes vanished pins- (`scene.remove`, `labelEl.remove()` at :914) and spawns arrivals via- `spawnNearbyPin()` (:950). **This diff/reconcile logic is exactly what we keep**- — D1 just feeds it from a live stream instead of a poll.-- `src/irl.js:884` `commitPin()` → `savePin()` (:837) POSTs the pin; the placer- already knows its own pin id. Other viewers don't, until their next poll.-- `src/walk-net.js` — the existing Colyseus client wrapper: `connect()` with- jittered single reconnect (:239), `_setStatus()` surfacing- `idle|connecting|online|offline|failed|unavailable`, room message relay- (`onMessage('chat')` :212). **Mirror this class shape exactly.**-- `multiplayer/src/index.js:189` `gameServer.define('walk_world', WalkRoom).filterBy(['coin','tier'])`- — the matchmaking pattern we copy: a room instance per filter key.--## Recommended approach (honest)--**Reuse the existing Colyseus host (`wss://three-ws-multiplayer.fly.dev`), add a-new `irl_world` room keyed by geohash, AND keep poll-delta as a real fallback.**--- The walk server is a long-lived Colyseus process — Vercel can't host WS, so we- do **not** add a new worker; we add one more `Room` class to the deployed host.-- A new room (not WalkRoom) because IRL has no avatars-walking schema; its state- is the *set of pins in this geocell* plus *live viewers* (D2). Define it with- `gameServer.define('irl_world', IrlRoom).filterBy(['geocell'])` so every viewer- inside one coarse geohash lands in the same room instance.-- **Geohash room key:** geohash precision 6 (~1.2km × 0.6km cell). The client- subscribes to its own cell **plus the up-to-8 neighbor cells** (standard- geohash neighbor expansion) so pins straddling a cell edge inside- `NEARBY_RADIUS` (150m) are never missed. One Colyseus connection, N filterBy- joins is heavy — instead the room is keyed on the **center** cell and the- server fans pins from neighbor cells into it (room holds a 3×3 cell window).-- **Poll fallback is not optional.** When the WS is `unavailable`/`failed`- (production with no `irl-server` meta, offline, corporate WiFi blocking WS),- fall back to the existing `loadNearbyPins()` on a 10s interval. The reconcile- code is identical, so the rest of the app never knows which transport fed it.--## What to build--### 1. `src/irl-net.js` — IRL realtime client (mirror `walk-net.js`)--```js-import { Client, getStateCallbacks } from 'colyseus.js';-import { IrlState } from '../multiplayer/src/irl-schemas.js';-import { encodeGeohash } from './shared/geohash.js'; // precision-6, new tiny util--const ROOM = 'irl_world';--export class IrlNet {- constructor({ lat, lng, deviceToken, agent, getServerUrl } = {}) {- this.geocell = encodeGeohash(lat, lng, 6);- this.status = 'idle'; // idle|connecting|online|offline|failed|unavailable- this._handlers = { status: new Set(), 'pin:add': new Set(),- 'pin:update': new Set(), 'pin:remove': new Set(),- presence: new Set() }; // presence → D2- // …same on()/_emit()/_setStatus()/_scheduleReconnect() shape as WalkNet- }- async connect() { /* joinOrCreate(ROOM, { geocell, deviceToken, agent, lat, lng }, IrlState) */ }- // Re-join a new cell when the viewer physically walks into a new geohash:- async moveTo(lat, lng) {- const cell = encodeGeohash(lat, lng, 6);- if (cell === this.geocell) return;- this.geocell = cell; await this.connect(); // leave old room, join new- }-}-```--### 2. Server: `multiplayer/src/rooms/IrlRoom.js` + `irl-schemas.js`--- `IrlState` = `MapSchema<Pin>` (pin id → `{ id, lat, lng, heading, avatarUrl,- avatarName, caption, x402Endpoint, agentId, ownerToken, placedAt }`) +- `MapSchema<Viewer>` for D2. Append-only fields like `schemas.js` warns.-- `onCreate({ geocell })`: load the cell's current live pins from Neon- (`SELECT … WHERE geocell IN (this + 8 neighbors) AND not expired`) into state.-- The room is the **broadcast hub, not the source of truth** — Neon stays- authoritative (pins survive server restarts / Vercel POSTs). On a Vercel- `POST /api/irl/pins`, the API publishes a `pin:add` to the room (see Data-API).-- `onMessage('pin:moved' | 'pin:removed', …)` validate ownerToken, persist, then- schema-patch removes/updates the MapSchema entry → Colyseus delta-broadcasts.--### 3. Wire into `src/irl.js`--```js-// Replace the poll with a stream; keep loadNearbyPins() as the fallback path.-function startPinSync() {- if (irlNet) irlNet.destroy();- irlNet = new IrlNet({ lat: gpsState.lat, lng: gpsState.lng,- deviceToken: _deviceToken, agent: _currentAgentId });- irlNet.on('pin:add', p => reconcilePin('add', p));- irlNet.on('pin:update', p => reconcilePin('update', p));- irlNet.on('pin:remove', p => reconcilePin('remove', p));- irlNet.on('status', ({ status }) => {- setNetPill(status); // state-kit pill: connecting/live/offline- if (status === 'unavailable' || status === 'failed') startPollFallback();- else stopPollFallback();- });- irlNet.connect();-}-function reconcilePin(kind, p) {- if (gpsPin?.id && p.id === gpsPin.id) return; // never spawn my own pin twice- const existing = nearbyPins.find(n => n.id === p.id);- if (kind === 'remove') { /* scene.remove + labelEl.remove, splice */ return; }- if (existing) { /* update caption/heading/avatar; re-spawn GLB if changed */ return; }- const entry = { ...normalize(p), group: null, labelEl: null, glbLoaded: false };- nearbyPins.push(entry); spawnNearbyPin(entry); updateNearbyBadge();-}-```--- `normalize(p)` maps wire camelCase (`avatarUrl`) → the snake_case- (`avatar_url`) the rest of `irl.js` already reads, so `spawnNearbyPin`,- `openPinSheet`, and the radar are untouched.-- On GPS movement crossing a geocell boundary, call `irlNet.moveTo(lat, lng)`.--## Message shapes (wire contract)--| Direction | Type | Payload |-|---|---|---|-| server→client | `pin:add` | `{ id, lat, lng, heading, avatarUrl, avatarName, caption, x402Endpoint, agentId, placedAt }` |-| server→client | `pin:update` | same shape (caption/heading/avatar/location changed) |-| server→client | `pin:remove` | `{ id }` |-| client→server | `pin:moved` | `{ id, lat, lng, heading, ownerToken }` (relocate, D-side of C5) |-| client→server | `pin:removed` | `{ id, ownerToken }` |--Adds/updates/removes are delivered as **Colyseus schema deltas** off the pin-`MapSchema`, not bespoke `broadcast()` calls — so a late joiner gets the full-current set on join for free, exactly like walk players sync on connect.--## Data / API changes--- `irl_pins`: add `geocell TEXT` (generated precision-6 geohash, indexed) so the- room and the nearby query both filter by cell. Backfill on migration.-- `POST /api/irl/pins` (`api/irl/pins.js:130`): after insert, fire-and-forget a- publish to the room so other viewers see it immediately. Since Vercel can't- hold the WS, POST to a small server ingress: `POST {irlServer}/publish` with- `{ geocell, type:'pin:add', pin }`, authed by a shared `IRL_PUBLISH_SECRET`.- Same for DELETE → `pin:remove`, PATCH → `pin:update`.-- New `multiplayer` route `POST /publish` (HTTP, not WS) that validates the- secret and `room.broadcast`-equivalents into the matching geocell room.--## Connecting / reconnecting / offline states (state-kit)--- A net pill (reuse the walk HUD pattern): `connecting` (pulsing), `live` (green- dot + "Live"), `offline` ("Polling" — fallback active, still functional),- `unavailable` (silent; poll path). Never show a dead "reconnecting…" forever —- after the single jittered retry, drop to poll and say "Polling".--## Acceptance checklist--- [ ] Two phones at the same spot: A places a pin, it appears on B within ~1s, no reload.-- [ ] A removes/relocates a pin → disappears/moves on B live.-- [ ] Walking across a geocell boundary re-joins the new room; pins stay correct.-- [ ] WS blocked (DevTools offline / kill server) → falls back to 10s poll, pill says "Polling", still works.-- [ ] Late joiner gets the full current pin set on join (schema sync), not just future deltas.-- [ ] My own pin is never double-spawned (`gpsPin.id` guard holds).-- [ ] No console errors; reconnect does not storm.--## Out of scope--- Presence counts / ghost viewers → **D2**. Interaction reactions → **D3**.- Moderation / caps → **D4**. Cross-user anchor *accuracy* → A3. D1 only makes- the pin set live.--## Verify--`npm run dev:walk-all` (Vite + Colyseus), open two browser profiles on-`/irl` at the same mocked GPS, place/remove pins, watch them sync. Then kill the-Colyseus process and confirm the poll fallback engages and the pill flips to-"Polling".--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/D1-realtime-pin-sync.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/D2-live-viewer-presence.md b/tasks/irl-live/D2-live-viewer-presence.mddeleted file mode 100644index f6b673e1d..000000000--- a/tasks/irl-live/D2-live-viewer-presence.md+++ /dev/null@@ -1,151 +0,0 @@-# D2 — Live viewer presence--## Goal--Show how many people are **currently viewing** a location, and optionally render-ghost markers/avatars of other live viewers nearby — so the IRL world feels-inhabited even when few pins are placed. Presence joins/leaves/heartbeats ride-the **same** geocell channel D1 opened. Privacy-aware: coarse location only,-opt-out by default-safe design.--## Why it matters--A pin is a static artifact; a *person also looking at this spot right now* is-social proof and a reason to stick around. "7 viewing nearby" turns a lonely AR-screen into a moment. It also primes D3 — once you can see co-located viewers,-you can show them ambient reactions to interactions.--## Why this is cheap (depends on D1)--D1 already establishes one Colyseus room per geocell with a viewer `MapSchema`-stub. Presence is just *populating and rendering that map* — no new transport,-no new worker. Colyseus already tracks join/leave (`onJoin`/`onLeave` in the-room) and delta-broadcasts schema changes, so "who is here" is free plumbing.--## Current state (real lines)--- `src/irl-net.js` (from D1) already joins `irl_world` with `{ geocell,- deviceToken, agent, lat, lng }` and has a `presence` handler bucket.-- `multiplayer/src/rooms/IrlRoom.js` (from D1) holds `MapSchema<Viewer>`.-- Walk presence precedent: `multiplayer/src/schemas.js` `Player` carries- `x/y/z/yaw` and the client renders peers — we render a far simpler ghost (a- dot + count), not a full avatar, unless the viewer opted to share an avatar.-- `src/walk-net.js:199` `$players.onAdd/onRemove` is the exact callback shape we- reuse for the viewer map.--## What to build--### 1. Viewer schema + heartbeat (server, `IrlRoom.js`)--```js-class Viewer extends Schema { // append-only, like Player- constructor() { super();- this.id = ''; // ephemeral session id (NOT the device token)- this.glat = 0; this.glng = 0; // COARSE: snapped to geocell-6 center + jitter- this.heading = 0; // optional compass facing, for ghost orientation- this.avatar = ''; // '' unless the viewer opted to share their avatar- this.ghost = false; // false = counted only, true = render a marker- this.tsServer = 0;- }-}-```--- `onJoin(client, { lat, lng, ghost, avatar })`: add a `Viewer`. **Server snaps- `lat/lng` to the geocell center and adds bounded jitter** — never store or- broadcast a viewer's precise GPS. `ghost` defaults `false` (count-only).-- `onMessage('heartbeat', { heading })`: refresh `tsServer`, update heading.-- A 30s reaper drops viewers whose last heartbeat is stale (covers silent- disconnects / backgrounded mobile tabs that never fire `onLeave`).-- `onLeave`: remove the viewer → delta-broadcast.--### 2. Client (`src/irl-net.js` + `src/irl.js`)--```js-// irl-net.js — surface viewer add/remove + a derived count-irlNet.on('presence', ({ count, viewers }) => updatePresence(count, viewers));-setInterval(() => irlNet.heartbeat(cameraYaw), 15000); // 15s heartbeat--// irl.js — HUD chip + optional ghost markers-function updatePresence(count, viewers) {- presenceChip.hidden = count <= 1; // don't count "1" = just me- presenceChip.textContent = `${count} viewing nearby`;- if (!shareGhost) return; // opt-in to SEEING is always on;- for (const v of viewers) renderGhost(v); // opt-in to BEING SEEN gates send-}-```--- **Ghost marker**: a translucent billboard dot at the viewer's coarse position- on the radar (`updateRadar()` at `irl.js:1230` — add a `.irl-radar-ghost`- class) and, when `ghost:true`, a faint avatar/orb in the 3D scene. Ghosts are- visually distinct from pins (lower opacity, no name, no tap target) so they're- never mistaken for a placed agent.-- **Privacy default:** you always *see* the count. You only *broadcast yourself- as a ghost* if you opt in via a toggle ("Appear to others nearby"), stored in- `localStorage('irl_share_ghost')`, default **off**. Count-only presence uses- geocell-center coords, so even non-opted viewers reveal nothing beyond "someone- in this ~1km cell."--### 3. Presence chip + toggle UI (`pages/irl.html`)--- A small chip near the nearby badge: a pulsing dot + "N viewing nearby".-- A settings toggle in the existing controls row for "Appear to others nearby".--## Message shapes--| Direction | Type | Payload |-|---|---|---|-| client→server | join opts | `{ geocell, lat, lng, ghost, avatar }` (ghost/avatar only if opted-in) |-| client→server | `heartbeat` | `{ heading }` |-| server→client | `presence` (derived from Viewer MapSchema delta) | `{ count, viewers:[{ id, glat, glng, heading, avatar, ghost }] }` |--Presence rides the Colyseus `Viewer` MapSchema (delta-encoded), so a fresh-joiner sees the current crowd immediately and the wire cost is tiny.--## Data / API changes--- **None in Neon.** Presence is ephemeral and lives only in room memory — viewers- are not pins and must never be persisted. (Storing live location is exactly the- privacy risk we're avoiding.)--## Connecting / reconnecting / offline states (state-kit)--- Presence chip hidden while `connecting` and whenever the D1 transport is in- poll-fallback (no WS = no live presence; never fake a count from the REST poll).-- On `offline`/`unavailable`: hide the chip and any ghosts cleanly (don't leave- stale ghosts frozen on screen). Restore on reconnect.--## Acceptance checklist--- [ ] Two devices at the same geocell: each sees "2 viewing nearby".-- [ ] Third leaves/backgrounds → count drops within the 30s reaper window.-- [ ] Ghost toggle **off** by default; no viewer marker broadcast until opted in.-- [ ] Ghosts render distinct from pins (faint, no name, not tappable) on radar + scene.-- [ ] No precise GPS of any viewer ever leaves the client (coarse/jittered only).-- [ ] Chip hidden in poll-fallback and while connecting; restored on reconnect.-- [ ] No console errors; heartbeat does not flood (15s cadence).--## Out of scope--- Reactions to interactions → **D3**. Pin add/remove sync → **D1**. Full avatar- walk simulation (that's `/walk`, not IRL). Account-level "friends nearby" — D2- is anonymous-by-default presence only.--## Verify--`npm run dev:walk-all`, open `/irl` on two profiles at the same mocked GPS,-confirm the count, toggle ghost on/off on one and confirm the marker-appears/disappears on the other, then close one tab and watch the reaper drop it.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/D2-live-viewer-presence.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/D3-interaction-broadcast.md b/tasks/irl-live/D3-interaction-broadcast.mddeleted file mode 100644index e5f1f6ed0..000000000--- a/tasks/irl-live/D3-interaction-broadcast.md+++ /dev/null@@ -1,184 +0,0 @@-# D3 — Interaction broadcast--## Goal--When user **A** interacts with an IRL agent (tap / view profile / x402 pay /-message), broadcast it two ways:-1. **To the owner** — a realtime event lands in their inbox (pairs with C4),- even though they may be on the other side of the world.-2. **To co-located viewers** — an *ambient reaction*: the agent emotes and a- floating reaction (e.g. a 💜 burst, a "paid!" sparkle) plays for everyone- currently viewing that geocell, so a busy agent visibly feels alive.--Define the flow `A → server → owner` and `A → server → nearby viewers`, on the-same channel D1/D2 opened.--## Why it matters--An interaction that only A sees is a dead end. Broadcasting it makes the agent a-*social object*: the owner gets the dopamine of "someone engaged with my agent-right now," and bystanders see activity that pulls them in. This is the feedback-loop that makes placing an agent worthwhile.--## Current state (real lines)--- `src/irl.js:1135` `openPinSheet()` — the tap card. Already wires View- (`:1157`, opens `/agents/:id`) and Pay (`:1169`, real x402 via- `withX402(window.ethereum, { maxPaymentUsd: 1.00 })` at `:1204`). These are the- three interaction moments to instrument: **open**, **view**, **pay**.-- `src/irl-net.js` (D1) — the live channel; add an `interaction` emitter + handler.-- `multiplayer/src/rooms/IrlRoom.js` (D1) — already holds pins + viewers; add an- `onMessage('interaction', …)` and an ambient reaction broadcast.-- C4 (`tasks/irl-live` sibling Epic C) defines the `irl_interactions` table + the- owner inbox. **D3 is the realtime delivery layer for C4** — it does not invent- the table; it writes to it and pushes a live event.-- B3 (`B3-real-interactions-profile-pay.md`) owns the *client-side* profile/pay- wiring; D3 is the broadcast that fires *after* those succeed.--## What to build--### 1. Emit on interaction (client, `src/irl.js`)--```js-// In openPinSheet(): the agent was tapped/opened.-irlNet?.interaction({ type: 'open', pinId: pin.id, agentId: pin.agent_id });--// In the View handler (irl.js:1157): profile opened.-irlNet?.interaction({ type: 'view', pinId, agentId });--// In the Pay handler, ONLY after r.ok (irl.js:1207): real settled payment.-irlNet?.interaction({ type: 'pay', pinId, agentId, usd: paidUsd });-```--- Never emit `pay` optimistically — only after the x402 response is `ok` (a real- on-chain settlement), so the owner's "earned" event is never a lie.-- `pay` carries no wallet address client-side; the server derives/records what it- needs. Actor identity to the owner is the ephemeral session + optional handle,- never raw GPS.--### 2. Route on the server (`IrlRoom.js`)--```js-this.onMessage('interaction', async (client, { type, pinId, agentId, usd }) => {- if (!['open','view','pay','message'].includes(type)) return;- if (!this._interactionOk(client.sessionId)) return; // rate-limit (see D4)- const pin = this.state.pins.get(pinId);- if (!pin) return;-- // (1) Persist + notify owner — write to irl_interactions (C4 schema) via the- // Vercel ingress, which also fans to the owner's live inbox channel.- await ingest({ type, pinId, agentId, ownerToken: pin.ownerToken,- usd, actor: client.sessionId });-- // (2) Ambient reaction to everyone viewing THIS geocell.- this.broadcast('reaction', { pinId, type, ts: Date.now() }, { afterNextPatch: false });-});-```--- `open`/`view` are common — debounce per (session, pin) so a jittery tap can't- spam owner notifications or reaction bursts (e.g. max 1 `open` per pin per 5s).-- `pay` and `message` are rare/high-signal — always delivered, never debounced.--### 3. Ambient reaction render (client, `src/irl.js`)--```js-irlNet.on('reaction', ({ pinId, type }) => {- const pin = nearbyPins.find(p => p.id === pinId);- if (!pin?.group) return;- playEmote(pin, type); // agent waves (open) / bows (pay) on the GLB- spawnFloatingReaction(pin, type); // 💜 for open/view, ✨"paid" for pay — CSS rise+fade-});-```--- `playEmote(pin, type)` triggers a quick animation on the loaded GLB if it has a- matching clip, else a soft scale/bounce on the group — always *something*, never- a no-op. Reuse the walk emote pattern (`schemas.js` `emote`/`emoteTs`).-- `spawnFloatingReaction` is a billboard projected like the name labels- (`updateLabels()` `irl.js:1254`): rise 40px, fade over 1.2s, `transform`/- `opacity` only (no layout), `will-change` set, auto-removed.-- Co-located viewers see the *placer's* interaction, not their own only — that's- the point: the agent looks busy because real people are engaging it.--### 4. Owner live delivery (`A → server → owner`)--- The owner is almost never in the same geocell room, so we can't reach them via- the geocell broadcast. The Vercel `ingest` (above) writes `irl_interactions`- (C4) and pushes to an **owner channel**: either a per-owner Colyseus room the- dashboard subscribes to, or a server-sent stream the C4 inbox already opens.- D3 fires the event; C4 owns the inbox UI and the unread/notification surface.--## Event flow summary--```-A taps/pays pin P (owned by O, in geocell G)- │ irlNet.interaction({type,pinId,agentId,usd})- ▼-IrlRoom(G).onMessage('interaction')- ├─ ingest() → POST {vercel}/api/irl/interactions → INSERT irl_interactions (C4)- │ → push to O's inbox channel (C4)- └─ broadcast('reaction') → every viewer in G sees the agent emote + 💜/✨-```--## Message shapes--| Direction | Type | Payload |-|---|---|---|-| client→server | `interaction` | `{ type:'open'|'view'|'pay'|'message', pinId, agentId, usd? }` |-| server→client (geocell) | `reaction` | `{ pinId, type, ts }` |-| server→owner-channel | `interaction` (C4) | `{ pinId, agentId, type, usd?, actor, ts }` |--## Data / API changes--- Writes go to **`irl_interactions`** (defined by C4) — D3 does not redefine it.- Columns it relies on: `pin_id, agent_id, owner_token/owner_user_id, type, usd,- actor_session, created_at`.-- New `POST /api/irl/interactions` ingress (or reuse C4's): validates the room's- shared secret, inserts the row, returns fast. Vercel can't hold the owner WS,- so the live-to-owner push is the Colyseus host's job, triggered by the ingress.--## Connecting / reconnecting / offline states (state-kit)--- If A is in poll-fallback (no WS): the interaction still **records** via the- normal REST path (pay already hits x402; open/view POST to- `/api/irl/interactions` directly) so the owner's inbox is never lossy — only the- *ambient reaction* is skipped (no live channel to broadcast on). Degrade the- flourish, never the record.-- Reaction rendering guards on `pin.group` existing; a reaction for a pin that- scrolled out of range is silently dropped.--## Acceptance checklist--- [ ] A pays pin P (real x402 ok) → owner's C4 inbox gets a live `pay` event with the USD amount.-- [ ] A co-located viewer B sees pin P's agent emote + a "paid" reaction within ~1s.-- [ ] `open`/`view` debounced (no notification/reaction spam from rapid taps).-- [ ] `pay`/`message` never debounced or dropped.-- [ ] No raw GPS or wallet address of A reaches the owner or other viewers.-- [ ] Poll-fallback: interaction still recorded for the owner; only the ambient flourish is skipped.-- [ ] Reactions are pure transform/opacity, auto-cleaned, no layout jank.-- [ ] No console errors.--## Out of scope--- The inbox UI, unread counts, notification permissions → **C4**. The pay/profile- wiring itself → **B3**. Presence counts → **D2**. Abuse caps/rate-limit policy- details → **D4** (D3 just calls the limiter).--## Verify--`npm run dev:walk-all`, two `/irl` profiles at one geocell + the C4 dashboard open-on a third: tap and (devnet/testnet) pay from A, confirm B sees the emote+reaction-and the dashboard inbox lights up live.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/D3-interaction-broadcast.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/D4-moderation-safety-caps.md b/tasks/irl-live/D4-moderation-safety-caps.mddeleted file mode 100644index fc2f65042..000000000--- a/tasks/irl-live/D4-moderation-safety-caps.md+++ /dev/null@@ -1,192 +0,0 @@-# D4 — Moderation, safety & density caps--## Goal--Public placement needs guardrails. Build: content checks on caption + avatar name-at POST time, a report flow (report a pin → hide/queue), per-area **density caps**-(max pins per small geocell), per-user/device pin caps + rate limits, and-expiry/cleanup. Keep everything $THREE-only and brand-safe.--## Why it matters--The moment "anyone at a location sees anyone's placed agent" ships (D1), the-abuse surface opens: slurs in captions, impersonation, ad spam, a single actor-carpet-bombing a plaza with 500 pins, a pin pointing at a malicious x402-endpoint. Without caps and moderation, the shared world becomes a liability the-first day it's public. This is the task that makes D1–D3 safe to launch.--## Honest abuse vectors (design against each)--1. **Hate / harassment in caption or avatar name** — public, on third-party- embeds. → content filter at POST.-2. **Density flooding** — one actor places hundreds of pins to dominate a spot or- grief a venue. → per-geocell cap + per-device cap.-3. **Rate spam** — scripted rapid POSTs. → token-bucket rate limit per device/IP.-4. **Malicious x402 endpoint** — a pin whose "pay" points at a scam/non-$THREE or- off-platform drain. → endpoint allow-list + $THREE-only guard.-5. **Impersonation** — avatar named like an official entity. → name checks +- report flow.-6. **Stale/ghost pins** — anonymous pins never cleaned up. → expiry + reaper.-7. **Report abuse** — mass false reports to hide a legit pin. → threshold +- owner-protected, queue not instant-delete.--## Current state (real lines)--- `api/irl/pins.js:130` `POST` — inserts caption / avatarName / x402Endpoint with- **no content check, no caps, no rate limit** today. This is the chokepoint to- harden.-- `api/irl/pins.js:145` anonymous pins already get a 7-day `expires_at`; the- nearby query (`:113`) and `/mine` (`:72`) already filter `expires_at > NOW()`.- Expiry exists — we add a **reaper** so dead rows don't accumulate forever.-- `src/profanity.js` `WORD_BLACKLIST` — lower-case substring slur/severe list,- already used by `src/widgets/pumpfun-feed.js`. **Reuse it server-side** for- captions + names.-- `api/_lib/granite-guardian.js` `assess(cfg, { input, risks })` + `decide()` +- `FLAG_THRESHOLD` — the existing AI content-risk layer (`social_bias`, `harm`,- etc.). Use it as a second tier above the wordlist for borderline captions.-- `api/_lib/auth.js` `getSessionUser` — to attribute caps to a user when signed- in; `device_token` covers anonymous.--## What to build--### 1. Content check at POST (`api/irl/pins.js`)--```js-import { WORD_BLACKLIST } from '../../src/profanity.js'; // shared list-import { guardianConfig, assess, decide } from '../_lib/granite-guardian.js';--function hardBlocked(text) {- const t = String(text || '').toLowerCase();- return WORD_BLACKLIST.some(w => t.includes(w));-}-// In POST, before INSERT:-if (hardBlocked(body.caption) || hardBlocked(body.avatarName)) {- return json(res, 422, { error: 'content', field: 'caption',- message: 'That text isn’t allowed on a public pin.' });-}-// Tier 2 — borderline text → Granite Guardian (skip if not configured)-const cfg = guardianConfig();-if (cfg && body.caption) {- const verdict = decide(await assess(cfg, { input: body.caption }));- if (verdict.flagged) return json(res, 422, { error: 'content', … });-}-```--- Wordlist is the always-on hard gate (no external dependency, fails closed and- fast). Guardian is the smart tier — **skip gracefully if unconfigured** so POST- never 500s on a missing key (Rule 9). Caption/name length clamp too- (caption ≤ 140, name ≤ 40).--### 2. x402 endpoint + $THREE safety--- Validate `x402Endpoint`: must be `https:`, must resolve to a three.ws /- allow-listed payment host (or the agent's own registered endpoint), reject- arbitrary external URLs. Never let a pin advertise a non-$THREE token anywhere- in caption/name — the wordlist gains a small **off-brand-coin guard** (reject- captions naming a competing token; $THREE is the only coin).--### 3. Density + per-user caps (`api/irl/pins.js` POST)--```js-// Per fine geocell (precision-7, ~150m) density cap.-const cellPins = await sql`- SELECT count(*)::int AS n FROM irl_pins- WHERE geocell7 = ${cell7} AND (expires_at IS NULL OR expires_at > NOW())`;-if (cellPins[0].n >= MAX_PINS_PER_CELL /* e.g. 40 */)- return json(res, 429, { error: 'area_full',- message: 'This area already has the maximum number of agents.' });--// Per device/user active-pin cap.-const ownerKey = session?.id ?? body.deviceToken;-const owned = await sql`SELECT count(*)::int AS n FROM irl_pins- WHERE (user_id = ${session?.id ?? null} OR device_token = ${body.deviceToken ?? ''})- AND (expires_at IS NULL OR expires_at > NOW())`;-if (owned[0].n >= MAX_PINS_PER_OWNER /* e.g. 20 anon, higher when signed in */)- return json(res, 429, { error: 'pin_limit', message: 'You’ve reached your active pin limit.' });-```--### 4. Rate limit (token bucket)--- Per device_token + IP: e.g. **5 POSTs / minute, 30 / hour**. Reuse the existing- rate-limit store (the Redis `three-ratelimit` limiter referenced across the- API). Return `429 { error:'rate', retryAfter }`. Fail-open-but-logged if the- limiter store is down (don't block legit placement on an infra hiccup, but- alert).--### 5. Report flow--- New `POST /api/irl/report { pinId, reason, deviceToken }` → insert into a new- `irl_pin_reports` table `(id, pin_id, reporter_token, reason, created_at)`.-- When a pin crosses `REPORT_HIDE_THRESHOLD` distinct reporters (e.g. 3), set- `irl_pins.hidden_at = NOW()`; the nearby query (`api/irl/pins.js:113`) adds- `AND hidden_at IS NULL` so hidden pins vanish for everyone **and** D1 emits a- `pin:remove`. Hidden, not deleted — queued for review, owner can appeal.-- Owner-placed pins still need ≥ threshold *distinct* reporters; a single actor- can't hide a pin. Reporter token dedup prevents report-bombing inflation.-- UI: a "Report" affordance in `openPinSheet()` (`irl.js:1135`) → reason sheet →- POST → toast "Thanks, we'll review it." (state-kit success/error states).--### 6. Expiry & cleanup reaper--- A cron (Vercel cron or the multiplayer host) deletes rows where- `expires_at < NOW() - INTERVAL '1 day'` and purges resolved reports. Keeps the- table and every geocell room lean. Signed-in permanent pins (`expires_at IS- NULL`) are never reaped.--## Data / API changes--- `irl_pins`: add `geocell7 TEXT` (indexed, for density), `hidden_at TIMESTAMPTZ`.- Nearby + mine queries gain `AND hidden_at IS NULL`.-- New table `irl_pin_reports (id, pin_id, reporter_token, reason, created_at)`- with a unique `(pin_id, reporter_token)` to dedup.-- New `POST /api/irl/report`; route in `vercel.json`.-- `POST /api/irl/pins` gains content check → cap check → rate check, in that- order (cheapest/most-decisive first), each with a designed error code.--## Connecting / reconnecting / offline states (state-kit)--- POST rejections (`content`/`area_full`/`pin_limit`/`rate`) surface as designed,- actionable messages in the caption panel / status line (`setStatus(..., {- error:true })`) — never a silent failure or a raw 4xx. Each tells the user- exactly what to do (shorten text, move, wait, remove an old pin).-- Report sheet has loading / success / error states; a failed report is- retryable, never a dead button.--## Acceptance checklist--- [ ] Caption/name containing a blacklisted term → `422`, designed message, no row inserted.-- [ ] Borderline caption flagged by Guardian when configured; POST still works (no 500) when it isn't.-- [ ] 41st pin in a precision-7 cell → `429 area_full`.-- [ ] Anonymous device past its active-pin cap → `429 pin_limit`.-- [ ] >5 POSTs/min from one device → `429 rate` with `retryAfter`.-- [ ] x402 endpoint outside the allow-list rejected; no non-$THREE token nameable in caption.-- [ ] 3 distinct reporters hide a pin (it vanishes for all viewers + D1 `pin:remove`); a single reporter cannot.-- [ ] Reaper purges expired anon pins; permanent signed-in pins untouched.-- [ ] No console errors; limiter-down degrades gracefully and logs.--## Out of scope--- The realtime transport itself → **D1**. Presence/ghosts → **D2**. Owner inbox →- **C4**. Full human-review console for the report queue (this task only hides at- threshold + queues; a moderator dashboard is a later epic).--## Verify--Hit `POST /api/irl/pins` with a blacklisted caption (422), spam to trip the rate-limit (429), fill a test geocell past the density cap (429), then file 3 reports-from 3 device tokens against one pin and confirm it disappears from-`GET /api/irl/pins` and D1 emits `pin:remove`.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/D4-moderation-safety-caps.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/E1-permissions-onboarding.md b/tasks/irl-live/E1-permissions-onboarding.mddeleted file mode 100644index ec58277a6..000000000--- a/tasks/irl-live/E1-permissions-onboarding.md+++ /dev/null@@ -1,156 +0,0 @@-# E1 — Permissions & onboarding (camera · motion · location)--## Goal--A first-run permission + onboarding flow for the three sensors IRL depends on —-**camera** (`getUserMedia`), **motion/orientation** (`DeviceOrientationEvent`),-and **location** (`navigator.geolocation`) — where every permission has a fully-*designed* state: prompt, granted, denied-with-recovery, and unsupported. Never a-blank screen, never a dead end. The iOS Safari motion gesture is handled explicitly.--## Why it matters--IRL is a phone-camera product. Today the camera path lives in `enableAR()`-(`src/irl.js:190`) and the motion gesture is buried inside `setLocked()`-(`src/irl.js:682`). A user who denies the camera prompt sees a 3-second toast-(`setStatus(... { error:true })`) and is then stranded — no explanation of *why*-we asked, no path to recover. iOS users who never tap **Pin** never get the-motion prompt at all, so world-lock silently does nothing. A first-run flow that-explains the value, requests each permission from a real gesture, and routes-every denial to a recovery card is the difference between "broken" and "best in class".--## Current state (real lines)--- **Camera** — `enableAR()` `src/irl.js:190`. Already handles `NotAllowedError`- vs other errors (`:202`) and the missing-API case (`:191`, `:277`), but only as- a transient `setStatus()` toast — no designed recovery surface.-- **Motion** — `setLocked()` `src/irl.js:684` calls- `DeviceOrientationEvent.requestPermission()` from the Pin tap (a real gesture),- but a `denied` result just toasts "Motion sensor access denied" (`:688`) and- returns. Listeners are attached at `:670`/`:674`.-- **Location** — `initGPS()` `src/irl.js:823` calls `watchPosition` with an empty- error callback (`:827`) — a denied GPS prompt is **swallowed**. `revealMyPinsBtn`- / nearby-pin loading only fire on first fix (`:799`).-- No onboarding/intro surface exists; `pages/irl.html` boots straight into the scene.-- `state-kit.js` exports `emptyStateHTML` / `errorStateHTML` / `ensureStateKitStyles`- — the just-shipped error-boundary bar. Use them here.--## What to build--A self-contained `src/irl/onboarding.js` module + a permission state machine.-Render into a new full-screen overlay `#irl-onboard` (added to `pages/irl.html`,-above the scene `z-index`). Drive it from `state-kit` shells so copy + visuals-match the platform.--```js-// src/irl/onboarding.js-import { emptyStateHTML, errorStateHTML, ensureStateKitStyles } from '../shared/state-kit.js';--export const PERMS = {- camera: { label: 'Camera', why: 'See your agents anchored in the real world through your camera.' },- motion: { label: 'Motion', why: 'Turn your phone to look around — agents stay pinned to real space.' },- location: { label: 'Location', why: 'Place agents at real spots and discover the ones others left nearby.' },-};--// Feature detection — drives the "unsupported" state per sensor.-export const support = {- camera: () => !!navigator.mediaDevices?.getUserMedia,- motion: () => typeof DeviceOrientationEvent !== 'undefined',- location: () => 'geolocation' in navigator,-};--// iOS 13+ gates motion behind an explicit gesture-bound requestPermission().-export const needsMotionGesture = () =>- typeof DeviceOrientationEvent?.requestPermission === 'function';-```--**State per permission** — render with state-kit, one card at a time:--| State | Surface | Copy / action |-|---|---|---|-| `prompt` | `emptyStateHTML` | "Why we need <Camera>" + the `why` line + a primary **Enable** button (the gesture). |-| `granted` | inline check, advance | green check, auto-advance to next permission. |-| `denied` | `errorStateHTML` | "Camera is blocked" + OS-specific recovery steps + **Try again** + **Continue without** (degraded). |-| `unsupported` | `emptyStateHTML` (compact) | "This device can't <use the camera>" + what still works (e.g. orbit-only, no AR). |--**iOS motion gesture — explicit handling.** Request must run *inside* the click-handler of the onboarding **Enable** button, not deferred:--```js-async function requestMotion() {- if (!support.motion()) return 'unsupported';- if (needsMotionGesture()) {- try {- const res = await DeviceOrientationEvent.requestPermission(); // MUST be in the gesture- return res === 'granted' ? 'granted' : 'denied';- } catch { return 'denied'; } // throws if not called from a user gesture- }- // Android / non-gated: assume usable; confirm by listening for one event.- return await probeOrientation(); // resolve 'granted' on first deviceorientation, else 'denied' after 1500ms-}-```--Camera + location requests follow the same shape (`getUserMedia` reusing-`enableAR`'s logic; `getCurrentPosition` once to surface the prompt, then hand off-to the existing `watchPosition`). Map `GeolocationPositionError.PERMISSION_DENIED`-(code 1) → `denied`, `POSITION_UNAVAILABLE`/`TIMEOUT` → a retryable error.--**Flow.** On first visit (no `localStorage['irl_onboarded_v1']`): show the overlay-with a one-line pitch + the three permission cards in sequence. Each card lets the-user **Enable**, **Skip**, or recover from denial. Camera + location are required-for the full IRL loop; motion is recommended (orbit fallback exists). After the-sequence — or immediately on a repeat visit — persist results and dismiss the-overlay into the live scene. A **denied** sensor leaves a persistent re-request-chip in the topbar (e.g. "Enable camera") so recovery is always one tap away;-never leave the user with a non-functional button and no explanation.--**Wire-in (no logic duplicated).** `enableAR()`, `setLocked()`, and `initGPS()`-call into the onboarding module's `ensurePermission('camera'|'motion'|'location')`-which resolves the cached/granted state or re-opens the relevant card — so the-inline error toasts become the *fallback*, with the designed card as the primary path.--## Data / API changes--None. Pure client. Persist outcome in `localStorage['irl_onboarded_v1']`-(`{ camera, motion, location, ts }`) so we don't re-nag, and re-show a single-card only for a sensor the user later wants.--## Acceptance checklist--- [ ] First visit shows `#irl-onboard` with a value pitch + per-sensor cards.-- [ ] Each sensor has all four designed states (prompt / granted / denied / unsupported) via state-kit.-- [ ] iOS `DeviceOrientationEvent.requestPermission()` is called **inside** the Enable click handler; a denial routes to the recovery card, not a toast.-- [ ] Camera denial shows recovery steps + **Continue without** (scene still loads in orbit mode).-- [ ] Location denial is no longer swallowed (`initGPS` error cb routes to a state); My-pins + nearby load gate cleanly.-- [ ] Repeat visits skip onboarding; a denied sensor shows a re-request chip in the topbar.-- [ ] No blank screen in any branch; every dead path removed.-- [ ] Existing `enableAR`/`setLocked`/`initGPS` reuse the module — no duplicated permission logic.-- [ ] No console errors/warnings; respects `prefers-reduced-motion`.--## Out of scope--- The world-anchor math (Epic A). This task only governs *getting permission* and- the onboarding shell; A1/A4 consume the granted sensors.-- Multiplayer presence prompts (Epic D).--## Verify--`npm run dev`, open `/irl` on a phone (or device-emulated DevTools with sensors).-Deny each permission in turn; confirm a designed recovery card appears and the-scene never blanks. On a real iPhone, confirm the motion card's Enable button-triggers the native iOS motion dialog and a denial shows recovery copy. Clear-`localStorage` and reload to re-trigger first-run. `npm test` stays green.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/E1-permissions-onboarding.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/E2-performance-scale.md b/tasks/irl-live/E2-performance-scale.mddeleted file mode 100644index bda4e124d..000000000--- a/tasks/irl-live/E2-performance-scale.md+++ /dev/null@@ -1,167 +0,0 @@-# E2 — Performance & scale (dense nearby agents stay smooth)--## Goal--Keep `/irl` at a steady frame rate when a busy location has many nearby pins:-**distance culling**, **GLB LOD / impostor billboards** beyond N metres, a-**concurrent-load cap + load queue**, an explicit **draw-call / texture budget**-(wired through `src/webgl-budget.js`), and **graceful degradation** on low-end-devices. Budgets are defined below, not left implicit.--## Why it matters--Every nearby pin currently spawns its own `Group` with a beacon, and any pin under-80 m tries to load a full GLB. A popular plaza could carry dozens of pins; a handful-of skinned-mesh avatars plus per-frame label projection will tank a mid-range phone-and trip *"Too many active WebGL contexts"* on top of the rest of the page. A-camera-AR product that stutters is dead on arrival — smoothness *is* the feature.--## Current state (real lines)--- **Load gate (the only throttle today):** `spawnNearbyPin()` `src/irl.js:981` —- `loadedCount < 5 && pin.distance_m < 80` before `loadPinGLB()`. Crude: no queue,- no eviction when the user walks away, no re-load when they walk back.-- **GLB load:** `loadPinGLB()` `src/irl.js:990` — a fresh `new GLTFLoader()` per- pin (no shared loader, no DRACO/meshopt reuse), beacon swapped for the model.-- **Beacon placeholder:** `src/irl.js:958` — every pin always carries a- transmission/emissive `MeshPhysicalMaterial` sphere (expensive material for a dot).-- **Per-frame work:** `updateLabels()` `:1254` and `updateRadar()` `:1230` iterate- *all* `nearbyPins` every frame; radar rebuilds DOM dots each frame (`:1233`).-- **Renderer:** `src/irl.js:103` — `antialias:true`, `preserveDrawingBuffer:true`,- `setPixelRatio(min(dpr,2))`, one 1024² shadow map (`:122`). No device-tiering.-- **Budget helper:** `src/webgl-budget.js` — `reserveWebGLContext()` /- `releaseWebGLContext()` track `window.__agent3dReservedContexts`. IRL owns one- long-lived context; it must `reserveWebGLContext()` once so the rest of the page- stays under the browser cap, and it never spawns per-pin contexts (all pins share- the single scene — keep it that way).-- `NEARBY_RADIUS = 150` (`:790`), fetch every 15 s (`:791`).--## What to build--### 1. Budgets (defined — tune per tier)--```js-// src/irl/perf-budget.js-export const TIER = detectTier(); // 'low' | 'mid' | 'high'--export const BUDGET = {- high: { maxGLB: 8, lodNear: 18, lodFar: 45, cull: 150, pixelRatio: 2, shadow: 1024, label: 24 },- mid: { maxGLB: 5, lodNear: 14, lodFar: 35, cull: 120, pixelRatio: 1.5, shadow: 512, label: 16 },- low: { maxGLB: 2, lodNear: 10, lodFar: 22, cull: 80, pixelRatio: 1, shadow: 0, label: 8 },-}[TIER];-// maxGLB = concurrent full avatars · lodNear = full GLB ≤ this · lodFar = impostor ≤ this-// cull = beyond this metres a pin is hidden entirely · label = max simultaneous HTML labels-```--`detectTier()` reads real signals: `navigator.hardwareConcurrency`,-`navigator.deviceMemory`, `devicePixelRatio`, a coarse mobile UA check, and an-optional one-frame GPU timer — no fake values, default to `mid` when unknown.--### 2. Distance culling--In a new `enforceLOD()` (called from `tick()`, throttled to ~4 Hz, not per frame):-for each pin compute distance from the camera and assign a band — `full` (GLB),-`impostor` (billboard), `dot` (cheap beacon), or `hidden` (set `group.visible=false`,-detach label). Crossing `BUDGET.cull` hides the pin and frees its label slot.--### 3. GLB LOD / impostor billboards beyond N metres--Beyond `lodNear` but within `lodFar`, render a **billboard impostor** instead of a-skinned GLB: a single camera-facing `PlaneGeometry` with a `SpriteMaterial`/textured-quad showing the avatar's thumbnail (`avatar_url`'s poster, or a render-to-texture-snapshot taken once when the GLB first loads). Impostors cost ~1 draw call and no-skinning. Replace the always-on `MeshPhysicalMaterial` beacon (`:958`) with a cheap-`MeshBasicMaterial`/sprite dot for the `dot` band.--### 4. Concurrent-load cap + load queue--Replace the ad-hoc `loadedCount < 5` check with a real queue:--```js-// src/irl/load-queue.js-const queue = []; let active = 0;-const loader = sharedGLTFLoader(); // ONE loader (+ DRACO/meshopt) reused across pins--export function requestGLB(pin, onDone) {- queue.push({ pin, onDone });- queue.sort((a, b) => a.pin.distance_m - b.pin.distance_m); // nearest first- pump();-}-function pump() {- while (active < BUDGET.maxGLB && queue.length) {- const { pin, onDone } = queue.shift();- active++;- loader.loadAsync(pin.avatar_url)- .then(onDone).catch(() => {})- .finally(() => { active--; pump(); });- }-}-export function evict(pin) { /* dispose geometry/material/textures, drop to impostor */ }-```--When a pin leaves `lodNear`, **evict** its GLB (dispose geometry + materials +-textures) and fall back to the impostor — bounded memory regardless of how many-pins the user walks past. Re-queue on re-approach.--### 5. Draw budget + texture budget (via webgl-budget)--- Call `reserveWebGLContext()` once at IRL boot; `releaseWebGLContext()` on unload.-- Track an approximate draw-call count = `active GLBs · avg + impostors + scene`.- When projected draws exceed the tier ceiling, demote the farthest `full` pin to- `impostor` even if it's inside `lodNear`. Cap simultaneous label DOM nodes at- `BUDGET.label` (nearest-first), reusing the existing `updateLabels()` loop.-- Texture budget: impostor atlas + shared loader keep VRAM bounded; dispose on evict.--### 6. Graceful degradation on low-end devices--On `TIER==='low'`: `pixelRatio=1`, shadows off (`renderer.shadowMap.enabled=false`,-matching `BUDGET.shadow===0`), `maxGLB=2`, smaller cull radius, impostors preferred.-Add a frame-time watchdog: if the rolling avg frame time exceeds ~28 ms for ~2 s,-step down one tier live (drop pixelRatio, then disable shadows, then shrink `maxGLB`)-— and step back up if it recovers. Never freeze; always degrade visibly-gracefully.--## Data / API changes--None required. **Nice-to-have (optional):** have `GET /api/irl/pins` include a-`thumb_url` (poster) per pin so impostors don't need a client-side render-snapshot-on first sight. If absent, snapshot the GLB to a texture once on load.--## Acceptance checklist--- [ ] `detectTier()` picks low/mid/high from real device signals; `BUDGET` applied at boot.-- [ ] Pins beyond `BUDGET.cull` are fully hidden (no draws, no label).-- [ ] Pins in the LOD-far band render as impostor billboards (~1 draw call), not skinned GLBs.-- [ ] A shared GLTFLoader + load queue enforces `maxGLB` concurrency, nearest-first.-- [ ] Walking away from a pin evicts its GLB and disposes geometry/materials/textures; re-approach re-loads.-- [ ] `reserveWebGLContext()` called once; IRL never creates per-pin contexts.-- [ ] Label DOM nodes capped at `BUDGET.label`; `updateLabels`/`updateRadar` stay O(n) and skip culled pins.-- [ ] Low tier: shadows off, pixelRatio 1; frame-time watchdog steps tiers down/up live.-- [ ] Verified smooth (~55–60 fps mid-tier) with 30+ simulated nearby pins.-- [ ] No console errors; no "Too many active WebGL contexts" warning.--## Out of scope--- Realtime pin sync (Epic D) — E2 only governs *rendering* whatever pins are loaded.-- The permission/onboarding flow (E1) and designed-state pass (E4).--## Verify--`npm run dev`, open `/irl`, seed many pins near your GPS (or temporarily fan out a-local pin set) and walk the avatar through them. Watch the DevTools FPS meter and-`renderer.info.render.calls` — confirm draws stay bounded as pin count climbs, GLBs-load nearest-first up to the cap, distant pins are impostors, and far pins vanish.-Throttle CPU 6× to confirm the watchdog degrades instead of stalling. `npm test` green.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/E2-performance-scale.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/E3-deeplinks-share.md b/tasks/irl-live/E3-deeplinks-share.mddeleted file mode 100644index 7e221d00e..000000000--- a/tasks/irl-live/E3-deeplinks-share.md+++ /dev/null@@ -1,155 +0,0 @@-# E3 — Deep-links & share (View in IRL/XR + composite screenshot)--> **Supersedes `tasks/irl-xr/03-irl-xr-deeplink.md` and `tasks/irl-xr/05-irl-xr-screenshot.md`.**-> Both partially landed since those were written — this task reconciles what-> already ships with what's still missing. Treat 03/05 as reference only.--## Goal--1. **"View in IRL" / "View in XR" buttons on agent _and_ avatar detail pages** that- deep-link to `/irl` (and `/xr`) with that agent/avatar preselected and loaded.-2. **A screenshot/share feature** that composites the 3D canvas over the camera feed- into one image and offers it through the native share sheet (`navigator.share`- with `files`), with a desktop download fallback.--## Why it matters--The platform feels linked only when every surface routes into the immersive layer.-An agent's profile that can't drop you into IRL with *that agent* is a dead end. And-a one-tap composite share ("here's my agent standing in my room") is the-screenshot-and-post moment that drives the loop — it must be real (camera + 3D-flattened into one PNG), not a bare canvas grab.--## Current state (real lines)--- **Avatar detail — already done.** `src/avatar-page.js:289-301` already renders the- `.av-ar-row` with **View in AR**, **Walk IRL** (`/irl?avatar=<id>`), and- **View in XR** (`/xr?avatar=<id>`). E3 does **not** rebuild this — it verifies- parity and reuses the markup/icon pattern for the agent page.-- **Agent detail — missing the IRL/XR pair.** `src/agent-detail.js` has only a- "View in AR" world link via `seeInWorldHref(agent)` (`:466-477`, the `#ad-3d-modal-world`- link). There is **no** "View in IRL"/"View in XR" CTA on the agent page. This is- the real gap to fill.-- **Deep-link target.** `/irl` reads `?avatar=<id>` (`src/irl.js:64`) and resolves- via `resolveAvatarUrl()` / `loadAvatar()` (`:67`, `:554`). An agent page has an- `agent.id`; map it to its avatar (the agent's `avatar_id`/`asset`) so the deep- link preselects the **agent's** body, and pass through to the inspect/profile wiring.-- **Screenshot — already implemented inline, but only on `/irl`.** `pages/irl.html:886-945`- has a working `#irl-share-btn` handler that composites `#irl-camera` (when- `body.is-ar`) under `#irl-canvas` and shares via `navigator.share`/`canShare` with- a download fallback. Renderer is built with `preserveDrawingBuffer:true`- (`src/irl.js:103`). So 05's IRL portion is **done** — but it's an inline `<script>`,- not reusable, and `/xr` still has no share affordance.--## What to build--### A. Agent-page IRL/XR deep-link CTAs (`src/agent-detail.js`)--Add a **View in IRL** + **View in XR** pair near the existing AR/world link. Resolve-the agent's avatar id so the link preselects the agent's body:--```js-// agent.avatar_id (or agent.asset / agent.glb) → /irl?avatar=<id>&agent=<agent.id>-function irlHref(agent) {- const av = agent.avatar_id || agent.asset || '';- const sp = new URLSearchParams();- if (av) sp.set('avatar', av);- if (agent.id) sp.set('agent', agent.id); // lets /irl deep-focus this agent's pin / inspect card- return `/irl${sp.toString() ? '?' + sp : ''}`;-}-const xrHref = (a) => `/xr?avatar=${encodeURIComponent(a.avatar_id || a.asset || '')}`;-```--Render as `<a href>` (right-click / new-tab friendly), matching `.av-ar-btn` styling-and the walk/cube icons used at `src/avatar-page.js:294-300`. Gate visibility on a-resolvable body (every agent has one — custom GLB or mannequin — so the href is-always real, same invariant the world link relies on at `:467`). Add a new-`&agent=` handler in `src/irl.js` that, once nearby pins load, focuses/opens the-matching pin's inspect card (reuse `highlightPinId` flash at `:933` + `openPinSheet`).--### B. Reusable composite-share module (`src/irl/share-frame.js`)--Lift the inline IRL handler into a module so `/xr` reuses it and IRL imports it-(delete the duplicated inline `<script>` in `pages/irl.html` once ported):--```js-// src/irl/share-frame.js-export async function captureComposite({ canvas, video, isAR }) {- const w = canvas.width, h = canvas.height; // renderer pixel size, not CSS- if (!w || !h) return null;- const out = document.createElement('canvas');- out.width = w; out.height = h;- const ctx = out.getContext('2d');- if (isAR && video && !video.paused) { // camera feed = background- try { ctx.drawImage(video, 0, 0, w, h); } catch {}- }- try { ctx.drawImage(canvas, 0, 0); } catch {} // 3D (alpha) over the top- return await new Promise((r) => out.toBlob(r, 'image/png'));-}--export async function shareOrDownload(blob, { filename = 'three-ws-irl.png', title = 'IRL · three.ws', fallbackUrl } = {}) {- const file = new File([blob], filename, { type: 'image/png' });- if (navigator.share && navigator.canShare?.({ files: [file] })) {- await navigator.share({ title, files: [file] }); return 'shared';- }- const url = URL.createObjectURL(blob); // desktop download- const a = document.createElement('a'); a.href = url; a.download = filename; a.click();- setTimeout(() => URL.revokeObjectURL(url), 4000); return 'downloaded';-}-```--Requires `preserveDrawingBuffer:true` on the renderer (already set in IRL at `:103`;-**add it in `src/xr.js`** if absent). All states designed: button shows-`…` while capturing, then `Shared!` / `Saved!`, and on a blank-canvas/share-abort-failure falls back to URL share → clipboard copy (the existing IRL fallback chain).--### C. Add share to `/xr`--`pages/xr.html` has no share button — add one in the topbar (mirror `.irl-share-btn`-position), wire to `captureComposite({ canvas:'#xr-canvas', video:'#xr-camera-feed',-isAR: <xr/passthrough active> })` + `shareOrDownload`. Confirm `src/xr.js` renderer-has `preserveDrawingBuffer:true`.--## Data / API changes--None. Deep-links are pure URL params; share is fully client-side. The `&agent=` focus-reuses the existing public `GET /api/irl/pins` nearby feed — no new endpoint.--## Acceptance checklist--- [ ] Agent detail page (`/agents/:id`) shows **View in IRL** + **View in XR** CTAs as real `<a href>` links.-- [ ] IRL link carries `?avatar=<agent body>&agent=<id>`; `/irl` loads that body and focuses the matching pin's inspect card when nearby.-- [ ] Avatar detail parity confirmed (existing `.av-ar-row` buttons unchanged / still correct).-- [ ] Composite-share logic lives in `src/irl/share-frame.js`; IRL imports it and the inline `<script>` in `pages/irl.html` is removed.-- [ ] `/xr` has a share button that composites camera + canvas; `src/xr.js` renderer uses `preserveDrawingBuffer:true`.-- [ ] In AR mode the shared PNG shows camera feed + 3D agent flattened together; non-AR shares the canvas alone.-- [ ] Mobile opens the native share sheet with the PNG; desktop downloads it; capture failure falls back to URL share → clipboard.-- [ ] Buttons have hover/active/focus states; capturing/shared/saved states are designed.-- [ ] No console errors; no duplicated share code across IRL and XR.--## Out of scope--- The inspect-card content itself (Epic B2/B3) — E3 only routes to it and focuses it.-- Server-side OG image rendering of shared frames (future).--## Verify--`npm run dev`. On `/agents/:id`, confirm both CTAs appear and open `/irl`/`/xr` in a-new tab with the agent's body loaded; with the agent pinned nearby, confirm `&agent=`-opens its inspect card. On `/irl` (AR on) and `/xr`, tap Share on a phone → native-sheet with a composited PNG; on desktop → PNG downloads. Inspect the PNG to confirm-camera + 3D are flattened. `npm test` green; review `git diff` for the deleted inline script.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/E3-deeplinks-share.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-live/E4-designed-states.md b/tasks/irl-live/E4-designed-states.mddeleted file mode 100644index 3061b34d6..000000000--- a/tasks/irl-live/E4-designed-states.md+++ /dev/null@@ -1,118 +0,0 @@-# E4 — Designed states across every IRL surface--## Goal--A systematic pass so **every** IRL surface — the AR view, the radar, the inspect-card, the My-pins sheet, and the owner dashboard pages — has a designed-**empty / loading / error / permission / unsupported-device** state, built on-`src/shared/state-kit.js` and consistent with the platform's just-completed-network/input error-boundary audit. No surface ever renders a blank container, a-bare spinner, or an unhandled rejection.--## Why it matters--The rest of the codebase now fails into designed states via `state-kit` +-`async-state` (`loadInto`/`renderError`). IRL is the loudest exception: it leans on-a 3-second `setStatus()` toast (`src/irl.js:92`) for *everything* — camera failure,-avatar failure, GPS-not-ready, empty pins. A toast that vanishes is not a designed-state. This task brings IRL up to the same bar surface by surface, so the product-feels finished from the first empty location to a mid-session network drop.--## Current state (real lines)--- **Single toast for all states:** `setStatus()` `src/irl.js:92` (auto-hides at 3 s,- `:99`). Used for avatar-load errors (`:634`, `:1420`), camera errors (`:204`),- payment errors (`:1213`), delete errors (`:1103`). Transient, not designed.-- **My-pins:** has a real empty state string (`src/irl.js:1072`) and a "Loading…"- string (`:1090`) but hand-rolled, not state-kit; no error state (a failed- `loadMyPins()` returns `[]` `:1063` → shows the *empty* copy, masking the error).-- **Nearby pins:** `loadNearbyPins()` swallows failures (`catch {}` `:947`); a busy- spot that fails to load looks identical to an empty one.-- **Inspect card / sheet:** `openPinSheet()` `:1135` assumes fields exist; no- loading/error state when richer card data (Epic B2) is fetched.-- **Dashboard:** `src/dashboard-next/pages/irl-placements.js` (~274 lines) lists- placements — must use `loadInto()` from `async-state.js` for its four states.-- **Toolkit available:** `emptyStateHTML` / `errorStateHTML` / `skeletonHTML` /- `ensureStateKitStyles` / `attachRetry` (`src/shared/state-kit.js`), and- `loadInto` / `renderError` (`src/shared/async-state.js`).--## What to build--A surface-by-surface audit. For each surface below, wire the listed states with-state-kit (and `loadInto`/`renderError` where there's a fetch). Add a small-`#irl-overlay` host for full-screen IRL states (camera/GPS/unsupported) so the AR-view has a designed canvas-level state, not just toasts.--### Surface → required states (the checklist)--| Surface | Loading | Empty | Error | Permission | Unsupported |-|---|---|---|---|---|---|-| **AR view** (scene boot, camera) | avatar skeleton / "Loading agent…" overlay | n/a (scene always present) | avatar-load error card w/ **Retry** (replaces toast at `:1420`) | camera/motion/location denied → recovery card (defer to **E1**, but the overlay host lives here) | no-WebGL / no-getUserMedia → "This device can't run IRL AR" + what still works |-| **Radar** (`#irl-radar`) | — (derives from pins) | "No agents in range" hint when GPS-ready but `nearbyPins` empty | pin-fetch failed → small error dot/tooltip + retry on next interval | hidden until GPS granted (handled by gps-mode class) | hidden if no geolocation |-| **Inspect card** (`#irl-sheet`) | skeleton rows while card data (B2) loads | "No services yet" when agent has no skills/x402 | `renderError` w/ Retry if card fetch fails | wallet-not-connected state on Pay (exists at `:1175`) — formalize w/ state-kit | Pay hidden if no `x402_endpoint` (exists at `:1145`) |-| **My-pins sheet** (`#irl-mypins-list`) | `skeletonHTML(3,'row')` (replace "Loading…" `:1090`) | keep current empty copy, via `emptyStateHTML` | **new** error state when `loadMyPins()` fails — stop masking it as empty (`:1063`) | "Enable location to manage pins" when GPS denied | — |-| **Nearby pins** (load loop) | first-load skeleton in radar/badge | nearby badge hidden + "Be the first to pin here" hint | surface `loadNearbyPins` failure (`:947`) → retry indicator, not silent | — | — |-| **Dashboard placements** (`irl-placements.js`) | `loadInto` skeleton (`variant:'row'`) | "No pins placed yet" + CTA to `/irl` | `loadInto` error w/ Retry | signed-out → sign-in CTA | — |--### Implementation notes--- **AR-view overlay host:** add `<div id="irl-overlay" hidden>` to `pages/irl.html`- (full-screen, above canvas). Render `errorStateHTML`/`emptyStateHTML` into it for- avatar-load failure (wire `attachRetry` → re-run `loadAvatar`) and- unsupported-device. This replaces the sticky error toast as the *primary* surface;- keep `setStatus` only for ephemeral progress ("Camera on", "Pin removed").-- **My-pins:** route through `loadInto(list, { load: loadMyPins, render, empty, skeleton:{count:3,variant:'row'} })`- so the error case stops collapsing into empty.-- **Nearby fetch:** on `loadNearbyPins` catch, set a transient "couldn't refresh- nearby" indicator on the badge and retry on the next 15 s interval — visible, not silent.-- **Dashboard:** replace bespoke list rendering with `loadInto`.-- **Copy is plain + actionable** (matches the platform's error-message audit): say- what happened and the next step; tuck technical detail behind `emptyStateHTML`'s- `tip` where useful. Respect `prefers-reduced-motion` (state-kit already does).--## Data / API changes--None. This is a presentation/error-boundary pass over existing fetches-(`loadMyPins`, `loadNearbyPins`, placements list, avatar load) and the inspect-card-fetch introduced by B2.--## Acceptance checklist--- [ ] Every row of the surface→states table is implemented with `state-kit` / `async-state`.-- [ ] `#irl-overlay` host added; avatar-load failure shows a designed **Retry** card (not a vanishing toast).-- [ ] Unsupported-device state (no WebGL / no `getUserMedia`) renders designed copy explaining what still works.-- [ ] My-pins uses `loadInto`; a failed `loadMyPins()` shows an **error** state, no longer masquerading as empty.-- [ ] `loadNearbyPins` failures surface a visible retry indicator instead of `catch {}` silence.-- [ ] Inspect card has loading skeleton + error/empty for service data; wallet-not-connected formalized via state-kit.-- [ ] Dashboard `irl-placements.js` renders all four states through `loadInto`.-- [ ] `setStatus` is reserved for ephemeral progress only; no permanent state depends on a toast.-- [ ] Copy is plain, actionable, platform-consistent; reduced-motion respected; no console errors.--## Out of scope--- The permission *prompt/onboarding flow* itself (E1) — E4 only provides the AR-view- overlay host and the denied-state copy that E1 fills.-- The inspect-card *content* and card API (Epic B2/B3) — E4 designs its loading/empty/error shells.--## Verify--`npm run dev`, `/irl`. Force each state: deny GPS (My-pins → location-needed; radar-hidden), break the avatar URL (overlay error + Retry), throttle network offline then-open My-pins (error state, not empty), open a fresh location (nearby empty hint).-Visit the dashboard placements page signed-out (sign-in CTA) and with zero pins-(empty CTA). Confirm no surface ever shows a blank container or a lone spinner.-`npm test` green; `git diff` reviewed.--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-live/E4-designed-states.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-xr/01-xr-avatar-lock.md b/tasks/irl-xr/01-xr-avatar-lock.mddeleted file mode 100644index 8d0825c7f..000000000--- a/tasks/irl-xr/01-xr-avatar-lock.md+++ /dev/null@@ -1,110 +0,0 @@-# XR Avatar Lock--## What to build--Add a pin/lock toggle to `/xr` that freezes the avatar's position while still allowing the camera to orbit freely. This is the same feature already live on `/irl` — bring full parity.--## Context--`/irl` (`pages/irl.html` + `src/irl.js`) already has this feature:-- A **"Lock"** pill button in the secondary row (id `irl-lock-btn`)-- `let avatarLocked = false` state in `src/irl.js`-- `setLocked(next)` function that toggles the state, updates button appearance (amber when active, label switches to "Locked"), and in AR mode unfreezes the camera so drag-to-orbit still works around the pinned avatar-- The tick loop gates avatar movement: `if (mag > 0.01 && avatar && !avatarLocked)`--`/xr` (`pages/xr.html` + `src/xr.js`) uses a different UI — no joystick, no placement objects. Instead it has:-- A bottom panel with: avatar row, body toggle (full/half), status row, Enter AR button-- The avatar is stationary (no walking); the user can orbit via `OrbitControls`--On `/xr` the avatar already doesn't move via joystick. "Lock" here means something slightly different: **lock the camera orbit** so the avatar stays centered and OrbitControls is disabled (useful when in WebXR or camera-AR mode, where you want the avatar fixed and the camera controlled by the device). When unlocked, OrbitControls works normally.--## What to do--### 1. Add lock state to `src/xr.js`--```js-let orbitLocked = false;--function setOrbitLocked(next) {- orbitLocked = next;- controls.enabled = !next;- if (lockBtn) {- lockBtn.setAttribute('aria-pressed', String(next));- lockBtn.classList.toggle('xr-lock--active', next);- lockBtn.querySelector('.xr-lock-label').textContent = next ? 'Locked' : 'Lock';- }- setStatus(next ? 'Avatar pinned — orbit disabled' : 'Orbit unlocked', 'idle');-}-```--Add DOM ref:-```js-const lockBtn = document.getElementById('xr-lock-btn');-```--Wire the button:-```js-if (lockBtn) lockBtn.addEventListener('click', () => setOrbitLocked(!orbitLocked));-```--### 2. Add the Lock button to `pages/xr.html`--Insert it inside `#xr-panel`, in the body-toggle row area — after the `#xr-body-toggle` div and before `#xr-half-info`. Style it as a small pill matching the XR design language:--```html-<button id="xr-lock-btn" type="button" class="xr-lock-btn" aria-pressed="false" aria-label="Lock avatar orbit">- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">- <rect x="3" y="11" width="18" height="11" rx="2"/>- <path d="M7 11V7a5 5 0 0 1 10 0v4"/>- </svg>- <span class="xr-lock-label">Lock</span>-</button>-```--Add CSS in the page `<style>`:-```css-.xr-lock-btn {- appearance: none;- border: 1px solid var(--border);- background: rgba(255,255,255,0.04);- color: var(--text-2);- font: inherit; font-size: 12px; font-weight: 600;- padding: 7px 14px; border-radius: 999px; cursor: pointer;- display: inline-flex; align-items: center; gap: 6px;- transition: background 0.15s, border-color 0.15s, color 0.15s;- align-self: flex-start;-}-.xr-lock-btn:hover { color: var(--text); border-color: rgba(255,255,255,0.2); }-.xr-lock-btn.xr-lock--active {- color: #fbbf24;- border-color: rgba(251,191,36,0.45);- background: rgba(251,191,36,0.1);-}-```--## Files to touch--- `src/xr.js`-- `pages/xr.html`--## Definition of done--- Lock button appears in the XR bottom panel-- Tapping it disables OrbitControls (amber styling, label = "Locked")-- Tapping again re-enables OrbitControls (normal styling, label = "Lock")-- Status bar reflects the state change-- No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-xr/01-xr-avatar-lock.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-xr/02-avatar-picker-thumbnail-3d.md b/tasks/irl-xr/02-avatar-picker-thumbnail-3d.mddeleted file mode 100644index 44bcedaf4..000000000--- a/tasks/irl-xr/02-avatar-picker-thumbnail-3d.md+++ /dev/null@@ -1,90 +0,0 @@-# Avatar Picker — 3D Thumbnail Previews--## What to build--Upgrade the avatar picker bottom sheet (`src/avatar-picker.js`) so each card shows a live 3D thumbnail rendered from the GLB, not a flat image. If no `thumbnail_url` exists (common for user-uploaded avatars), render the GLB in a tiny offscreen Three.js canvas instead of the blank silhouette placeholder.--## Context--`src/avatar-picker.js` is a shared bottom-sheet component used by both `/irl` and `/xr`. It fetches `GET /api/avatars` and renders a grid of cards. Currently each card shows:-- `thumbnail_url` (a flat image) if available, OR-- An SVG silhouette placeholder if the avatar has no thumbnail--The placeholder silhouette looks weak. Many user avatars lack a thumbnail. A 3D render gives a much better preview.--## Approach--Use a single shared offscreen `WebGLRenderer` with a tiny orthographic/perspective camera. Render each GLB into it one at a time (they're loaded lazily as the user scrolls through the grid — use `IntersectionObserver`). Cache rendered canvases as `data:image/png` URLs so each GLB is only rendered once per picker session.--```-OffscreenRenderer (singleton, 256×256)- └─ for each card entering viewport:- 1. fetch + parse GLB (GLTFLoader.loadAsync)- 2. center + scale scene to fill frame- 3. renderer.render(scene, camera) → canvas.toDataURL()- 4. set as card <img> src- 5. dispose GLB from scene-```--## Implementation sketch--```js-// inside avatar-picker.js--let _offscreenRenderer = null;--function getOffscreenRenderer() {- if (_offscreenRenderer) return _offscreenRenderer;- const canvas = document.createElement('canvas');- canvas.width = 256; canvas.height = 256;- const { WebGLRenderer, Scene, PerspectiveCamera, AmbientLight, DirectionalLight, Box3, Vector3 } = THREE;- const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });- renderer.setPixelRatio(1);- renderer.setSize(256, 256);- // ... camera + lights setup- _offscreenRenderer = { renderer, /* camera, scene, lights */ };- return _offscreenRenderer;-}--async function render3dThumbnail(glbUrl) {- // GLTFLoader.loadAsync(glbUrl)- // fit to frame- // render → canvas.toDataURL('image/png')- // return data URL-}-```--Use `IntersectionObserver` on each card's thumbnail div to trigger `render3dThumbnail` lazily (don't render all 50 avatars upfront).--## Files to touch--- `src/avatar-picker.js` — add offscreen renderer + lazy 3D thumbnail logic--## Notes--- The offscreen renderer must be created lazily (first card load), not at module import time, to avoid a WebGL context being created when the picker is never opened-- Dispose of each loaded GLB scene after rendering to free GPU memory — only the PNG data URL is kept-- If the GLB fails to load, silently fall back to the existing placeholder-- No new npm packages — Three.js is already imported elsewhere in the project via Vite (import from `'three'` and `'three/addons/loaders/GLTFLoader.js'`)-- Import Three.js dynamically inside the render function to keep the picker's initial bundle lean--## Definition of done--- Cards without a `thumbnail_url` show a 3D render of the actual GLB-- 3D thumbnails load lazily as cards enter the viewport (IntersectionObserver)-- No perceptible freeze when the picker opens (renders happen async)-- No console errors on open/close--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-xr/02-avatar-picker-thumbnail-3d.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-xr/03-irl-xr-deeplink.md b/tasks/irl-xr/03-irl-xr-deeplink.mddeleted file mode 100644index a17352ec7..000000000--- a/tasks/irl-xr/03-irl-xr-deeplink.md+++ /dev/null@@ -1,77 +0,0 @@-# IRL + XR Deep-link From Avatar Profile--## What to build--Add "Open in IRL" and "Open in XR" buttons to the avatar detail page (`/avatars/:id`) so users can jump directly from their avatar's profile into the immersive experience with that avatar pre-loaded.--## Context--Avatar detail page: `src/avatar-page.js` + the HTML rendered at `/avatars/:slug`.--Both `/irl` and `/xr` already accept a `?avatar=<id>` URL param which pre-loads that specific avatar:-- `/irl?avatar=<uuid>` — walks the avatar on a dark ground or camera-AR-- `/xr?avatar=<uuid>` — places the avatar in WebXR / camera passthrough--The avatar page currently has action buttons (Edit, Share, etc). We need two new CTA buttons.--## What to do--### 1. Find where action buttons are rendered--In `src/avatar-page.js`, locate the section that renders the avatar action buttons / CTA row (likely near `share`, `edit`, or `download` buttons).--### 2. Add IRL and XR buttons--```js-// Build the avatar action row — add alongside existing buttons-const irlUrl = `/irl?avatar=${avatar.id}`;-const xrUrl = `/xr?avatar=${avatar.id}`;-```--Button markup (match the existing button style on the page):-```html-<a href="/irl?avatar=UUID" class="av-action-btn">- <svg ...walk/person icon...></svg>- Walk IRL-</a>-<a href="/xr?avatar=UUID" class="av-action-btn">- <svg ...AR/cube icon...></svg>- View in XR-</a>-```--### 3. Also add to the avatar gallery card hover state--In the avatar gallery / explore page, each avatar card on hover (or long-press on mobile) should show an "IRL" badge link. Find the card component in `src/avatar-page.js` or wherever the gallery renders, and add a small pill overlay on the card thumbnail.--## Files to touch--- `src/avatar-page.js` — add IRL/XR buttons to detail view and optionally gallery cards-- Possibly the avatar detail HTML template if it's server-rendered--## Notes--- Buttons should only appear if `avatar.visibility === 'public'` OR the viewer is the owner-- The XR button can be hidden behind a `if (navigator.xr || true)` check — show it always for now since `/xr` has camera-passthrough fallback-- Use `<a href>` not `<button onclick>` so right-click → open in new tab works--## Definition of done--- Avatar detail page shows "Walk IRL" and "View in XR" action buttons-- Clicking either navigates to the correct URL with `?avatar=<id>`-- The destination pages load the correct avatar immediately (this already works — the param handling is in place)-- No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-xr/03-irl-xr-deeplink.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-xr/04-irl-scene-persistence.md b/tasks/irl-xr/04-irl-scene-persistence.mddeleted file mode 100644index 50c5706ef..000000000--- a/tasks/irl-xr/04-irl-scene-persistence.md+++ /dev/null@@ -1,135 +0,0 @@-# IRL Scene Persistence — Save & Restore Session State--## What to build--Persist the user's IRL session to `localStorage` so that refreshing the page or coming back later restores: the chosen avatar, the lock state, and any placed objects.--## Context--`src/irl.js` currently has:-- `_currentAvatarId` — the selected avatar UUID (or null for default)-- `avatarLocked` — boolean lock state-- `placedObjects[]` — array of `{ mesh, spawnT }` — these are Three.js Mesh objects, not serializable directly. Each was created from `OBJ_DEFS[selectedType].create()` where `selectedType` is `'orb'|'crate'|'crystal'|'ring'|'pillar'`.--The placed objects have positions (`mesh.position.x/z`) and a type. We need to save type + position and recreate them on restore.--## What to do--### 1. Define the persisted state shape--```js-// localStorage key-const STORAGE_KEY = 'irl_session_v1';--// Shape-{- avatarId: string | null,- locked: boolean,- placedObjects: Array<{ type: string, x: number, z: number }>-}-```--### 2. Save on every change--Call `_saveSession()` after:-- Avatar swap completes (`loadAvatar` resolves)-- Lock state changes (`setLocked`)-- Object placed (in the `pointerup` tap handler)-- Objects cleared (in `clearBtn` handler)--```js-function _saveSession() {- try {- localStorage.setItem(STORAGE_KEY, JSON.stringify({- avatarId: _currentAvatarId,- locked: avatarLocked,- placedObjects: placedObjects.map(o => ({- type: o.type,- x: o.mesh.position.x,- z: o.mesh.position.z,- })),- }));- } catch {}-}-```--Note: the existing `placedObjects` array stores `{ mesh, spawnT }`. Extend it to also store `type` at placement time so we can serialize it:-```js-placedObjects.push({ mesh, spawnT: 0, type: selectedType });-```--### 3. Restore on boot--After `loadAvatar()` resolves in the boot sequence, read and apply the saved session:--```js-function _restoreSession() {- try {- const raw = localStorage.getItem(STORAGE_KEY);- if (!raw) return;- const s = JSON.parse(raw);- if (s.locked) setLocked(true);- for (const o of (s.placedObjects || [])) {- const def = OBJ_DEFS[o.type];- if (!def) continue;- const mesh = def.create();- mesh.position.x = o.x;- mesh.position.z = o.z;- mesh.scale.setScalar(1); // skip spawn animation on restore- scene.add(mesh);- placedObjects.push({ mesh, spawnT: SPAWN_DURATION, type: o.type });- }- if (placedObjects.length) clearBtn.hidden = false;- } catch {}-}-```--Avatar restore: if `s.avatarId` differs from the URL param, prefer the URL param (explicit link wins); otherwise use the saved one.--```js-const targetId = avatarIdParam || s?.avatarId || null;-```--Restore this before calling `loadAvatar()` in boot.--### 4. Clear session on explicit "Clear" button press--When the user taps "Clear", also remove placed objects from localStorage:-```js-clearBtn.addEventListener('click', () => {- // existing clear logic...- _saveSession(); // persists empty placedObjects-});-```--## Files to touch--- `src/irl.js` only--## Notes--- `localStorage` can throw in private browsing on some iOS versions — always wrap in `try/catch`-- Don't persist the AR camera state (that's a hardware permission, not a user preference)-- Don't persist `cameraYaw`/`cameraPitch` — start fresh each visit-- The schema version suffix `_v1` means we can bump to `_v2` later without corrupting old sessions--## Definition of done--- Refresh IRL page → same avatar is loaded, same placed objects appear, lock state restored-- Clearing objects → refresh shows empty scene-- URL param `?avatar=` always takes precedence over saved session-- No console errors in private browsing mode--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-xr/04-irl-scene-persistence.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl-xr/05-irl-xr-screenshot.md b/tasks/irl-xr/05-irl-xr-screenshot.mddeleted file mode 100644index 1302ca447..000000000--- a/tasks/irl-xr/05-irl-xr-screenshot.md+++ /dev/null@@ -1,120 +0,0 @@-# IRL + XR Screenshot / Share--## What to build--Add a **screenshot** button to both `/irl` and `/xr` that captures the current Three.js canvas (with or without the camera feed composited) and either:-1. Shares via the native Web Share API (`navigator.share`) on mobile with `files: [blob]`-2. Downloads as a PNG on desktop--The IRL page already has a "Share" button in the top bar — extend it to capture the frame first. XR has no share affordance yet — add one.--## Context--**`/irl`** (`pages/irl.html` + `src/irl.js`):-- Three.js canvas: `#irl-canvas`, rendered by `renderer` (a `WebGLRenderer`)-- Camera feed: `#irl-camera` (a `<video>`) — visible only in AR mode (`body.is-ar`)-- Existing share button: `#irl-share-btn` in the top bar — currently copies URL to clipboard-- `renderer` is accessible at module scope in `src/irl.js`--**`/xr`** (`pages/xr.html` + `src/xr.js`):-- Three.js canvas: `#xr-canvas`-- Camera feed: `#xr-camera-feed` (a `<video>`)-- No share button exists yet-- `renderer` is accessible at module scope in `src/xr.js`--## Compositing--In AR mode, the real picture is: video (background) + 3D canvas (foreground with alpha). To composite both into one PNG:--```js-async function captureFrame(renderer, videoEl, isArActive) {- // Ensure preserveDrawingBuffer is true on the renderer- // (set it at renderer construction time)-- const w = renderer.domElement.width;- const h = renderer.domElement.height;- const out = document.createElement('canvas');- out.width = w; out.height = h;- const ctx = out.getContext('2d');-- if (isArActive && videoEl && !videoEl.paused) {- // Draw the camera feed first (background)- ctx.drawImage(videoEl, 0, 0, w, h);- }-- // Draw the Three.js frame on top- // Force a render so the pixels are fresh- // (renderer must have been created with preserveDrawingBuffer: true)- ctx.drawImage(renderer.domElement, 0, 0);-- return new Promise(resolve => out.toBlob(resolve, 'image/png'));-}-```--**Important:** `WebGLRenderer` must be constructed with `preserveDrawingBuffer: true`. Currently both pages construct it without this flag — add it.--## Sharing--```js-async function shareOrDownload(blob, filename) {- if (navigator.share && navigator.canShare?.({ files: [new File([blob], filename)] })) {- await navigator.share({- title: 'My 3D avatar — three.ws',- files: [new File([blob], filename, { type: 'image/png' })],- });- } else {- const url = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = url; a.download = filename;- a.click();- setTimeout(() => URL.revokeObjectURL(url), 4000);- }-}-```--## IRL changes--1. Add `preserveDrawingBuffer: true` to the `WebGLRenderer` constructor in `src/irl.js`-2. Replace the existing `#irl-share-btn` click handler (which only copies URL) with:- - Capture frame → share/download PNG- - Fallback to URL copy if capture fails--## XR changes--1. Add `preserveDrawingBuffer: true` to the `WebGLRenderer` constructor in `src/xr.js`-2. Add a screenshot button to `pages/xr.html` (top bar, right side — same position as IRL's share button)-3. Wire it to `captureFrame` + `shareOrDownload`--## Files to touch--- `src/irl.js` — add `preserveDrawingBuffer: true`, replace share handler-- `src/xr.js` — add `preserveDrawingBuffer: true`, add screenshot handler-- `pages/xr.html` — add screenshot button to top bar--## Notes--- `preserveDrawingBuffer: true` has a small performance cost (disables buffer swap optimization). It's acceptable on these pages since they're not performance-critical multiplayer scenes.-- On iOS, `navigator.share` with `files` requires iOS 15+. The download fallback handles older devices.-- The compositing canvas must match the renderer's pixel size, not CSS size (`renderer.domElement.width`, not `window.innerWidth`).--## Definition of done--- Tapping Share/Screenshot on mobile opens the native share sheet with a PNG attached-- On desktop, tapping downloads a PNG-- In AR mode, the downloaded image shows the camera feed + 3D avatar composited together-- `preserveDrawingBuffer: true` is set on both renderers-- No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl-xr/05-irl-xr-screenshot.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl/01-caption-and-heading.md b/tasks/irl/01-caption-and-heading.mddeleted file mode 100644index 29645571e..000000000--- a/tasks/irl/01-caption-and-heading.md+++ /dev/null@@ -1,83 +0,0 @@-# Task: IRL — Caption & compass heading when pinning--## What to build--When the user taps "Pin here" in AR mode, show a small slide-up input panel BEFORE the pin is saved so they can add an optional caption (e.g. "P2P trades here — DM me on Telegram"). Also capture the device's compass heading at pin time so the placed agent faces the world correctly.--## Current state--- `src/irl.js` — `setLocked(true)` at ~line 644 calls `savePin(lat, lng)` immediately, with no caption or heading.-- `savePin()` at ~line 758 sends `{ lat, lng, avatarUrl, avatarName, deviceToken }` — no `caption`, no `heading`.-- `api/irl/pins.js` — POST handler accepts `caption` and `heading` and stores them; nothing to change there.-- `api/_lib/db.js` exports `sql` tagged template for Neon Postgres.--## Changes required--### 1. Capture compass heading--In `src/irl.js`, there is already a `cameraYaw` variable (radians, updated by `onDeviceOrientation`). This represents the heading the user is currently facing. Convert it to degrees at pin time:--```js-const headingDeg = ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;-```--Store this in `gpsPin.heading` and pass it to `savePin`.--Update `savePin(lat, lng, heading, caption)` to include both fields in the POST body.--### 2. Caption input UI--In `pages/irl.html`, add a caption panel that slides up between "Pin here" tap and actual save. It should sit above `#irl-sheet` (z-index 21), look like a bottom sheet (same glass style), and contain:--- A `<textarea id="irl-caption-input">` placeholder "Add a caption… (optional)"-- A "Pin it" confirm button (green pill, same style as `.irl-sheet-btn-primary`)-- An "×" dismiss that cancels the whole pin action--CSS: same `transform: translateY(100%)` / `.is-open` pattern as `#irl-sheet`.--### 3. Flow change in `setLocked(true)`--Instead of calling `savePin` immediately:-1. Compute `gpsPin` lat/lng as now (lines 650-658)-2. Set `gpsModeActive = true` and lock the avatar-3. Open the caption panel-4. On "Pin it" click: read the caption value, call `savePin(lat, lng, headingDeg, caption)`, close the panel-5. On "×" dismiss: call `setLocked(false)` to undo the lock--### 4. Orient the placed agent in world space--In `spawnNearbyPin()` (~line 811), the `Group` is spawned with default rotation. After spawning, set:--```js-// Face the agent toward the placer's original heading (they placed it facing them)-pin.group.rotation.y = -(pin.heading ?? 0) * Math.PI / 180;-```--### 5. Update the nearby pin entry--In `loadNearbyPins()` the `entry` spread already carries `pin.heading` since the API returns it. No change needed there.--## Checklist--- [ ] Caption panel HTML added to `pages/irl.html` with CSS slide-up-- [ ] `setLocked(true)` opens caption panel instead of saving immediately-- [ ] Caption panel "Pin it" calls `savePin` with caption + heading, closes panel-- [ ] Caption panel dismiss cancels the lock-- [ ] `savePin` sends `caption` and `heading` in POST body-- [ ] `spawnNearbyPin` sets `group.rotation.y` from `pin.heading`-- [ ] No console errors, no unreachable states-- [ ] Changelog entry NOT required (internal UX refinement of a feature shipped same day)--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl/01-caption-and-heading.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl/02-view-agent-profile.md b/tasks/irl/02-view-agent-profile.mddeleted file mode 100644index e517daed4..000000000--- a/tasks/irl/02-view-agent-profile.md+++ /dev/null@@ -1,85 +0,0 @@-# Task: IRL — Wire "View agent" to real agent profile--## What to build--When a user taps a nearby pin's floating label and the interaction sheet opens, the "View agent" button currently navigates to `/walk?agent=<name>` (a name-search fallback). It should navigate to the agent's actual profile page at `/agents/<id>` when `agent_id` is available.--## Current state--`src/irl.js` ~line 893:--```js-document.getElementById('irl-sheet-view')?.addEventListener('click', () => {- const sheet = document.getElementById('irl-sheet');- const name = document.getElementById('irl-sheet-name')?.textContent || '';- sheet?.classList.remove('is-open');- window.open(`/walk?agent=${encodeURIComponent(name)}`, '_blank', 'noopener');-});-```--The `openPinSheet(pin)` function at ~line 872 already has the full pin object including `pin.agent_id`. It just doesn't forward it to the button.--## Changes required--### 1. Store agent_id on the sheet element--In `openPinSheet(pin)`, store `agent_id` on the sheet element as a data attribute:--```js-sheet.dataset.agentId = pin.agent_id ?? '';-sheet.dataset.agentName = pin.avatar_name ?? '';-```--### 2. Update the click handler--```js-document.getElementById('irl-sheet-view')?.addEventListener('click', () => {- const sheet = document.getElementById('irl-sheet');- const agentId = sheet?.dataset.agentId;- const name = sheet?.dataset.agentName || '';- sheet?.classList.remove('is-open');- if (agentId) {- window.open(`/agents/${agentId}`, '_blank', 'noopener');- } else {- // Fallback: search by name in the 3D walk scene- window.open(`/walk?agent=${encodeURIComponent(name)}`, '_blank', 'noopener');- }-});-```--### 3. Confirm `/agents/<id>` route exists--Check `vercel.json` for a route that maps `/agents/:id` → an HTML page. It should already exist as:--```json-{ "src": "/agents/([^/]+)", "dest": "/agents.html" }-```--(or similar). If the agent profile page reads the ID from `location.pathname`, the link will work. Verify the agent profile page URL format by checking `pages/agents.html` or looking at how existing agent links are constructed in the codebase (grep for `/agents/` in `src/`).--If the agents page reads from query string (`/agents?id=`), adjust the URL accordingly.--## Files to touch--- `src/irl.js` — `openPinSheet()` and the `irl-sheet-view` click handler (~lines 872–897)--## Checklist--- [ ] `openPinSheet` stores `agent_id` and `avatar_name` on `sheet.dataset`-- [ ] Click handler uses `agent_id` if present, falls back to name search-- [ ] Target URL format verified against how the rest of the site links to agent profiles-- [ ] No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl/02-view-agent-profile.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl/03-x402-payment.md b/tasks/irl/03-x402-payment.mddeleted file mode 100644index 00940284f..000000000--- a/tasks/irl/03-x402-payment.md+++ /dev/null@@ -1,113 +0,0 @@-# Task: IRL — Real x402 payment flow in the interaction sheet--## What to build--When a nearby pin has an `x402_endpoint`, the interaction sheet shows "Pay via x402". The current handler at `src/irl.js ~line 900` just does a raw `fetch(endpoint, { method: 'POST' })` and reports the 402 status as "coming soon". Build the real x402 payment flow using the existing `@three-ws/x402-fetch` client that is already in the project.--## Current state--```js-// src/irl.js ~line 900-document.getElementById('irl-sheet-pay')?.addEventListener('click', async (e) => {- const endpoint = e.currentTarget.dataset.endpoint;- if (!endpoint) return;- try {- const r = await fetch(endpoint, { method: 'POST' });- if (r.status === 402) {- setStatus('Payment required — x402 support coming soon', { error: true });- } else if (r.ok) {- setStatus('Payment sent');- }- } catch { setStatus('Payment failed', { error: true }); }-});-```--## x402 client that already exists--`sdk/x402-fetch/src/index.js` (or the published `@three-ws/x402-fetch` package) exports `wrapFetch`. It intercepts a 402 response, parses the `X-Payment-Required` header, signs a payment with the user's connected Solana wallet, and retries.--The Solana wallet adapter is already wired in the codebase — check how other pages that do x402 payments import and use `wrapFetch`. Look in `src/` for existing usages of `wrapFetch` or `x402`.--## How to get the connected wallet in irl.js--IRL mode doesn't currently use the wallet. You need to:--1. Import the wallet connection utility from the existing wallet module (grep for `getWallet` or `connectWallet` in `src/`).-2. On "Pay via x402" click, check if a wallet is connected. If not, prompt the user to connect first (use the existing wallet connect flow — don't invent a new one).-3. Pass the wallet's `signTransaction` / `signMessage` capability to `wrapFetch`.--## Implementation--Replace the current click handler with:--```js-document.getElementById('irl-sheet-pay')?.addEventListener('click', async (e) => {- const btn = e.currentTarget;- const endpoint = btn.dataset.endpoint;- if (!endpoint) return;-- // 1. Require wallet- const wallet = await ensureWalletConnected(); // use existing util- if (!wallet) return; // ensureWalletConnected shows its own error/prompt-- btn.disabled = true;- btn.textContent = 'Sending…';- try {- const fetchWithPayment = wrapFetch(fetch, wallet);- const r = await fetchWithPayment(endpoint, { method: 'POST' });- if (r.ok) {- setStatus('Payment sent');- btn.textContent = 'Paid ✓';- } else {- throw new Error(`${r.status}`);- }- } catch (err) {- setStatus(`Payment failed: ${err.message}`, { error: true });- btn.disabled = false;- btn.textContent = 'Pay via x402';- }-});-```--## Research steps--Before writing code, grep the codebase to find:--1. `grep -r "wrapFetch\|x402-fetch" src/ pages/ --include="*.js" -l` — find existing usages-2. `grep -r "connectWallet\|getWallet\|walletAdapter" src/ --include="*.js" -l` — find wallet util-3. Read those files to understand the exact import paths and function signatures--Match whatever pattern the rest of the codebase uses exactly.--## UX notes--- Disable the button while payment is in flight (prevent double-send)-- Show "Paid ✓" on success (don't reset to "Pay via x402" — prevents accidental double-pay)-- On failure, re-enable the button so the user can retry-- If no wallet is connected, show a prompt consistent with how other pages handle it--## Files to touch--- `src/irl.js` — the pay button click handler (~line 900) and any new imports at the top--## Checklist--- [ ] Real x402 payment signed and sent (not mocked)-- [ ] Wallet connect gated before payment attempt-- [ ] Button disabled during in-flight request-- [ ] Success / failure states displayed via `setStatus()`-- [ ] No `// implement later` or stub code--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl/03-x402-payment.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl/04-my-pins-management.md b/tasks/irl/04-my-pins-management.mddeleted file mode 100644index efc97a7c0..000000000--- a/tasks/irl/04-my-pins-management.md+++ /dev/null@@ -1,122 +0,0 @@-# Task: IRL — "My pins" management UI--## What to build--A user who has placed pins should be able to see them and remove them from any device (or even after reloading the page), as long as they're on the same device with the same `localStorage` device token. Add a "My pins" section that appears in the bottom sheet when the user has active pins they placed.--## Current state--- Anonymous ownership uses `localStorage.getItem('irl_device_token')` — a UUID generated on first visit and sent as `deviceToken` in POST / DELETE calls.-- The API at `GET /api/irl/pins` returns all nearby pins but doesn't filter by owner.-- The API at `DELETE /api/irl/pins?id=<id>&deviceToken=<token>` removes pins where `device_token` matches.-- There is no way for the user to browse their own remote pins (the in-memory `gpsPin` is lost on page reload).--## New API endpoint needed--Add `GET /api/irl/pins/mine?deviceToken=<token>` to `api/irl/pins.js` (or create `api/irl/my-pins.js`):--```sql-SELECT id, lat, lng, avatar_name, caption, placed_at, expires_at-FROM irl_pins-WHERE device_token = $1- AND (expires_at IS NULL OR expires_at > NOW())-ORDER BY placed_at DESC-LIMIT 20-```--Returns `{ pins: [...] }`.--## UI changes in `pages/irl.html`--Add a "My pins" pill button next to the existing avatar and pin buttons in `.irl-secondary-row`:--```html-<button class="irl-pill-btn" id="irl-mypins-btn" type="button" hidden aria-label="My active pins">- <svg ...><!-- list icon --></svg>- My pins-</button>-```--Show this button only when GPS is ready and the device has a stored token (checked in `initGPS()`).--When tapped, slide up a bottom sheet (`#irl-mypins-sheet`) listing the user's active pins. Each row shows:-- Agent name-- Caption (if any), truncated to one line-- Distance in metres (compute from current GPS position using haversine)-- Placed time (e.g. "2h ago")-- A red trash icon button to delete that pin--The sheet style should match `#irl-sheet` (same glass blur, same slide-up animation).--## JS changes in `src/irl.js`--```js-async function loadMyPins() {- if (!_deviceToken) return [];- const r = await fetch(`/api/irl/pins/mine?deviceToken=${_deviceToken}`);- if (!r.ok) return [];- return (await r.json()).pins ?? [];-}--async function openMyPinsSheet() {- const pins = await loadMyPins();- // render rows into #irl-mypins-list- // show #irl-mypins-sheet-}--async function deleteMyPin(id) {- await fetch(`/api/irl/pins?id=${id}&deviceToken=${_deviceToken}`, { method: 'DELETE' });- // re-render the list- // if id === gpsPin?.id, call setLocked(false) to clear local state-}-```--## API changes in `api/irl/pins.js`--Add a branch for `GET /api/irl/pins/mine` **before** the existing GET handler:--```js-if (req.method === 'GET' && req.url?.includes('/mine')) {- const deviceToken = req.query.deviceToken;- if (!deviceToken) return json(res, 400, { error: 'deviceToken required' });- const rows = await sql`- SELECT id, lat, lng, avatar_name, caption, placed_at, expires_at- FROM irl_pins- WHERE device_token = ${deviceToken}- AND (expires_at IS NULL OR expires_at > NOW())- ORDER BY placed_at DESC- LIMIT 20- `;- return json(res, 200, { pins: rows });-}-```--Also add a route in `vercel.json`:-```json-{ "src": "/api/irl/pins/mine", "dest": "/api/irl/pins.js" }-```--## Checklist--- [ ] `GET /api/irl/pins/mine?deviceToken=` endpoint works-- [ ] Route registered in `vercel.json`-- [ ] "My pins" button visible only after GPS initialises-- [ ] Sheet shows all active pins with name, caption, distance, time-- [ ] Trash button deletes pin from DB and removes from list-- [ ] Deleting the currently-pinned avatar also clears local `gpsPin` state (calls `setLocked(false)`)-- [ ] Empty state: "No active pins" message-- [ ] No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl/04-my-pins-management.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl/05-radar-minimap.md b/tasks/irl/05-radar-minimap.mddeleted file mode 100644index 53047da43..000000000--- a/tasks/irl/05-radar-minimap.md+++ /dev/null@@ -1,149 +0,0 @@-# Task: IRL — Radar minimap showing nearby pins by direction--## What to build--A compact radar overlay in the corner of the IRL screen that shows nearby GPS-pinned agents as dots with their distance and compass bearing relative to the user. Think Pokémon Go's nearby tracker, but simpler — a circular radar with the user at center, north up, dots representing agents. Visible only in GPS pin mode.--## Where it lives--`pages/irl.html` — a new `<div id="irl-radar">` fixed to the top-right corner, visible only when `gpsModeActive` is true (add/remove a CSS class from body or the element itself).--## Design--```-┌──────────────┐-│ · │ ← radar circle, ~120px diameter-│ ● │ ← user dot (center)-│ · │ ← nearby agent dot-│ · │-└──────────────┘-```--- Background: `rgba(0,0,0,0.55)` circle with subtle border-- User: white dot at exact center-- Agents: blue dots (`#88bbff`) scaled and positioned by bearing + distance-- Max radar radius = 150m (the `NEARBY_RADIUS`). An agent at 150m sits on the edge.-- Each dot is 8px; on hover shows the agent name in a tooltip-- Compass: faint N/S/E/W text labels at edges (optional, adds polish)--## CSS--```css-#irl-radar {- position: fixed;- top: calc(env(safe-area-inset-top, 0px) + 68px); /* below topbar */- right: 16px;- width: 120px;- height: 120px;- border-radius: 50%;- background: rgba(0,0,0,0.55);- border: 1px solid rgba(255,255,255,0.12);- backdrop-filter: blur(10px);- -webkit-backdrop-filter: blur(10px);- z-index: 8;- display: none; /* shown only in GPS mode */- pointer-events: none;-}-body.gps-mode #irl-radar { display: block; }--.irl-radar-dot {- position: absolute;- width: 8px;- height: 8px;- border-radius: 50%;- background: #88bbff;- transform: translate(-50%, -50%);- pointer-events: auto;- cursor: pointer;- box-shadow: 0 0 6px rgba(136,187,255,0.6);-}-.irl-radar-self {- position: absolute;- top: 50%; left: 50%;- width: 10px; height: 10px;- border-radius: 50%;- background: #fff;- transform: translate(-50%, -50%);- box-shadow: 0 0 8px rgba(255,255,255,0.8);-}-```--## JS changes in `src/irl.js`--Add `updateRadar()` called from `tick()` (only when `gpsModeActive`):--```js-function updateRadar() {- const radar = document.getElementById('irl-radar');- if (!radar || !gpsModeActive) return;-- // Remove old dots (keep .irl-radar-self)- radar.querySelectorAll('.irl-radar-dot').forEach(d => d.remove());-- const R = 60; // radar radius in px (half of 120px container)- const maxDist = NEARBY_RADIUS; // 150m-- for (const pin of nearbyPins) {- if (!pin.group) continue;- // World position relative to user (camera at 0,0,0)- const wx = pin.group.position.x; // east- const wz = pin.group.position.z; // south (positive = south)- const dist = Math.sqrt(wx * wx + wz * wz);- if (dist > maxDist) continue;-- const frac = Math.min(dist / maxDist, 1);- const px = R + (wx / maxDist) * R; // east = right- const py = R + (-wz / maxDist) * R; // north = up (wz negative = north)-- const dot = document.createElement('div');- dot.className = 'irl-radar-dot';- dot.style.left = `${px}px`;- dot.style.top = `${py}px`;- dot.title = `${pin.avatar_name || 'Agent'} · ${pin.distance_m ?? Math.round(dist)}m`;- dot.addEventListener('click', () => openPinSheet(pin));- radar.appendChild(dot);- }-}-```--Add `body.classList.add('gps-mode')` when `gpsModeActive = true` and remove when false.--Add the self-dot HTML inside `#irl-radar` in the HTML:-```html-<div id="irl-radar" aria-hidden="true">- <div class="irl-radar-self"></div>-</div>-```--## Integration points--- `tick()` calls `updateRadar()` after `updateLabels()` — only meaningful when `gpsModeActive && gpsState.ready`-- `setLocked(true)` adds `body.classList.add('gps-mode')`-- `setLocked(false)` removes it-- Clicking a radar dot calls `openPinSheet(pin)` — same function used by the floating labels--## Checklist--- [ ] Radar visible only in GPS pin mode (`body.gps-mode`)-- [ ] Self dot at center-- [ ] Agent dots positioned correctly relative to GPS world space (east=right, north=up)-- [ ] Dots capped to radar edge at max distance-- [ ] Clicking a dot opens the interaction sheet for that pin-- [ ] Radar updates each frame (called from `tick()`)-- [ ] No performance regression — `updateRadar()` is O(n) in `nearbyPins.length` (max 50)-- [ ] Works on mobile (touch `click` events fire on tap)-- [ ] No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl/05-radar-minimap.md"-```--Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.diff --git a/tasks/irl/06-agent-id-from-session.md b/tasks/irl/06-agent-id-from-session.mddeleted file mode 100644index 4aa195641..000000000--- a/tasks/irl/06-agent-id-from-session.md+++ /dev/null@@ -1,79 +0,0 @@-# Task: IRL — Link the placed pin to the session's active agent_id--## What to build--When a user pins their avatar in IRL mode, `savePin()` currently sends `agent_id: undefined` because the session's active agent ID isn't plumbed into `src/irl.js`. Wire the agent ID so that the stored pin carries a real `agent_id`, enabling the "View agent" profile link (task 02) to work for self-placed pins.--## How agents are selected in IRL--The IRL page (`/irl`) inherits the avatar selected in the 3D walk scene. The user picks an avatar via the "Avatar" pill button (`#irl-avatar-btn`), which opens the avatar picker. The current avatar is tracked by `_currentAvatarId` in `src/irl.js` (a string like `"3d-agent-id-or-glb-key"`).--Read `src/irl.js` to find:-1. Where `_currentAvatarId` is set and what format it holds-2. Whether an `agent_id` (UUID) is stored anywhere alongside the GLB URL--## What to change--### If `_currentAvatarId` IS a UUID agent ID--Simply add it to the `savePin` POST body:--```js-// in savePin():-agentId: _currentAvatarId ?? null,-```--### If `_currentAvatarId` is a filename/key (not a UUID)--The avatar URL may encode the agent ID. Check if the avatar URL pattern is `/cdn/<agent-id>/avatar.glb` or similar. If so, extract the UUID:--```js-function agentIdFromUrl(url) {- if (!url) return null;- const m = url.match(/\/agents?\/([0-9a-f-]{36})\//i)- ?? url.match(/\/([0-9a-f-]{36})(?:\/|\.)/i);- return m?.[1] ?? null;-}-```--Pass `agentIdFromUrl(resolveAvatarUrl(_currentAvatarId))` as `agentId` in `savePin`.--### If agent ID comes from a different source--The page URL may carry `?agent=<id>` (set by the avatar picker redirect). Check `new URLSearchParams(location.search).get('agent')` as a fallback.--## Research first--Before writing any code:--```bash-grep -n "_currentAvatarId\|resolveAvatarUrl\|agent_id\|agentId" src/irl.js | head -30-grep -n "avatar-picker\|irl-avatar-btn\|loadAvatar" src/irl.js | head -20-```--Understand what `_currentAvatarId` actually is, then pick the right extraction strategy above.--## Files to touch--- `src/irl.js` — `savePin()` and possibly a new helper `agentIdFromUrl()`--## Checklist--- [ ] `savePin` POST body includes a valid UUID `agentId` when an agent is selected-- [ ] Falls back to `null` gracefully when no agent is selected (anonymous avatar)-- [ ] Verified by inspecting the `irl_pins` table (`agent_id` column populated on new pins)-- [ ] No console errors--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/irl/06-agent-id-from-session.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/task-09-memory-sync.md b/tasks/task-09-memory-sync.mddeleted file mode 100644index 44abbaf1e..000000000--- a/tasks/task-09-memory-sync.md+++ /dev/null@@ -1,82 +0,0 @@-# Task: Multi-Device Memory Sync--## Context--This is the `three.ws` 3D agent platform. Agents have a runtime memory store (`src/agent-memory.js`) that persists to `localStorage` and syncs to a backend API (`api/agent-memory.js`). The sync is one-directional: writes go from the browser to the backend. If a user opens the same agent on a second device or browser, that device has an empty memory — it never pulls from the backend.--## Goal--Make memory sync bidirectional so agents have consistent memory across devices. When an `<agent-3d>` element loads (or becomes active), it should pull the agent's memories from the backend and merge them into the local store.--## Files to Read First--- `src/agent-memory.js` (260 lines) — `AgentMemory` class: `add()`, `query()`, `_scheduleSync()`, localStorage structure-- `api/agent-memory.js` (188 lines) — `GET /api/agent-memory?agent_id=<id>` returns the agent's entries-- `src/element.js` — `<agent-3d>` custom element; find `connectedCallback()` or wherever the memory module is initialized--## What to Build--### Changes to `src/agent-memory.js`--Add a `pull()` method:--```js-async pull(agentId, authToken) {- // Fetch all non-deleted entries from GET /api/agent-memory?agent_id=<agentId>- // For each remote entry:- // - If not in local store: add it (skip _scheduleSync to avoid re-uploading)- // - If in local store and remote updatedAt > local updatedAt: overwrite local- // - If in local store and local is newer: keep local (it will sync up on next push)- // Persist merged state to localStorage-}-```--Conflict resolution: **last-write-wins by `updatedAt` timestamp**. This is simple and correct for the use case (personal agent memory, single user).--Also:-- Ensure every entry has an `updatedAt` field set on `add()` and updated on any modification-- The `_scheduleSync()` push should send `updatedAt` in the request body so the backend stores it--### Changes to `api/agent-memory.js`--- `GET /api/agent-memory` response should include `updated_at` per entry (check if the DB column exists; if not, use `created_at` as fallback)-- `POST /api/agent-memory` should accept and store `updated_at` from the client-- `PUT /api/agent-memory` should update `updated_at`--### Changes to `src/element.js`--In the element's init sequence (after auth is resolved and `agentId` is known), call:--```js-await memory.pull(agentId, authToken)-```--This should happen **before** the first LLM turn, so the agent has its full memory on the first message.--## Constraints--- `pull()` must be idempotent — calling it twice should not duplicate entries-- Do not pull on every message — only on init (when the element connects)-- The pull should be a best-effort background operation: if the network is unavailable, silently skip and use local state-- Do not change the localStorage key structure--## Success Criteria--- Open an agent on Device A, have a conversation (agent remembers the user's name via `remember` tool)-- Open the same agent on Device B — on first load, memory is pulled and the agent knows the user's name-- No duplicate entries after pulling (idempotent)-- Offline devices degrade gracefully (no error thrown, uses cached localStorage)--<!-- 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/task-09-memory-sync.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/task-irl-01-permanent-auth-pins.md b/tasks/task-irl-01-permanent-auth-pins.mddeleted file mode 100644index 736ae246e..000000000--- a/tasks/task-irl-01-permanent-auth-pins.md+++ /dev/null@@ -1,141 +0,0 @@-# IRL Task 01 — Permanent Auth-Linked Pins--## Context--The IRL GPS anchor system (`/api/irl/pins`, `src/irl.js`) already exists and works:-- POST `/api/irl/pins` stores a GPS pin in `irl_pins` table-- GET `/api/irl/pins?lat=&lng=&radius=` returns nearby pins-- DELETE `/api/irl/pins?id=&deviceToken=` removes a pin-- Frontend already calls savePin(), loadNearbyPins(), spawnNearbyPin(), loadPinGLB()-- Table has `user_id`, `agent_id`, `device_token`, `expires_at` columns--**The problem:** Every pin expires in 7 days (`expires_at = NOW() + INTERVAL '7 days'`). Authenticated users should get **permanent** pins (no expiry). Also, the POST endpoint doesn't extract the authenticated user's session — `user_id` is always null. DELETE only works by `device_token`, so you can't delete your own pin from a different device.--## What to build--### 1. Auth linkage in POST `/api/irl/pins.js`--In `api/irl/pins.js`, import `getSessionUser` from `api/_lib/auth.js` (already used in other endpoints — see `api/sniper/strategy.js` for the pattern). In the POST handler:--- Call `getSessionUser(req)` — it returns `{ id, ... }` or null-- If authenticated: set `user_id = session.id`, set `expires_at = NULL` (permanent)-- If anonymous: keep `device_token` from body, keep `expires_at = NOW() + INTERVAL '7 days'`--```js-// pattern to follow from api/sniper/strategy.js-import { getSessionUser } from '../_lib/auth.js';--// in POST handler:-const session = await getSessionUser(req).catch(() => null);-const userId = session?.id ?? null;-const expiresAt = userId ? null : new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString();-```--Then pass `userId` and `expiresAt` into the INSERT:-```sql-INSERT INTO irl_pins (user_id, ..., expires_at)-VALUES (${userId}, ..., ${expiresAt})-```--The table's `expires_at` default is `NOW() + 7 days` — override it explicitly so NULL = permanent.--### 2. Auth DELETE in `/api/irl/pins.js`--Extend the DELETE handler to also allow deletion by authenticated `user_id`. Currently:-```sql-WHERE id = ${id} AND (device_token = ${deviceToken} OR device_token IS NULL)-```--Change to:-```sql-WHERE id = ${id}- AND (- device_token = ${deviceToken ?? ''}- OR user_id = ${userId}- OR device_token IS NULL- )-```--Where `userId` comes from `getSessionUser(req)` (null if not authenticated).--### 3. GET — list my pins endpoint--Add a new query mode: when `req.query.mine === '1'` and the user is authenticated, return all pins belonging to that user (no lat/lng required, no radius filter):--```js-if (req.method === 'GET' && req.query.mine === '1') {- const session = await getSessionUser(req).catch(() => null);- if (!session) return json(res, 401, { error: 'not authenticated' });- const rows = await sql`- SELECT id, lat, lng, heading, avatar_url, avatar_name, caption, placed_at, expires_at- FROM irl_pins- WHERE user_id = ${session.id}- ORDER BY placed_at DESC- LIMIT 100- `;- return json(res, 200, { pins: rows });-}-```--This is what the dashboard management page (Task 02) calls.--### 4. Frontend: send agentId + userId context when saving--In `src/irl.js`, the `savePin()` function currently sends `{ lat, lng, avatarUrl, avatarName, deviceToken }`. Extend it to also send `agentId` from the URL param (already parsed as `avatarIdParam`):--```js-body: JSON.stringify({- lat, lng,- avatarUrl: resolveAvatarUrl(_currentAvatarId),- avatarName: nameEl.textContent,- deviceToken: _deviceToken,- agentId: avatarIdParam || null, // add this line-}),-```--### 5. Expiry display in status message--In `src/irl.js`, the lock button sets a status message. Extend it to show permanence:--Find the `setLocked` function and the status string. After you get a successful `savePin` response, check if the returned `pin.expires_at` is null:--```js-savePin(gpsPin.lat, gpsPin.lng).then(result => {- if (result?.id && gpsPin) {- gpsPin.id = result.id;- const forever = result.permanent; // we'll add this to API response- setStatus(forever ? 'Pinned permanently — others nearby can see you' : 'Pinned for 7 days');- }-});-```--And in the API response from POST, add `permanent: expiresAt === null` to the returned object.--## Files to edit--- `api/irl/pins.js` — auth linkage, permanent expiry, auth DELETE, GET ?mine=1-- `src/irl.js` — send agentId in savePin(), show permanent status--## Definition of done--- Logged-in user POSTs a pin → `user_id` populated, `expires_at` is NULL in DB-- Anonymous user POSTs → `expires_at` is 7 days from now (unchanged)-- Logged-in user can DELETE their pin from a different device (by session, not device_token)-- GET `/api/irl/pins?mine=1` returns all pins for authenticated user-- `savePin()` sends `agentId` in body-- Status message says "Pinned permanently" for auth users-- No regressions to anonymous flow--<!-- AUTO:self-delete-on-complete -->-------## ✅ On completion — delete this file--This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:--```bash-git rm "tasks/task-irl-01-permanent-auth-pins.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/task-irl-02-dashboard-manage.md b/tasks/task-irl-02-dashboard-manage.mddeleted file mode 100644index 52c17a849..000000000--- a/tasks/task-irl-02-dashboard-manage.md+++ /dev/null@@ -1,192 +0,0 @@-# IRL Task 02 — Dashboard: Manage Your Placed Pins From Anywhere--## Context--The IRL GPS system (`/api/irl/pins`, `src/irl.js`) lets users anchor their 3D agent avatar at a real-world GPS location. After Task 01, authenticated users have permanent pins linked to their `user_id`, deletable by session auth. `GET /api/irl/pins?mine=1` returns all pins for the authenticated user.--**The missing piece:** There is no way to see or manage your placed pins from a non-IRL context. If you're in a different city, you can't see where you're pinned or remove old pins without physically going back.--## What to build--### New dashboard page: `/dashboard/irl-placements`--Create a full dashboard page at `/src/dashboard-next/pages/irl-placements.js` and register it.--**Layout** (follow the patterns in `src/dashboard-next/pages/sniper.js` and `src/dashboard-next/pages/copy.js`):--```-┌─────────────────────────────────────────────────────┐-│ My Placed Avatars + Place new ↗ │-├─────────────────────────────────────────────────────┤-│ [Avatar img] Agent Name │-│ 📍 New York, NY · 2.3km away │-│ Placed 3 hours ago · Permanent │-│ [Edit caption] [Remove pin] │-├─────────────────────────────────────────────────────┤-│ [Avatar img] Agent Name │-│ 📍 37.7749°N, 122.4194°W │-│ Placed 2 days ago · Expires in 5d │-│ [Edit caption] [Remove pin] │-└─────────────────────────────────────────────────────┘-```--Empty state: "You haven't placed any avatars yet. Open IRL, enable camera, and use the Lock button to pin yourself to a real-world location." With a CTA button → `/irl`.--### Implementation--**1. Fetch pins**--```js-async function loadMyPins() {- const r = await fetch('/api/irl/pins?mine=1');- if (!r.ok) { /* show error state */ return; }- const { pins } = await r.json();- render(pins);-}-```--**2. Reverse-geocode display**--For each pin, show human-readable location. Use the browser Nominatim (OpenStreetMap) API — it's free, no key needed:--```js-async function reverseGeocode(lat, lng) {- try {- const r = await fetch(- `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json`,- { headers: { 'User-Agent': 'three.ws/1.0' } }- );- const d = await r.json();- return d.address?.city || d.address?.town || d.address?.village- || d.address?.county || d.display_name?.split(',')[0] || null;- } catch { return null; }-}-```--Show the city name if found, otherwise show `${lat.toFixed(5)}°, ${lng.toFixed(5)}°`.--**3. Distance from current location**--If `navigator.geolocation` is available, get the user's current position once and show distance to each pin ("2.3 km away"). Use the haversine formula (copy from `api/irl/pins.js` — it's a one-liner).--**4. Expiry display**--- `expires_at === null` → badge: `Permanent`-- `expires_at` in future → `Expires in Xd Xh`-- `expires_at` in past → `Expired` (show faded, offer cleanup)--**5. Edit caption**--Inline: clicking "Edit caption" shows a text input pre-filled with current caption. On save, PATCH `/api/irl/pins` (see below for API addition).--**6. Remove pin**--```js-async function removePin(id) {- const r = await fetch(`/api/irl/pins?id=${id}`, { method: 'DELETE' });- if (r.ok) { /* remove card from DOM */ }- else { /* show error */ }-}-```--(DELETE by session auth — implemented in Task 01)--**7. "Place new" button**--Top-right link → `/irl` (opens IRL experience). If the user already has a pin, show "Update placement" instead.--**8. "View in IRL" link per pin**--Each card has a link: `/irl?highlight=${pin.id}` — when IRL opens with `?highlight=`, it centers the camera on that pin's GPS location and highlights it. Add this param handling to `src/irl.js`:--```js-const highlightId = params.get('highlight');-// after loadNearbyPins(), if highlightId matches a pin, flash its label-```--### API addition: PATCH for caption edit--In `api/irl/pins.js`, add a PATCH handler:--```js-if (req.method === 'PATCH') {- const session = await getSessionUser(req).catch(() => null);- if (!session) return json(res, 401, { error: 'not authenticated' });- const { id, caption } = req.body ?? {};- if (!id) return json(res, 400, { error: 'id required' });- const [row] = await sql`- UPDATE irl_pins SET caption = ${caption ?? null}- WHERE id = ${id} AND user_id = ${session.id}- RETURNING id, caption- `;- if (!row) return json(res, 404, { error: 'not found' });- return json(res, 200, { pin: row });-}-```--### Register in nav + router--In `src/dashboard-next/nav.js`, add to the NAV array (in the "Presence" or "Monetize" group — pick whichever fits):--```js-{ path: '/dashboard/irl-placements', label: 'IRL Placements', icon: 'pin', group: 'Presence', tags: ['irl', 'ar', 'gps', 'pin', 'place', 'avatar', 'location'] },-```--Add the `pin` icon to ICONS:-```js-pin: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2a5 5 0 015 5c0 3.5-5 11-5 11S5 10.5 5 7a5 5 0 015-5z"/><circle cx="10" cy="7" r="1.8"/></svg>',-```--In `src/dashboard-next/router.js` (or wherever pages are registered), add:--```js-'/dashboard/irl-placements': () => import('./pages/irl-placements.js'),-```--In `vercel.json`, add under `functions`:-```json-"api/irl/pins.js": {- "maxDuration": 15-}-```--(The route `/api/irl/pins` → `/api/irl/pins.js` already exists in vercel.json routes — just add the function config.)--### CSS--Follow the card style from `src/dashboard-next/pages/sniper.js` (`.sn-card` pattern). Create equivalent `.irl-card`, `.irl-card-head`, `.irl-badge` styles. Keep it minimal — 50 lines of CSS max.--## Files to create/edit--- **Create** `src/dashboard-next/pages/irl-placements.js`-- `api/irl/pins.js` — add PATCH handler, add CORS for PATCH-- `src/dashboard-next/nav.js` — add nav entry + pin icon-- `src/dashboard-next/router.js` — register route-- `src/irl.js` — handle `?highlight=` param-- `vercel.json` — add function config for `api/irl/pins.js`-- `data/changelog.json` — add changelog entry (improvement, link: /dashboard/irl-placements)--## Definition of done--- `/dashboard/irl-placements` loads and shows your placed pins (or empty state)-- Each card shows location name (reverse-geocoded), distance from current position, expiry status, caption-- Edit caption works inline with save/cancel-- Remove pin deletes from DB and removes card from DOM-- "Place new" / "Update placement" button navigates to /irl-- `?highlight=` in IRL flashes the matching pin label-- PATCH `/api/irl/pins` updates caption by session auth-- Nav entry visible in dashboard sidebar--<!-- 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/task-irl-02-dashboard-manage.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/task-irl-03-compass-heading.md b/tasks/task-irl-03-compass-heading.mddeleted file mode 100644index 8c93e5f7e..000000000--- a/tasks/task-irl-03-compass-heading.md+++ /dev/null@@ -1,147 +0,0 @@-# IRL Task 03 — Compass Heading: Avatars Face the Right Direction--## Context--The IRL GPS pin system (`/api/irl/pins`, `src/irl.js`) stores a `heading` column (float, degrees 0–360) in `irl_pins`, but:--1. The frontend `savePin()` in `src/irl.js` **never sends a heading** — it's always 0 in the DB-2. `spawnNearbyPin()` places foreign avatars in the scene but **never rotates them** based on heading-3. The device compass (`DeviceOrientationEvent`) is already wired in `src/irl.js` (see `onDeviceOrientation`, `devOrientBaseAlpha`, `devOrientAlpha`) but its value is only used for AR camera control — not captured at pin time--The result: all foreign avatars face the same direction (Three.js default, Z- axis) regardless of which way they were facing when pinned.--## What to build--### 1. Capture heading at pin time (`src/irl.js`)--Find the `devOrientAlpha` variable (already maintained by `onDeviceOrientation`). This is the device's compass heading in degrees (0 = north, clockwise). When `savePin()` is called (inside the lock button handler), pass the current heading:--```js-// In the lockBtn click / setLocked(true) handler, find where savePin is called:-savePin(gpsPin.lat, gpsPin.lng, devOrientAlpha ?? 0)- .then(result => { ... });-```--Update `savePin()` to accept and send heading:--```js-async function savePin(lat, lng, heading = 0) {- try {- const r = await fetch('/api/irl/pins', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- lat, lng,- heading: Math.round(heading) % 360, // add this- avatarUrl: resolveAvatarUrl(_currentAvatarId),- avatarName: nameEl.textContent,- deviceToken: _deviceToken,- agentId: avatarIdParam || null,- }),- });- ...- }-}-```--The API already accepts `heading` in the POST body and stores it — no API change needed.--### 2. Rotate foreign avatars in the scene (`src/irl.js`)--In `spawnNearbyPin(pin)`, after setting `g.position`, rotate the group to face the stored heading.--GPS heading 0 = north. In Three.js the scene's Z- axis = "forward" (camera looks down -Z by default). The mapping from compass heading to Three.js Y rotation is:--```-threeRotationY = -(heading * Math.PI / 180)-```--(Negate because Three.js rotates counter-clockwise, compass is clockwise.)--Add this after `g.position.set(...)`:--```js-if (pin.heading != null) {- g.rotation.y = -(pin.heading * Math.PI / 180);-}-```--This applies to the whole group — beacon placeholder and loaded GLB alike — so both face the right direction from the moment they appear.--### 3. Re-rotate when GLB loads (`src/irl.js`)--In `loadPinGLB(pin)`, after the model is added to the group, re-apply the rotation because the GLB loader may reset it. Find the end of `loadPinGLB`:--```js-// After: pin.group.add(model); pin.glbLoaded = true;-if (pin.heading != null) {- pin.group.rotation.y = -(pin.heading * Math.PI / 180);-}-```--### 4. Live heading updates for own avatar (optional but high quality)--When the user is in GPS pin mode (`gpsModeActive === true`) and walking, their own avatar already faces the direction of movement. But when **locked** (avatar stationary, camera orbiting), the avatar should face the stored heading rather than defaulting to whatever it was last walking toward.--In `setLocked(next)`, when `next === true` and `gpsPin` exists:--```js-if (next && avatar && devOrientAlpha != null) {- avatar.rotation.y = -(devOrientAlpha * Math.PI / 180);-}-```--This snaps the avatar to face north-relative at lock time, consistent with what gets stored.--### 5. Show heading in IRL placement status--In the status message shown after locking, include the compass direction:--```js-function compassLabel(deg) {- const dirs = ['N','NE','E','SE','S','SW','W','NW'];- return dirs[Math.round(((deg % 360) + 360) % 360 / 45) % 8];-}--// In savePin().then():-const dir = compassLabel(devOrientAlpha ?? 0);-setStatus(`Pinned facing ${dir} — others nearby can see you`);-```--### 6. Dashboard card (Task 02 follow-up)--In `src/dashboard-next/pages/irl-placements.js` (built in Task 02), each pin card should show the facing direction using the same `compassLabel` function. Display it as a small badge next to the location: `📍 New York · Facing NE`.--Export `compassLabel` from a shared util or inline it in both files (it's 3 lines).--## Files to edit--- `src/irl.js` — capture heading in savePin(), rotate groups in spawnNearbyPin() + loadPinGLB(), snap avatar on lock--## Files that may need a minor touch--- `src/dashboard-next/pages/irl-placements.js` (Task 02) — show compass direction in pin card--## Definition of done--- Locking your avatar captures the current compass heading and sends it to the API-- Foreign avatars spawn facing their stored heading direction (not always Z-)-- After GLB loads, heading rotation is preserved-- When you lock your own avatar, it snaps to face the stored heading-- Status message shows compass direction (e.g. "Pinned facing NE")-- Dashboard pin cards show facing direction badge-- No regressions: anonymous flow, unlocking, and AR camera orbit all still work--<!-- 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/task-irl-03-compass-heading.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/verify-nvidia-trellis-artifact-fix.md b/tasks/verify-nvidia-trellis-artifact-fix.mddeleted file mode 100644index 8a290f27a..000000000--- a/tasks/verify-nvidia-trellis-artifact-fix.md+++ /dev/null@@ -1,131 +0,0 @@-# Task: Verify + Harden NVIDIA TRELLIS Artifact Extraction--## Background--Production logs showed the free text→3D lane failing on every forge seed tick with:--```-[nvidia] sync 200 but no GLB artifact — json keys=["artifacts"]-```--This means NVIDIA TRELLIS returned HTTP 200 with `{ "artifacts": [...] }` but the items-didn't match the previously documented shape `{ base64: "..." }`.--A fix was deployed that extends `extractGlbBase64()` in `api/_providers/nvidia.js` to also:-1. Handle URL-based artifacts — if `artifact[0].url` is set, fetch and buffer the CDN file-2. Handle direct string artifacts in the array (without an object wrapper)-3. Emit a better diagnostic: now logs `json keys=[...] artifact[0]=[...]` so the actual- schema is visible in the first failure after any future NVIDIA API change--The improved diagnostic means if NVIDIA changes the schema again, the next failure log will-show the new artifact[0] keys immediately, making the fix obvious without guessing.--## What to verify after the next deploy--### 1. Check that forge seed is succeeding--After deploying, wait for 2–3 cron ticks (2–3 minutes). In Vercel logs, look for:--```-[forge-seed] new_job: { ok: true, sync: true, glb_url: "https://..." }-```--or--```-[forge-seed] new_job: { ok: true, job_id: "nvcf-..." }-```--Either means the NVIDIA lane is working. If you still see `[nvidia] sync 200 but no GLB-artifact`, the next log line will now include `artifact[0]=[...]` — that tells you exactly-what keys NVIDIA is returning so the extraction can be patched precisely.--### 2. Live probe (if still broken after deploy)--Run a direct test against the NVIDIA endpoint to see the raw response:--```bash-node - <<'EOF'-const key = process.env.NVIDIA_API_KEY;-const res = await fetch('https://ai.api.nvidia.com/v1/genai/microsoft/trellis', {- method: 'POST',- headers: {- authorization: `Bearer ${key}`,- accept: 'application/json',- 'content-type': 'application/json',- },- body: JSON.stringify({- mode: 'text',- prompt: 'a small red cube, studio lighting',- ss_sampling_steps: 10,- slat_sampling_steps: 10,- output_format: 'glb',- }),- signal: AbortSignal.timeout(60_000),-});-console.log('status:', res.status);-console.log('content-type:', res.headers.get('content-type'));-const body = await res.json().catch(() => res.text());-if (typeof body === 'object') {- console.log('top keys:', Object.keys(body));- if (Array.isArray(body.artifacts) && body.artifacts.length > 0) {- const a0 = body.artifacts[0];- console.log('artifact[0] type:', typeof a0);- if (typeof a0 === 'object') {- console.log('artifact[0] keys:', Object.keys(a0));- // Show value type + first 80 chars of each key- for (const k of Object.keys(a0)) {- const v = a0[k];- console.log(` ${k}: ${typeof v} ${String(v).slice(0, 80)}`);- }- } else {- console.log('artifact[0] value:', String(a0).slice(0, 80));- }- }-} else {- console.log('body (first 200):', body.slice(0, 200));-}-EOF-```--Run with `NVIDIA_API_KEY=$(vercel env pull --yes /dev/stderr 2>&1 | grep NVIDIA | awk -F= '{print $2}') node ...`-or pull the key from `vercel env pull`.--### 3. Update the protocol comment in `api/_providers/nvidia.js`--The file header (lines 25–37) currently documents the artifact shape as:-```-result body.artifacts[0].base64 — base64-encoded .glb-```--After confirming what NVIDIA actually returns, update this to reflect the real shape.-For example, if it's now URL-based:-```-result body.artifacts[0].url — CDN URL to a .glb; fetched + buffered by extractGlbBase64-```--## Key files--- `api/_providers/nvidia.js` — `extractGlbBase64()` (line ~124), protocol comment (line ~25)-- `api/cron/forge-seed-cron.js` — the cron that exercises this path every 60s-- `tasks/nvidia-nim/probes/trellis.md` — prior probe transcripts; add a new entry with today's findings--## Acceptance criteria--- Vercel logs show at least one `ok: true` forge seed result with a real `glb_url`-- The protocol comment in `nvidia.js` accurately describes the current artifact shape-- `tasks/nvidia-nim/probes/trellis.md` updated with the confirmed schema and date--<!-- 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/verify-nvidia-trellis-artifact-fix.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/wire-pumpfun-bot-url.md b/tasks/wire-pumpfun-bot-url.mddeleted file mode 100644index 14b09b4ed..000000000--- a/tasks/wire-pumpfun-bot-url.md+++ /dev/null@@ -1,20 +0,0 @@-# Wire PUMPFUN_BOT_URL → moved--This task is now the canonical, fully-specified task at-[tasks/pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md](pumpfun-launchpad-100/08-wire-pumpfun-bot-url.md)-— part of the **Pump.fun Launchpad → 100%** plan-([tasks/pumpfun-launchpad-100/README.md](pumpfun-launchpad-100/README.md)).--<!-- 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/wire-pumpfun-bot-url.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.