Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
IRL AR world-anchoring, camera-aware gaze, reliable tap, and owner calibration
nirholas4a76781e1ae2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 277d463af..4f5d27b7d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,15 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-06-17++- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`+- **iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk** — iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated. (`/irl`) `[improvement]`+- **IRL agents now materialize as you walk up to them** — On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going. (`/irl`) `[fix, improvement]`+- **IRL agents turn to look at you as you move around them** — On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you. (`/irl`) `[improvement]`+- **Place your IRL agent on the real floor with AR anchoring** — On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button. (`/irl`) `[feature]`+- **Tapping an IRL agent is now reliable — hit the body, not just the tiny label** — On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap. (`/irl`) `[improvement]`+## 2026-06-16- **Agent Activity — Oracle conviction in real time** (`/activity`) — The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex fca59c569..7168cceef 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -196,6 +196,14 @@ export const limits = {// `authIp` budget shared by on-chain buy/sell/launch actions. Iterating in// the launch wizard would otherwise lock the user out of trading for 10 min.pumpMetaIp: (ip) => getLimiter('pump:meta:ip', { limit: 60, window: '10 m' }).limit(ip),+ // IRL write buckets — /irl places real 3D agents at GPS spots and logs visitor+ // interactions, all from public (often anonymous) callers, so the write paths+ // need their own ceilings or a script could carpet a map with pins, inflate+ // view counts, or flood an owner's interaction inbox.+ // · irlPinIp — create/edit/delete a placement (heavier; placing dozens is abuse)+ // · irlInteractIp — log a tap/view/message (lighter; legit viewing fans out)+ irlPinIp: (ip) => getLimiter('irl:pin:ip', { limit: 20, window: '10 m' }).limit(ip),+ irlInteractIp: (ip) => getLimiter('irl:interact:ip', { limit: 60, window: '1 m' }).limit(ip),// Same-origin image proxy (api/img). A token-cloud view loads dozens of// thumbnails at once, so the ceiling is generous — but bounded so the proxy// can't be turned into an open bandwidth relay. Responses are CDN-cached.diff --git a/api/irl/agent-card.js b/api/irl/agent-card.jsindex 2a45d5156..2ae28a9c6 100644--- a/api/irl/agent-card.js+++ b/api/irl/agent-card.js@@ -1,20 +1,36 @@/**- * IRL Agent Card — the public profile shown when a viewer taps a 3D agent+ * IRL Agent Card (v2) — the rich profile shown when a viewer taps a 3D agent* placed in the real world.*- * GET /api/irl/agent-card?id=<agentId> resolve by agent identity id- * GET /api/irl/agent-card?pin=<pinId> resolve via the pin's agent_id+ * GET /api/irl/agent-card?agent_id=<uuid> resolve by agent identity id+ * GET /api/irl/agent-card?id=<uuid> alias of agent_id+ * GET /api/irl/agent-card?pin=<pinId> resolve via the pin's agent_id*- * Returns a compact, public-safe card the AR popup renders inline:- * { id, name, description, thumbnail, home_url, skills,- * services: [{ slug, name, description, price_usdc, network }],- * reputation: { chats, services, registered, onchain, score },- * x402_endpoint }+ * One server-side fan-out — agent record + on-chain Solana reputation + the+ * agent's paid x402 services — merged into a single payload so the camera popup+ * makes ONE call (instead of three round-trips from a phone on cellular) and the+ * card renders instantly. Public, IP rate-limited, Redis + CDN cached.+ *+ * Reputation is derived from the real Solana attestation system+ * (solana_attestations / threews.feedback|validation|accept.v1) — the same raw+ * aggregates /api/agents/solana-reputation exposes — but here we DERIVE a tier+ * and a 0–100 score server-side so the client renders a badge without+ * re-implementing the formula. A reputation-query failure must never fail the+ * card: it degrades to { available:false } and the service menu still renders.+ *+ * Services note: "services with x402 prices" are the agent's hosted paid+ * endpoints in `agent_paid_services` (each has a real USDC price, a network, and+ * a three.ws-hosted x402 paywall at /api/x402/service/<slug>). This is the only+ * service table with a per-service x402 endpoint — `agent_skill_prices` is a+ * separate Solana-Pay skill-purchase rail with no hosted endpoint, so it is not+ * what a "tap → pay this service" card should surface.*- * Aggregates agent_identities + agent_paid_services into one cheap, cached- * payload so the camera popup stays instant. Public, IP rate-limited, Redis +- * CDN cached. Falls back to the pin's own avatar_name/x402_endpoint when a pin- * has no linked agent (anonymous placements still get a usable card).+ * { agent: { id, name, bio, thumbnail_url, profile_url },+ * reputation: { asset, score, tier, attestation_count, unique_attesters,+ * tasks_accepted, available },+ * services: [{ skill, name, description, price_usd, currency, chain,+ * x402_endpoint }],+ * x402_endpoint }*/import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';@@ -22,23 +38,89 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';import { publicUrl } from '../_lib/r2.js';import { getRedis } from '../_lib/redis.js';-import { atomicsToUsdc } from '../_lib/agent-paid-services.js';--const CACHE_TTL_S = 60;--// A small, monotonic reputation score (0–100) from public signals so the popup-// can show a single number without an on-chain round-trip. Chat volume is the-// dominant signal; registration and offering paid services add trust.-function reputationScore({ chats, services, registered }) {- const chatPts = Math.min(70, Math.round(Math.log10(Math.max(1, chats)) * 28));- const svcPts = Math.min(18, services * 6);- const regPts = registered ? 12 : 0;- return Math.min(100, chatPts + svcPts + regPts);+import { atomicsToUsdc, serviceResourceUrl } from '../_lib/agent-paid-services.js';++const CACHE_TTL_S = 30;+const MAX_SERVICES = 6;+const BIO_MAX = 280;++const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));++/**+ * Derive a 0–100 reputation score and a tier from the raw on-chain aggregates.+ *+ * Weights (documented, explicit):+ * 60% feedback quality — average star rating (1–5) normalised to 0–1+ * 20% attester breadth — unique attesters, log-scaled, saturating near ~50+ * 20% validation pass rate — passed / (passed + failed) glTF/schema checks+ *+ * Tiers: >=85 elite · >=60 trusted · >=30 emerging · else new+ */+function deriveReputation({ fbTotal, scoreAvg, uniqueAttesters, valPassed, valFailed, tasksAccepted }) {+ // 1–5 stars → 0–1 (a 1-star floor contributes nothing; a 5-star avg is full).+ const scoreNorm = fbTotal > 0 ? clamp((scoreAvg - 1) / 4, 0, 1) : 0;+ // log10(1+n)/log10(51): 0 attesters → 0, ~50 attesters → ~1.+ const attesterNorm = clamp(Math.log10(1 + uniqueAttesters) / Math.log10(51), 0, 1);+ const valTotal = valPassed + valFailed;+ const valPassRate = valTotal > 0 ? valPassed / valTotal : 0;++ const score = clamp(Math.round(60 * scoreNorm + 20 * attesterNorm + 20 * valPassRate), 0, 100);+ const tier = score >= 85 ? 'elite' : score >= 60 ? 'trusted' : score >= 30 ? 'emerging' : 'new';++ return {+ score,+ tier,+ // "attestations" the viewer can point to: feedback left + validations passed.+ attestation_count: fbTotal + valPassed,+ unique_attesters: uniqueAttesters,+ tasks_accepted: tasksAccepted,+ };+}++/**+ * Fetch the on-chain reputation aggregates for an agent's Solana asset in a+ * single round-trip. Returns null on any failure (missing tables, RPC, etc.) so+ * the caller can degrade to { available:false } without failing the card.+ */+async function fetchReputation(asset, network) {+ const [row] = await sql`+ WITH fb AS (+ SELECT (payload->>'score')::int AS score, attester+ FROM solana_attestations+ WHERE agent_asset = ${asset} AND network = ${network}+ AND kind = 'threews.feedback.v1' AND revoked = false+ ),+ val AS (+ SELECT+ count(*) FILTER (WHERE (payload->>'passed')::bool) AS passed,+ count(*) FILTER (WHERE NOT (payload->>'passed')::bool) AS failed+ FROM solana_attestations+ WHERE agent_asset = ${asset} AND network = ${network}+ AND kind = 'threews.validation.v1' AND revoked = false+ )+ SELECT+ (SELECT count(*)::int FROM fb) AS fb_total,+ (SELECT coalesce(avg(score), 0)::float FROM fb) AS score_avg,+ (SELECT count(DISTINCT attester)::int FROM fb) AS unique_attesters,+ (SELECT coalesce(passed, 0)::int FROM val) AS val_passed,+ (SELECT coalesce(failed, 0)::int FROM val) AS val_failed,+ (SELECT count(*) FILTER (WHERE kind = 'threews.accept.v1' AND verified)::int+ FROM solana_attestations+ WHERE agent_asset = ${asset} AND network = ${network}) AS tasks_accepted+ `;+ return deriveReputation({+ fbTotal: row.fb_total,+ scoreAvg: row.score_avg,+ uniqueAttesters: row.unique_attesters,+ valPassed: row.val_passed,+ valFailed: row.val_failed,+ tasksAccepted: row.tasks_accepted,+ });}async function buildCard(agentId, fallback = {}) {const [agent] = await sql`- SELECT i.id, i.name, i.description, i.skills, i.home_url, i.chat_count, i.meta,+ SELECT i.id, i.name, i.description, i.home_url, i.meta,a.thumbnail_key AS avatar_thumbnail_key,a.visibility AS avatar_visibilityFROM agent_identities i@@ -49,41 +131,58 @@ async function buildCard(agentId, fallback = {}) {if (!agent) return null;+ const meta = agent.meta || {};+ // Solana asset + the network it was registered on (register flow stamps both).+ const asset =+ meta.sol_mint_address || meta.onchain?.sol_asset || meta.solana_asset || null;+ const network =+ meta.network || meta.onchain?.network || 'mainnet';++ // Reputation — degrade gracefully. No asset → "no on-chain reputation yet".+ let reputation;+ if (!asset) {+ reputation = { asset: null, available: false };+ } else {+ try {+ const rep = await fetchReputation(asset, network);+ reputation = { asset, available: true, ...rep };+ } catch (err) {+ console.warn('[irl/agent-card] reputation query failed, degrading:', err?.message);+ reputation = { asset, available: false, degraded: true };+ }+ }++ // price_atomics is text holding a bigint; ::numeric so ORDER BY sorts by value+ // (cheapest "try me" service first), not lexicographically.const services = await sql`SELECT slug, name, description, price_atomics, networkFROM agent_paid_servicesWHERE agent_id = ${agentId} AND archived_at IS NULL- ORDER BY created_at DESC- LIMIT 8+ ORDER BY price_atomics::numeric ASC+ LIMIT ${MAX_SERVICES}`.catch(() => []);- const meta = agent.meta || {};- const onchain = meta.onchain || null;- const registered = !!(onchain || meta.sol_mint_address || meta.erc8004_agent_id);- const thumbPub = agent.avatar_visibility === 'public' || agent.avatar_visibility === 'unlisted';- const chats = Number(agent.chat_count) || 0;+ const thumbPub = agent.avatar_visibility === 'public' || agent.avatar_visibility === 'unlisted';+ const bio = agent.description ? String(agent.description).trim().slice(0, BIO_MAX) : null;return {- id: agent.id,- name: agent.name || fallback.name || 'Agent',- description: agent.description || fallback.description || null,- thumbnail: agent.avatar_thumbnail_key && thumbPub ? publicUrl(agent.avatar_thumbnail_key) : null,- home_url: agent.home_url || `/agents/${agent.id}`,- skills: Array.isArray(agent.skills) ? agent.skills.slice(0, 12) : [],+ agent: {+ id: agent.id,+ name: agent.name || fallback.name || 'Agent',+ bio: bio || fallback.description || null,+ thumbnail_url: agent.avatar_thumbnail_key && thumbPub ? publicUrl(agent.avatar_thumbnail_key) : null,+ profile_url: agent.home_url || `/agents/${agent.id}`,+ },+ reputation,services: services.map((s) => ({- slug: s.slug,- name: s.name,- description: s.description || null,- price_usdc: atomicsToUsdc(s.price_atomics),- network: s.network || 'base',+ skill: s.slug,+ name: s.name,+ description: s.description || null,+ price_usd: atomicsToUsdc(s.price_atomics),+ currency: 'USDC', // paid services settle in USDC+ chain: s.network || 'base',+ x402_endpoint: serviceResourceUrl(s.slug),})),- reputation: {- chats,- services: services.length,- registered,- onchain: onchain ? { network: onchain.network, asset: onchain.sol_asset || null } : null,- score: reputationScore({ chats, services: services.length, registered }),- },x402_endpoint: fallback.x402_endpoint || null,};}@@ -95,16 +194,36 @@ export default wrap(async (req, res) => {const rl = await limits.publicIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;- const idParam = (p.get('id') || '').trim();+ const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const idParam = (p.get('agent_id') || p.get('id') || '').trim();const pinParam = (p.get('pin') || '').trim();if (!idParam && !pinParam) {- return error(res, 400, 'validation_error', 'id or pin is required');+ return error(res, 400, 'validation_error', 'agent_id or pin is required');}- let agentId = idParam || null;+ let agentId = idParam || null;let fallback = {};+ const fromPin = !idParam && !!pinParam;++ // A minimal card for an anonymous pin (no linked agent) or a pin whose linked+ // agent is private/deleted — the pin is real and visible, so still render+ // something usable rather than 404-ing the tap.+ const anonCard = () => ({+ card: {+ agent: {+ id: null,+ name: fallback.name || 'Agent',+ bio: fallback.description || null,+ thumbnail_url: null,+ profile_url: null,+ },+ reputation: { asset: null, available: false },+ services: [],+ x402_endpoint: fallback.x402_endpoint || null,+ anonymous: true,+ },+ });// Resolve the linked agent (and an anonymous-pin fallback) from a pin id.if (!agentId && pinParam) {@@ -123,7 +242,7 @@ export default wrap(async (req, res) => {};}- const cacheKey = agentId ? `irlcard:${agentId}` : null;+ const cacheKey = agentId ? `irlcard:v2:${agentId}` : null;const redis = cacheKey ? await getRedis() : null;if (redis && cacheKey) {@@ -133,37 +252,30 @@ export default wrap(async (req, res) => {res.setHeader('X-Cache', 'HIT');// The pin-derived x402 endpoint isn't part of the cached identity card.if (fallback.x402_endpoint && !cached.x402_endpoint) cached.x402_endpoint = fallback.x402_endpoint;- return json(res, 200, { card: cached }, { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=300' });+ return json(res, 200, { card: cached }, { 'Cache-Control': 'public, max-age=30, stale-while-revalidate=120' });}} catch { /* cache miss */ }}// No linked agent — return the anonymous pin's own minimal card.if (!agentId) {- return json(res, 200, {- card: {- id: null,- name: fallback.name || 'Agent',- description: fallback.description || null,- thumbnail: null,- home_url: null,- skills: [],- services: [],- reputation: { chats: 0, services: 0, registered: false, onchain: null, score: 0 },- x402_endpoint: fallback.x402_endpoint || null,- anonymous: true,- },- }, { 'Cache-Control': 'public, max-age=30' });+ return json(res, 200, anonCard(), { 'Cache-Control': 'public, max-age=30' });}const card = await buildCard(agentId, fallback);- if (!card) return error(res, 404, 'not_found', 'agent not found');+ if (!card) {+ // Pin → private/deleted agent: degrade to the pin's own card. Explicit+ // agent_id → genuine 404.+ if (fromPin) return json(res, 200, anonCard(), { 'Cache-Control': 'public, max-age=30' });+ return error(res, 404, 'not_found', 'agent not found');+ }if (redis && cacheKey) {- // Cache the identity portion only; the per-pin x402 endpoint is merged per request.- const { x402_endpoint, ...identity } = card;- redis.set(cacheKey, identity, { ex: CACHE_TTL_S }).catch(() => {});+ // Cache the identity+reputation+services portion; the per-pin x402 endpoint+ // is pin-specific and merged per request.+ const { x402_endpoint, ...cacheable } = card;+ redis.set(cacheKey, cacheable, { ex: CACHE_TTL_S }).catch(() => {});}- return json(res, 200, { card }, { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=300' });+ return json(res, 200, { card }, { 'Cache-Control': 'public, max-age=30, stale-while-revalidate=120' });});diff --git a/api/irl/agent-summary.js b/api/irl/agent-summary.jsnew file mode 100644index 000000000..6647528d3--- /dev/null+++ b/api/irl/agent-summary.js@@ -0,0 +1,83 @@+/**+ * IRL Agent Summary — one round-trip the owner dashboard (C1) paints from.+ *+ * GET /api/irl/agent-summary?mine=1 (auth required)+ * Returns one row per owned pin, joined to its agent identity and derived+ * activity, so the overview card renders without N blocking calls. Balance is+ * hydrated separately (per-agent /api/agents/:id/solana) so first paint is fast.+ *+ * Returns { agents: [ {+ * pin_id, agent_id, lat, lng, heading, caption, avatar_url, avatar_name,+ * placed_at, expires_at, view_count, agent_name, solana_address,+ * interaction_count, last_interaction_at, status+ * } ] }+ *+ * `status` is derived: 'expired' (expires_at passed) · 'online' (an interaction+ * touched the pin in the last 5 min — proxy until D1/C4 write last_seen_at) ·+ * 'visible' (live, no recent activity). Degrades to 0 / null when the+ * irl_interactions table (C4) isn't created yet — never 500s.+ */++import { cors, json, wrap } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';++const ONLINE_WINDOW_MS = 5 * 60 * 1000;++export default wrap(async (req, res) => {+ cors(req, res, { methods: ['GET', 'OPTIONS'] });+ if (req.method === 'OPTIONS') return res.end();+ if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' });++ const session = await getSessionUser(req).catch(() => null);+ if (!session) return json(res, 401, { error: 'not authenticated' });++ // Table-existence guards so a fresh DB (or pre-C4 deploy) degrades instead of 500ing.+ const [reg] = await sql`+ SELECT to_regclass('irl_pins') IS NOT NULL AS has_pins,+ to_regclass('irl_interactions') IS NOT NULL AS has_ix+ `;+ if (!reg?.has_pins) return json(res, 200, { agents: [] });++ // Join interaction activity only when that table exists yet (C4). The two+ // query forms are explicit because Neon's driver doesn't splice sql fragments.+ const rows = reg.has_ix+ ? await sql`+ SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,+ p.avatar_url, p.avatar_name, p.placed_at, p.expires_at, p.view_count,+ a.name AS agent_name,+ a.meta->>'solana_address' AS solana_address,+ COALESCE(ix.total, 0)::int AS interaction_count,+ ix.last_at AS last_interaction_at+ FROM irl_pins p+ LEFT JOIN agent_identities a ON a.id = p.agent_id AND a.deleted_at IS NULL+ LEFT JOIN (+ SELECT pin_id, COUNT(*)::int AS total, MAX(created_at) AS last_at+ FROM irl_interactions GROUP BY pin_id+ ) ix ON ix.pin_id = p.id+ WHERE p.user_id = ${session.id}+ ORDER BY p.placed_at DESC+ LIMIT 100`+ : await sql`+ SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,+ p.avatar_url, p.avatar_name, p.placed_at, p.expires_at, p.view_count,+ a.name AS agent_name,+ a.meta->>'solana_address' AS solana_address,+ 0 AS interaction_count,+ NULL AS last_interaction_at+ FROM irl_pins p+ LEFT JOIN agent_identities a ON a.id = p.agent_id AND a.deleted_at IS NULL+ WHERE p.user_id = ${session.id}+ ORDER BY p.placed_at DESC+ LIMIT 100`;++ const now = Date.now();+ const agents = rows.map((r) => {+ const expired = r.expires_at && new Date(r.expires_at).getTime() <= now;+ const lastMs = r.last_interaction_at ? new Date(r.last_interaction_at).getTime() : 0;+ const online = !expired && lastMs > 0 && now - lastMs < ONLINE_WINDOW_MS;+ return { ...r, status: expired ? 'expired' : online ? 'online' : 'visible' };+ });++ return json(res, 200, { agents });+});diff --git a/api/irl/interactions.js b/api/irl/interactions.jsindex 69fcbacbe..3b1517e55 100644--- a/api/irl/interactions.js+++ b/api/irl/interactions.js@@ -7,10 +7,13 @@* including any message the visitor left and where the encounter happened.** POST /api/irl/interactions- * { pinId, agentId?, type: 'view'|'message'|'pay', message?, deviceToken? }- * Anonymous-friendly: viewer attribution falls back to the device token.- * Repeat 'view's from the same device on the same pin within VIEW_DEDUPE_MS- * collapse into the first one so the feed stays meaningful.+ * { pinId, type: 'view'|'tap'|'message'|'pay', message?, deviceToken?,+ * amount?, currencyMint?, network?, payload? }+ * agent_id + owner are taken from the pin, never the caller. Anonymous-friendly:+ * viewer attribution falls back to the device token. Repeat 'view's from the+ * same device on the same pin within VIEW_DEDUPE_MS collapse into the first one.+ * A 'pay' must carry a valid settlement signature + a $THREE/USDC mint and is+ * de-duped per signature. 'pay'/'message' fan out an owner notification.** GET /api/irl/interactions?mine=1[&unread=1] — interactions on MY pins* Owner is matched by session user OR by ?deviceToken= (anonymous placements).@@ -19,14 +22,68 @@* GET /api/irl/interactions?pinId=<id> — public count for one pin*/-import { cors, json, wrap } from '../_lib/http.js';+import { cors, json, wrap, rateLimited } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';+import { insertNotification } from '../_lib/notify.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { limits, clientIp } from '../_lib/rate-limit.js';-const TYPES = new Set(['view', 'message', 'pay']);+// view | tap — passive/active sighting of the agent. message — a note left for+// the owner. pay — an x402 settlement against the agent (see PAY note below).+const TYPES = new Set(['view', 'tap', 'message', 'pay']);const VIEW_DEDUPE_MS = 5 * 60 * 1000; // collapse repeat views from one deviceconst MAX_MESSAGE_LEN = 280;+// A `pay` is the one caller-asserted type that names money, so it is NOT trusted+// blindly (the original guard against forged "someone paid your agent" rows). A+// pay is only recorded when it carries a settlement proof we can sanity-check:+// 1. a well-formed on-chain signature (0x… EVM tx hash, or base58 Solana sig),+// 2. a currency mint that is $THREE or USDC — the only coins this platform+// references; anything else is rejected outright, and+// 3. global de-dupe by signature so one settlement can be logged exactly once.+// Pays surface ONLY in the owner's private inbox (never publicly), and the write+// is rate-limited + deduped, so the residual abuse surface is a forger spamming+// their own inbox. Full on-chain attribution (recipient/amount match) is layered+// on by the B3 settlement path, which owns the seller payout + price context.+const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;+const SOL_SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{43,88}$/;+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const USDC_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';+// Lowercased lookup so an EVM address compares case-insensitively; the two+// case-sensitive base58 mints are matched verbatim.+const ALLOWED_PAY_MINTS = new Set([THREE_MINT, USDC_SOLANA, USDC_BASE]);+function isAllowedMint(mint) {+ if (typeof mint !== 'string' || !mint) return false;+ return ALLOWED_PAY_MINTS.has(mint) || ALLOWED_PAY_MINTS.has(mint.toLowerCase());+}+function isValidPaySignature(sig) {+ return typeof sig === 'string' && (EVM_TX_RE.test(sig) || SOL_SIG_RE.test(sig));+}+// Block-explorer deep link for a settlement, picking the chain from the+// signature shape (EVM tx hash → Basescan) or an explicit network hint,+// defaulting to Solscan. Returned in the notification so the owner can open the+// receipt straight from the bell.+function explorerTxUrl(sig, network) {+ if (!sig) return null;+ const net = String(network || '').toLowerCase();+ if (EVM_TX_RE.test(sig) || net.includes('base') || net.includes('eip155')) {+ return `https://basescan.org/tx/${sig}`;+ }+ return `https://solscan.io/tx/${sig}`;+}+// Bound an untrusted payload object so a caller can't store an arbitrarily large+// blob in the JSONB column. Non-objects and oversized payloads collapse to {}.+function clampPayload(obj) {+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) return {};+ try {+ return JSON.stringify(obj).length <= 2000 ? obj : {};+ } catch {+ return {};+ }+}+let _tableReady = false;async function ensureTable() {if (_tableReady) return;@@ -47,6 +104,14 @@ async function ensureTable() {`;await sql`CREATE INDEX IF NOT EXISTS irl_interactions_pin ON irl_interactions (pin_id, created_at DESC)`;await sql`CREATE INDEX IF NOT EXISTS irl_interactions_viewer ON irl_interactions (viewer_device, pin_id, type)`;+ // Earnings columns (C4) — populated for type='pay'. amount is in the asset's+ // atomic units; currency_mint is $THREE or USDC; payload carries the on-chain+ // signature, network, and any structured context (geo, settlement detail).+ await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS amount NUMERIC`;+ await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS currency_mint TEXT`;+ await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS payload JSONB DEFAULT '{}'::jsonb`;+ // One settlement → one pay row. Indexed for the de-dupe lookup on insert.+ await sql`CREATE INDEX IF NOT EXISTS irl_interactions_paysig ON irl_interactions ((payload->>'signature')) WHERE type = 'pay'`;_tableReady = true;}@@ -58,6 +123,9 @@ export default wrap(async (req, res) => {// ── POST — log an interaction ─────────────────────────────────────────────if (req.method === 'POST') {+ const rl = await limits.irlInteractIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const body = req.body ?? {};const pinId = body.pinId;if (!pinId) return json(res, 400, { error: 'pinId required' });@@ -100,23 +168,80 @@ export default wrap(async (req, res) => {if (recent) return json(res, 200, { ok: true, deduped: true, id: recent.id });}+ // Earnings fields — only ever set for a verified `pay` (see PAY note up top).+ let amount = null;+ let currencyMint = null;+ let payload = clampPayload(body.payload);+ if (type === 'pay') {+ const sig = payload.signature ?? body.signature ?? null;+ const mint = body.currencyMint ?? payload.currencyMint ?? null;+ if (!isValidPaySignature(sig)) {+ return json(res, 400, { error: 'pay requires a valid on-chain settlement signature' });+ }+ if (!isAllowedMint(mint)) {+ return json(res, 400, { error: 'currency_mint must be $THREE or USDC' });+ }+ const amt = Number(body.amount);+ amount = Number.isFinite(amt) && amt > 0 ? amt : null;+ currencyMint = mint;+ payload = { ...payload, signature: sig };+ if (body.network) payload.network = String(body.network).slice(0, 32);+ // One settlement → one pay row, even if the client retries the log.+ const [dupe] = await sql`+ SELECT id FROM irl_interactions+ WHERE type = 'pay' AND payload->>'signature' = ${sig}+ LIMIT 1+ `;+ if (dupe) return json(res, 200, { ok: true, deduped: true, id: dupe.id });+ }+const [row] = await sql`INSERT INTO irl_interactions- (pin_id, agent_id, type, message, viewer_user_id, viewer_device, lat, lng)+ (pin_id, agent_id, type, message, viewer_user_id, viewer_device, lat, lng,+ amount, currency_mint, payload)VALUES (${pinId},- ${pin.agent_id ?? body.agentId ?? null},+ ${pin.agent_id ?? null},${type},${message},${viewerUserId},${viewerDevice},${pin.lat},- ${pin.lng}+ ${pin.lng},+ ${amount},+ ${currencyMint},+ ${JSON.stringify(payload)}::jsonb)RETURNING id, type, created_at`;- // Increment deduplicated visitor count on the pin for quick dashboard display- sql`UPDATE irl_pins SET view_count = view_count + 1 WHERE id = ${pinId}`.catch(() => {});+ // view_count is the "Visitors" metric — only an actual view counts. A message+ // (or any non-view) must not inflate it (the owner already sees those as feed+ // rows). Owner-self views and same-device repeats already returned above.+ if (type === 'view') {+ sql`UPDATE irl_pins SET view_count = view_count + 1 WHERE id = ${pinId}`.catch(() => {});+ }+ // High-signal events notify the owner: in-app always (the dashboard inbox ++ // the global nav bell), plus an optional Telegram ping for a pay. Both are+ // fire-and-forget and no-op when the owner is anonymous or creds are absent.+ if ((type === 'pay' || type === 'message') && pin.user_id) {+ insertNotification(pin.user_id, 'irl_interaction', {+ pin_id: pinId,+ agent_id: pin.agent_id ?? null,+ kind: type,+ amount,+ currency_mint: currencyMint,+ message,+ tx_signature: type === 'pay' ? payload.signature : undefined,+ link: type === 'pay' ? explorerTxUrl(payload.signature, payload.network) : undefined,+ });+ if (type === 'pay') {+ sendOpsAlert(+ 'IRL agent paid',+ `A placed agent was paid IRL${amount ? ` (${amount} ${currencyMint})` : ''}. Pin ${pinId}.`,+ { signature: `irl-pay:${payload.signature}` },+ );+ }+ }return json(res, 201, { ok: true, interaction: row });}@@ -140,8 +265,11 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'sign in or pass deviceToken' });}const unreadOnly = req.query.unread === '1';+ // Null-guard both identifiers so a missing owner id or an empty device token+ // can NEVER match a row (a NULL user_id or '' device_token would otherwise+ // surface another owner's — or every legacy NULL-token — interaction).const ownerId = session?.id ?? null;- const ownerDev = deviceToken ?? '';+ const ownerDev = (typeof deviceToken === 'string' && deviceToken.length) ? deviceToken : null;// Neon's tagged template doesn't compose nested `sql` fragments, so the// unread filter is two explicit queries rather than a spliced clause.@@ -150,10 +278,12 @@ export default wrap(async (req, res) => {SELECTix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,ix.lat, ix.lng, ix.seen_at, ix.created_at,+ ix.amount, ix.currency_mint, ix.payload,p.avatar_name, p.captionFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_id- WHERE (p.user_id = ${ownerId} OR p.device_token = ${ownerDev})+ WHERE ((${ownerId}::uuid IS NOT NULL AND p.user_id = ${ownerId}::uuid)+ OR (${ownerDev}::text IS NOT NULL AND p.device_token = ${ownerDev}))AND ix.seen_at IS NULLORDER BY ix.created_at DESCLIMIT 100`@@ -161,17 +291,20 @@ export default wrap(async (req, res) => {SELECTix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,ix.lat, ix.lng, ix.seen_at, ix.created_at,+ ix.amount, ix.currency_mint, ix.payload,p.avatar_name, p.captionFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_id- WHERE (p.user_id = ${ownerId} OR p.device_token = ${ownerDev})+ WHERE ((${ownerId}::uuid IS NOT NULL AND p.user_id = ${ownerId}::uuid)+ OR (${ownerDev}::text IS NOT NULL AND p.device_token = ${ownerDev}))ORDER BY ix.created_at DESCLIMIT 100`;const [agg] = await sql`SELECT COUNT(*) FILTER (WHERE ix.seen_at IS NULL)::int AS unreadFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_id- WHERE (p.user_id = ${session?.id ?? null} OR p.device_token = ${deviceToken ?? ''})+ WHERE ((${ownerId}::uuid IS NOT NULL AND p.user_id = ${ownerId}::uuid)+ OR (${ownerDev}::text IS NOT NULL AND p.device_token = ${ownerDev}))`;return json(res, 200, { interactions: rows, unread: agg?.unread ?? 0 });}@@ -179,8 +312,10 @@ export default wrap(async (req, res) => {// ── PATCH — mark my interactions as seen ──────────────────────────────────if (req.method === 'PATCH') {const session = await getSessionUser(req).catch(() => null);- const deviceToken = req.body?.deviceToken ?? null;- if (!session && !deviceToken) {+ const rawTok = req.body?.deviceToken ?? null;+ const ownerId = session?.id ?? null;+ const ownerDev = (typeof rawTok === 'string' && rawTok.length) ? rawTok : null;+ if (!ownerId && !ownerDev) {return json(res, 400, { error: 'sign in or pass deviceToken' });}await sql`@@ -189,7 +324,8 @@ export default wrap(async (req, res) => {FROM irl_pins pWHERE ix.pin_id = p.idAND ix.seen_at IS NULL- AND (p.user_id = ${session?.id ?? null} OR p.device_token = ${deviceToken ?? ''})+ AND ((${ownerId}::uuid IS NOT NULL AND p.user_id = ${ownerId}::uuid)+ OR (${ownerDev}::text IS NOT NULL AND p.device_token = ${ownerDev}))`;return json(res, 200, { ok: true });}diff --git a/api/irl/pins.js b/api/irl/pins.jsindex 9c2acbad3..dc56a8be4 100644--- a/api/irl/pins.js+++ b/api/irl/pins.js@@ -6,13 +6,41 @@* GET /api/irl/pins?mine=1 my pins (auth required)* POST /api/irl/pins { lat, lng, heading, avatarUrl, avatarName, caption, agentId }* PATCH /api/irl/pins { id, caption, avatarUrl, avatarName, lat, lng } edit pin (auth required)+ * PATCH /api/irl/pins { id, deviceToken, calibrate:{ lat, lng, anchorYawDeg, anchorHeightM } }+ * owner-gated, bounds-checked pose nudge (A3)* DELETE /api/irl/pins?id= remove own pin (device_token or auth)* POST /api/irl/pins/interact { pinId, event, deviceToken } log a tap/view*/-import { cors, json, wrap } from '../_lib/http.js';+import { cors, json, wrap, rateLimited } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';++// Validate a URL that will be handed to every nearby viewer's browser — the+// avatar GLB (→ GLTFLoader) and the x402 pay endpoint (→ Pay button). Same-origin+// relative paths (avatars live under /api/avatars/…) are always allowed; absolute+// URLs must be https and must not point at localhost / private / loopback hosts,+// so a placement can't aim other users' devices at an internal or attacker host.+// Returns { ok: true, value } or { ok: false }. `value` is the normalized string.+function safeRemoteUrl(raw, { allowRelative = true } = {}) {+ if (raw == null || raw === '') return { ok: true, value: null };+ const v = String(raw).trim();+ if (!v) return { ok: true, value: null };+ if (allowRelative && v.startsWith('/') && !v.startsWith('//')) return { ok: true, value: v };+ let u;+ try { u = new URL(v); } catch { return { ok: false }; }+ if (u.protocol !== 'https:') return { ok: false };+ if (u.username || u.password) return { ok: false };+ const host = u.hostname.toLowerCase();+ if (+ host === 'localhost' || host.endsWith('.local') || host.endsWith('.internal') ||+ host === '0.0.0.0' || host === '::1' ||+ /^127\./.test(host) || /^10\./.test(host) || /^192\.168\./.test(host) ||+ /^169\.254\./.test(host) || /^172\.(1[6-9]|2\d|3[01])\./.test(host)+ ) return { ok: false };+ return { ok: true, value: u.toString() };+}// Haversine distance in meters between two GPS pointsfunction haversineDist(lat1, lng1, lat2, lng2) {@@ -50,9 +78,105 @@ async function ensureTable() {await sql`CREATE INDEX IF NOT EXISTS irl_pins_expires ON irl_pins (expires_at)`;// view_count — deduplicated visitor count; incremented by /api/irl/interactionsawait sql`ALTER TABLE irl_pins ADD COLUMN IF NOT EXISTS view_count BIGINT NOT NULL DEFAULT 0`;+ // Anchor pose — added 2026-06 for IRL-Live world anchoring (A2). Persisting the+ // full pose (floor height, orientation, GPS-fix trust) is the prerequisite for+ // WebXR anchors (A1), shared-spot reconciliation (A3), and gyro-lock replay (A4).+ 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_tableReady = true;}+// ── Calibration bounds (A3) ─────────────────────────────────────────────────+// A nudge is a fine-tune, never a teleport. The client clamps to ±3 m / ±45°;+// the server re-validates with a small margin so a corrected pose can never be+// abused to move someone's agent across the map. Diagonal of a 3 m N + 3 m E+// drag is ~4.24 m, so 5 m is the tightest ceiling that never rejects a legit nudge.+const CAL_MAX_MOVE_M = 5; // ground-move ceiling, metres+const CAL_MAX_YAW_DEG = 46; // yaw-nudge ceiling, degrees+const CAL_MAX_RISE_M = 3; // floor-height nudge ceiling, metres++// Smallest signed distance between two compass bearings, 0–180°.+function circularYawDelta(a, b) {+ let d = ((a - b) % 360 + 360) % 360;+ if (d > 180) d -= 360;+ return Math.abs(d);+}++// Owner-gated, bounds-checked pose correction. Mutates the A2 pose columns so the+// re-fetch every nearby viewer already runs picks up the corrected spot. (Pushing+// the correction to already-loaded viewers in realtime rides on D1; a re-fetch+// suffices here.) Calibration touches no coin and no third-party token.+async function handleCalibrate(res, { id, session, body }) {+ const cal = (body.calibrate && typeof body.calibrate === 'object') ? body.calibrate : {};++ const [pin] = await sql`+ SELECT id, user_id, device_token, lat, lng, heading, anchor_yaw_deg, anchor_height_m+ FROM irl_pins+ WHERE id = ${id}+ `;+ if (!pin) return json(res, 404, { error: 'not found' });++ // Ownership: the authenticated owner (user_id) or the anonymous device that+ // placed it (device_token). Anything else is denied — never silently allowed.+ const owns =+ (!!session?.id && !!pin.user_id && pin.user_id === session.id) ||+ (!!pin.device_token && !!body.deviceToken && pin.device_token === body.deviceToken);+ if (!owns) return json(res, 403, { error: 'only the owner can calibrate this agent' });++ // New ground position — required, validated, range-checked.+ const newLat = parseFloat(cal.lat);+ const newLng = parseFloat(cal.lng);+ if (!isFinite(newLat) || newLat < -90 || newLat > 90 ||+ !isFinite(newLng) || newLng < -180 || newLng > 180) {+ return json(res, 400, { error: 'invalid calibrate coordinates' });+ }+ const moved = haversineDist(pin.lat, pin.lng, newLat, newLng);+ if (moved > CAL_MAX_MOVE_M) {+ return json(res, 422, { error: 'calibration move too large', max_m: CAL_MAX_MOVE_M });+ }++ // New yaw — optional; bounded against the stored bearing.+ let newYaw = null;+ if (Number.isFinite(cal.anchorYawDeg)) {+ newYaw = ((cal.anchorYawDeg % 360) + 360) % 360;+ const storedYaw = Number.isFinite(pin.anchor_yaw_deg) ? pin.anchor_yaw_deg : (pin.heading ?? 0);+ if (circularYawDelta(newYaw, storedYaw) > CAL_MAX_YAW_DEG) {+ return json(res, 422, { error: 'calibration rotation too large', max_deg: CAL_MAX_YAW_DEG });+ }+ }++ // New floor height — optional; bounded against the stored height.+ let newHeight = null;+ if (Number.isFinite(cal.anchorHeightM)) {+ newHeight = cal.anchorHeightM;+ const baseH = Number.isFinite(pin.anchor_height_m) ? pin.anchor_height_m : 0;+ if (Math.abs(newHeight - baseH) > CAL_MAX_RISE_M || Math.abs(newHeight) > 50) {+ return json(res, 422, { error: 'calibration height too large', max_m: CAL_MAX_RISE_M });+ }+ }++ // Persist. heading stays in sync with anchor_yaw_deg so legacy clients (which+ // only read `heading`) still render the corrected bearing.+ const headingToStore = newYaw != null ? Math.round(newYaw) : null;+ const [row] = await sql`+ UPDATE irl_pins SET+ lat = ${newLat},+ lng = ${newLng},+ anchor_yaw_deg = COALESCE(${newYaw}, anchor_yaw_deg),+ heading = COALESCE(${headingToStore}, heading),+ anchor_height_m = COALESCE(${newHeight}, anchor_height_m)+ WHERE id = ${id}+ RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, gps_accuracy_m+ `;+ return json(res, 200, { pin: row, calibrated: true });+}+export default wrap(async (req, res) => {cors(req, res, { methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'] });if (req.method === 'OPTIONS') return res.end();@@ -85,7 +209,9 @@ export default wrap(async (req, res) => {if (!session) return json(res, 401, { error: 'not authenticated' });const rows = await sql`SELECT id, lat, lng, heading, avatar_url, avatar_name, caption, agent_id,- placed_at, expires_at, view_count+ placed_at, expires_at, view_count,+ anchor_height_m, anchor_yaw_deg, anchor_quat,+ gps_accuracy_m, altitude_m, anchor_sourceFROM irl_pinsWHERE user_id = ${session.id}ORDER BY placed_at DESC@@ -108,9 +234,17 @@ export default wrap(async (req, res) => {const latDelta = radius / 110540;const lngDelta = radius / (111320 * Math.cos(lat * Math.PI / 180));+ // Resolve the caller so we can tell them which nearby pins are THEIRS without+ // ever exposing other people's owner identifiers.+ const session = await getSessionUser(req).catch(() => null);+ const myId = session?.id ?? null;+ const myTok = req.query.deviceToken || null;+const rows = await sql`- SELECT id, user_id, agent_id, lat, lng, heading,- avatar_url, avatar_name, caption, x402_endpoint, placed_at, view_count+ SELECT id, user_id, device_token, agent_id, lat, lng, heading,+ avatar_url, avatar_name, caption, x402_endpoint, placed_at, view_count,+ anchor_height_m, anchor_yaw_deg, anchor_quat,+ gps_accuracy_m, altitude_m, anchor_sourceFROM irl_pinsWHERE lat BETWEEN ${lat - latDelta} AND ${lat + latDelta}AND lng BETWEEN ${lng - lngDelta} AND ${lng + lngDelta}@@ -119,9 +253,29 @@ export default wrap(async (req, res) => {LIMIT 50`;+ // Explicit allow-list projection: NEVER return user_id or device_token in the+ // public feed (a stable owner UUID + precise coords is a deanonymization /+ // location-tracking vector). Surface only an is_mine boolean computed here.const pins = rows.map(r => ({- ...r,+ id: r.id,+ agent_id: r.agent_id,+ lat: r.lat,+ lng: r.lng,+ heading: r.heading,+ avatar_url: r.avatar_url,+ avatar_name: r.avatar_name,+ caption: r.caption,+ x402_endpoint: r.x402_endpoint,+ placed_at: r.placed_at,+ view_count: r.view_count,+ anchor_height_m: r.anchor_height_m,+ anchor_yaw_deg: r.anchor_yaw_deg,+ anchor_quat: r.anchor_quat,+ gps_accuracy_m: r.gps_accuracy_m,+ altitude_m: r.altitude_m,+ anchor_source: r.anchor_source,+ is_mine: (!!myId && r.user_id === myId) || (!!myTok && r.device_token === myTok),distance_m: Math.round(haversineDist(lat, lng, r.lat, r.lng)),})).filter(r => r.distance_m <= radius)@@ -132,6 +286,9 @@ export default wrap(async (req, res) => {// ── POST — create pin ─────────────────────────────────────────────────────if (req.method === 'POST') {+ const rl = await limits.irlPinIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const body = req.body ?? {};const lat = parseFloat(body.lat);const lng = parseFloat(body.lng);@@ -143,26 +300,63 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'invalid coordinates' });}+ // Validate the URLs handed to every nearby viewer (avatar GLB + x402 pay).+ const avatarUrlChk = safeRemoteUrl(body.avatarUrl);+ if (!avatarUrlChk.ok) return json(res, 400, { error: 'invalid avatarUrl' });+ const x402Chk = safeRemoteUrl(body.x402Endpoint, { allowRelative: false });+ if (!x402Chk.ok) return json(res, 400, { error: 'invalid x402Endpoint' });+ // Empty-string device token would otherwise become a shared anonymous owner.+ const deviceToken = body.deviceToken || null;+const session = await getSessionUser(req).catch(() => null);const userId = session?.id ?? null;// Authenticated users get permanent pins; anonymous expire in 7 days.const expiresAt = userId ? null : new Date(Date.now() + 7 * 24 * 3600 * 1000).toISOString();+ // Anchor pose (A2) — optional, back-compat: old clients send no `anchor`,+ // every pose column inserts NULL. New clients send a reproducible pose so+ // later sessions / other users can reconstruct where the agent stands.+ const pose = (body.anchor && typeof body.anchor === 'object') ? body.anchor : {};+ // Reject absurd floor height (> ±50 m above/below eye) to NULL, not noise.+ const anchorHeightM = Number.isFinite(pose.heightM) && Math.abs(pose.heightM) <= 50+ ? pose.heightM : null;+ const anchorYawDeg = Number.isFinite(pose.yawDeg)+ ? ((pose.yawDeg % 360) + 360) % 360 : null;+ const anchorQuat = Array.isArray(pose.quat) && pose.quat.length === 4 &&+ pose.quat.every(Number.isFinite)+ ? JSON.stringify(pose.quat) : null;+ // Clamp GPS accuracy to a sane 0–500 m range (a worse fix is meaningless here).+ const gpsAccuracyM = Number.isFinite(pose.gpsAccuracyM)+ ? Math.min(500, Math.max(0, pose.gpsAccuracyM)) : null;+ const altitudeM = Number.isFinite(pose.altitudeM) ? pose.altitudeM : null;+ // 'webxr' (A1) · 'gyro-gps' (absolute compass heading) · 'gyro-gps:rel'+ // (page-relative heading only — A3 down-weights its cross-user bearing).+ const anchorSource = pose.source === 'webxr' ? 'webxr'+ : pose.source === 'gyro-gps:rel' ? 'gyro-gps:rel' : 'gyro-gps';+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)+ 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},+ ${deviceToken},${lat}, ${lng},${parseFloat(body.heading) || 0},- ${body.avatarUrl ?? null},+ ${avatarUrlChk.value},${body.avatarName ?? null},${body.caption ?? null},- ${body.x402Endpoint ?? null},- ${expiresAt}+ ${x402Chk.value},+ ${expiresAt},+ ${anchorHeightM},+ ${anchorYawDeg},+ ${anchorQuat},+ ${gpsAccuracyM},+ ${altitudeM},+ ${anchorSource})RETURNING *`;@@ -175,12 +369,25 @@ export default wrap(async (req, res) => {// Anonymous device-token owners can only update caption (no location/avatar changes// from anonymous sessions for safety).if (req.method === 'PATCH') {+ const rl = await limits.irlPinIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const session = await getSessionUser(req).catch(() => null);- if (!session) return json(res, 401, { error: 'not authenticated' });const body = req.body ?? {};const { id } = body;if (!id) return json(res, 400, { error: 'id required' });+ // ── Calibrate — a small, owner-gated pose correction (A3) ─────────────+ // Owner-gated for both authenticated owners and the anonymous device that+ // placed the pin, so it routes BEFORE the auth gate below; ownership and+ // nudge bounds are enforced inside handleCalibrate.+ if (body.calibrate && typeof body.calibrate === 'object') {+ return handleCalibrate(res, { id, session, body });+ }++ // Field edits (caption / avatar / location / heading / x402) require auth.+ if (!session) return json(res, 401, { error: 'not authenticated' });+// Build update SET clause only for fields the caller providedconst updates = {};if ('caption' in body) updates.caption = body.caption ?? null;@@ -207,15 +414,33 @@ export default wrap(async (req, res) => {return json(res, 400, { error: 'invalid lng' });}+ // Validate URL fields if the caller is changing them (relative avatar URLs ok).+ if ('avatarUrl' in updates) {+ const c = safeRemoteUrl(updates.avatarUrl);+ if (!c.ok) return json(res, 400, { error: 'invalid avatarUrl' });+ updates.avatarUrl = c.value;+ }+ if ('x402Endpoint' in updates) {+ const c = safeRemoteUrl(updates.x402Endpoint, { allowRelative: false });+ if (!c.ok) return json(res, 400, { error: 'invalid x402Endpoint' });+ updates.x402Endpoint = c.value;+ }++ // Present-flag each text field so an explicit clear (null) actually writes+ // NULL. COALESCE treats null as "no change", silently dropping a clear and+ // desyncing the dashboard (which optimistically cleared the field) from the+ // row every nearby viewer fetches. lat/lng/heading keep COALESCE since 0 is a+ // valid value there and they are never "cleared".+ const has = (k) => k in updates;const [row] = await sql`UPDATE irl_pins SET- caption = COALESCE(${updates.caption ?? null}, caption),- avatar_url = COALESCE(${updates.avatarUrl ?? null}, avatar_url),- avatar_name = COALESCE(${updates.avatarName ?? null}, avatar_name),- lat = COALESCE(${updates.lat ?? null}, lat),- lng = COALESCE(${updates.lng ?? null}, lng),- heading = COALESCE(${updates.heading ?? null}, heading),- x402_endpoint = COALESCE(${updates.x402Endpoint ?? null}, x402_endpoint)+ caption = CASE WHEN ${has('caption')} THEN ${updates.caption ?? null}::text ELSE caption END,+ avatar_url = CASE WHEN ${has('avatarUrl')} THEN ${updates.avatarUrl ?? null}::text ELSE avatar_url END,+ avatar_name = CASE WHEN ${has('avatarName')} THEN ${updates.avatarName ?? null}::text ELSE avatar_name END,+ x402_endpoint = CASE WHEN ${has('x402Endpoint')} THEN ${updates.x402Endpoint ?? null}::text ELSE x402_endpoint END,+ lat = COALESCE(${updates.lat ?? null}, lat),+ lng = COALESCE(${updates.lng ?? null}, lng),+ heading = COALESCE(${updates.heading ?? null}, heading)WHERE id = ${id} AND user_id = ${session.id}RETURNING id, caption, avatar_url, avatar_name, lat, lng, heading, x402_endpoint`;@@ -225,6 +450,9 @@ export default wrap(async (req, res) => {// ── DELETE — remove own pin ───────────────────────────────────────────────if (req.method === 'DELETE') {+ const rl = await limits.irlPinIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+const id = req.query.id;const deviceToken = req.query.deviceToken ?? req.body?.deviceToken;@@ -233,14 +461,22 @@ export default wrap(async (req, res) => {const session = await getSessionUser(req).catch(() => null);const userId = session?.id ?? null;- // Allow deletion by device_token (anonymous) or user_id (authenticated)+ // Must prove ownership: an authenticated user_id OR the placing device_token.+ // (A bare anonymous caller with neither must not be able to delete anything.)+ if (!userId && !deviceToken) {+ return json(res, 401, { error: 'authentication or device token required' });+ }++ // Match strictly by owner. Each branch is null-guarded so a NULL user_id or a+ // NULL/empty device_token can NEVER match a row — closing the prior+ // `device_token IS NULL AND $userId IS NULL` clause that let an anonymous+ // caller delete every pin whose device_token happened to be NULL.const result = await sql`DELETE FROM irl_pinsWHERE id = ${id}AND (- device_token = ${deviceToken ?? ''}- OR user_id = ${userId}- OR (device_token IS NULL AND ${userId} IS NULL)+ (${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)+ OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''}))RETURNING id`;diff --git a/data/changelog.json b/data/changelog.jsonindex 0f3fefc95..bf75e80d7 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,48 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-17",+ "title": "Tapping an IRL agent is now reliable — hit the body, not just the tiny label",+ "summary": "On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap.",+ "tags": ["improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "Everyone at a location now sees your IRL agent in the same real spot",+ "summary": "three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry.",+ "tags": ["feature", "improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk",+ "summary": "iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated.",+ "tags": ["improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "Place your IRL agent on the real floor with AR anchoring",+ "summary": "On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.",+ "tags": ["feature"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL agents turn to look at you as you move around them",+ "summary": "On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you.",+ "tags": ["improvement"],+ "link": "/irl"+ },+ {+ "date": "2026-06-17",+ "title": "IRL agents now materialize as you walk up to them",+ "summary": "On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going.",+ "tags": ["fix", "improvement"],+ "link": "/irl"+ },{"date": "2026-06-16","title": "IRL: multiplayer AR, camera-aware agents, agent switcher, and owner dashboard",diff --git a/multiplayer/src/geohash.js b/multiplayer/src/geohash.jsnew file mode 100644index 000000000..41055204d--- /dev/null+++ b/multiplayer/src/geohash.js@@ -0,0 +1,88 @@+// Geohash (precision-6) — the coarse spatial key for the IRL world.+//+// Shared by the IrlRoom (server) and src/irl-net.js (client, bundled by Vite the+// same way it bundles schemas.js). A precision-6 cell is ~1.2km × 0.6km, the+// matchmaking key every viewer inside one cell joins (filterBy(['geocell'])).+//+// Privacy by design: the geohash IS the coarse location. A viewer's device never+// has to send precise GPS — it sends only this cell string, and the server places+// presence markers at the cell centre + bounded jitter. So "where someone is"+// never resolves finer than "somewhere in this ~1km cell."++const BASE32 = '0123456789bcdefghjkmnpqrstuvwxyz'; // (no a, i, l, o)++/**+ * Encode a lat/lng to a geohash string of the given precision.+ * @param {number} lat+ * @param {number} lng+ * @param {number} [precision=6]+ * @returns {string}+ */+export function encodeGeohash(lat, lng, precision = 6) {+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) return '';+ let idx = 0;+ let bit = 0;+ let evenBit = true; // true → bisecting longitude, false → latitude+ let geohash = '';+ let latMin = -90, latMax = 90;+ let lngMin = -180, lngMax = 180;++ while (geohash.length < precision) {+ if (evenBit) {+ const mid = (lngMin + lngMax) / 2;+ if (lng >= mid) { idx = idx * 2 + 1; lngMin = mid; } else { idx = idx * 2; lngMax = mid; }+ } else {+ const mid = (latMin + latMax) / 2;+ if (lat >= mid) { idx = idx * 2 + 1; latMin = mid; } else { idx = idx * 2; latMax = mid; }+ }+ evenBit = !evenBit;+ if (++bit === 5) {+ geohash += BASE32[idx];+ bit = 0;+ idx = 0;+ }+ }+ return geohash;+}++/**+ * Decode a geohash to its bounding box.+ * @returns {{ latMin:number, latMax:number, lngMin:number, lngMax:number }}+ */+export function decodeGeohashBounds(geohash) {+ let evenBit = true;+ let latMin = -90, latMax = 90;+ let lngMin = -180, lngMax = 180;+ for (const ch of String(geohash || '').toLowerCase()) {+ const idx = BASE32.indexOf(ch);+ if (idx < 0) continue; // tolerate stray chars rather than throwing on the wire+ for (let n = 4; n >= 0; n--) {+ const bitN = (idx >> n) & 1;+ if (evenBit) {+ const mid = (lngMin + lngMax) / 2;+ if (bitN === 1) lngMin = mid; else lngMax = mid;+ } else {+ const mid = (latMin + latMax) / 2;+ if (bitN === 1) latMin = mid; else latMax = mid;+ }+ evenBit = !evenBit;+ }+ }+ return { latMin, latMax, lngMin, lngMax };+}++/**+ * Decode a geohash to its centre point and half-extents (degrees of error each way).+ * The half-extents bound the jitter the server adds so a presence marker stays+ * inside the cell it claims.+ * @returns {{ lat:number, lng:number, latErr:number, lngErr:number }}+ */+export function decodeGeohash(geohash) {+ const b = decodeGeohashBounds(geohash);+ return {+ lat: (b.latMin + b.latMax) / 2,+ lng: (b.lngMin + b.lngMax) / 2,+ latErr: (b.latMax - b.latMin) / 2,+ lngErr: (b.lngMax - b.lngMin) / 2,+ };+}diff --git a/pages/irl.html b/pages/irl.htmlindex f1a6580c5..2836533a8 100644--- a/pages/irl.html+++ b/pages/irl.html@@ -258,6 +258,7 @@}.irl-status.is-hidden { opacity: 0; }.irl-status.is-error { color: var(--danger); }+ .irl-status.is-warn { color: #fbbf24; }.irl-status-spinner {width: 13px;height: 13px;@@ -358,6 +359,87 @@background: rgba(251,191,36,0.1);}#irl-lock-btn.is-active:hover { background: rgba(251,191,36,0.18); }+ /* WebXR floor-anchor entry — accent it as the premium placement path */+ #irl-anchor-btn {+ color: #c4b5fd;+ border-color: rgba(155,140,255,0.4);+ background: rgba(155,140,255,0.08);+ }+ #irl-anchor-btn:hover:not(:disabled) {+ color: #ddd6fe;+ border-color: rgba(155,140,255,0.6);+ background: rgba(155,140,255,0.16);+ }+ #irl-anchor-btn.is-active {+ color: #ddd6fe;+ border-color: rgba(155,140,255,0.7);+ background: rgba(155,140,255,0.2);+ }+ /* ── WebXR floor-anchor in-session overlay (dom-overlay root) ── */+ #irl-xr-overlay {+ position: fixed;+ inset: 0;+ z-index: 60;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: flex-start;+ pointer-events: none; /* only the chrome inside is interactive */+ padding: calc(env(safe-area-inset-top, 0px) + 18px) 16px 0;+ }+ #irl-xr-overlay[hidden] { display: none; }+ .irl-xr-bar {+ display: flex;+ align-items: center;+ gap: 12px;+ max-width: 560px;+ width: 100%;+ padding: 10px 12px 10px 16px;+ border-radius: 999px;+ background: rgba(10,11,18,0.72);+ border: 1px solid rgba(255,255,255,0.12);+ backdrop-filter: blur(12px);+ -webkit-backdrop-filter: blur(12px);+ box-shadow: 0 6px 28px rgba(0,0,0,0.45);+ pointer-events: auto;+ }+ .irl-xr-hint {+ flex: 1;+ margin: 0;+ font-size: 13.5px;+ font-weight: 600;+ line-height: 1.35;+ color: #e8e8ef;+ letter-spacing: -0.01em;+ }+ .irl-xr-exit {+ flex-shrink: 0;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 8px 13px;+ border-radius: 999px;+ font: 600 12.5px/1 var(--font-body, system-ui, sans-serif);+ color: #e8e8ef;+ background: rgba(255,255,255,0.08);+ border: 1px solid rgba(255,255,255,0.16);+ cursor: pointer;+ transition: background 0.15s ease, border-color 0.15s ease, transform 0.12s ease;+ }+ .irl-xr-exit:hover { background: rgba(255,255,255,0.14); border-color: rgba(255,255,255,0.28); }+ .irl-xr-exit:active { transform: translateY(1px); }+ .irl-xr-exit:focus-visible { outline: 2px solid rgba(255,255,255,0.5); outline-offset: 2px; }+ .irl-xr-error {+ pointer-events: auto;+ margin-top: 14vh;+ max-width: 420px;+ width: 100%;+ border-radius: 18px;+ background: rgba(10,11,18,0.92);+ border: 1px solid rgba(255,255,255,0.12);+ box-shadow: 0 10px 40px rgba(0,0,0,0.5);+ }+ .irl-xr-error[hidden] { display: none; }/* Gyro pulse on lock icon when actively tracking orientation in AR */body.is-ar.is-locked #irl-lock-icon {animation: irl-gyro-pulse 2.5s ease-in-out infinite;@@ -629,6 +711,42 @@#irl-caption-cancel { width: 44px; height: 44px; padding: 0; border-radius: 12px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.06); color: #6b7280; font: 600 18px inherit; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background 0.15s; }#irl-caption-cancel:hover { background: rgba(255,255,255,0.12); color: #e5e7eb; }+ /* Designed guidance sheet — motion permission, GPS-not-ready, etc. (A4) */+ #irl-error-sheet {+ position: fixed;+ bottom: 0;+ left: 0;+ right: 0;+ z-index: 24;+ background: rgba(12,14,20,0.97);+ border-top: 1px solid rgba(248,113,113,0.3);+ border-radius: 18px 18px 0 0;+ padding: 20px 22px 36px;+ backdrop-filter: blur(22px);+ -webkit-backdrop-filter: blur(22px);+ transform: translateY(100%);+ transition: transform 0.28s cubic-bezier(0.32,0.72,0,1);+ pointer-events: none;+ }+ #irl-error-sheet.is-open { transform: translateY(0); pointer-events: all; }+ #irl-error-sheet .irl-sheet-handle { margin-bottom: 14px; }+ .irl-error-icon {+ width: 40px; height: 40px;+ border-radius: 12px;+ display: flex; align-items: center; justify-content: center;+ background: rgba(248,113,113,0.12);+ color: var(--danger);+ margin-bottom: 12px;+ }+ #irl-error-sheet h3 { font-size: 16px; font-weight: 700; color: #e5e7eb; margin: 0 0 8px; }+ #irl-error-body { font-size: 13.5px; line-height: 1.55; color: var(--text-2); margin: 0 0 16px; }+ .irl-error-row { display: flex; gap: 10px; }+ #irl-error-action { flex: 1; padding: 12px 16px; border-radius: 12px; border: 1px solid rgba(96,165,250,0.4); background: rgba(96,165,250,0.16); color: #93c5fd; font: 600 14px inherit; cursor: pointer; transition: background 0.15s; }+ #irl-error-action:hover { background: rgba(96,165,250,0.26); }+ #irl-error-action:active { transform: scale(0.98); }+ #irl-error-dismiss { width: 44px; height: 44px; padding: 0; border-radius: 12px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.06); color: #9ca3af; font: 600 18px inherit; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background 0.15s; }+ #irl-error-dismiss:hover { background: rgba(255,255,255,0.12); color: #e5e7eb; }+/* My Pins management sheet */#irl-mypins-sheet {position: fixed;@@ -685,7 +803,16 @@-webkit-backdrop-filter: blur(8px);box-shadow: 0 0 10px rgba(136,187,255,0.15);animation: irl-label-in 0.22s ease-out;- transition: border-color 0.2s, box-shadow 0.2s, color 0.2s;+ transition: border-color 0.2s, box-shadow 0.2s, color 0.2s, transform 0.18s ease;+ }+ /* Expanded touch target (B4) — an invisible ≥44px (Apple HIG) hit area+ around the visible label so a finger reliably opens the agent on a+ phone. Paints nothing; only enlarges the element's hit region. */+ .irl-agent-label::before {+ content: '';+ position: absolute;+ inset: -12px;+ border-radius: 16px;}/* Camera-aware state: agent is in the camera's view cone */.irl-agent-label.is-aware {@@ -708,52 +835,170 @@border-color: rgba(251,191,36,0.9);box-shadow: 0 0 20px rgba(251,191,36,0.4);}+ /* Proximity focus (B4) — the single nearest reachable on-screen agent gets+ a "you'll tap this" reticle: a crisp ring + subtle scale. Layered after+ is-aware/is-own so the focus target always reads on top, and eased via+ the label's transform/box-shadow transition. */+ .irl-agent-label.is-focus {+ border-color: rgba(136,187,255,0.95);+ box-shadow: 0 0 0 2px rgba(136,187,255,0.55), 0 0 22px rgba(136,187,255,0.5);+ transform: translate(-50%, -100%) scale(1.07);+ }+ .irl-agent-label.is-own.is-focus {+ border-color: rgba(251,191,36,0.95);+ box-shadow: 0 0 0 2px rgba(251,191,36,0.6), 0 0 22px rgba(251,191,36,0.5);+ }+ @media (prefers-reduced-motion: reduce) {+ .irl-agent-label.is-focus { transform: translate(-50%, -100%); }+ }@keyframes irl-label-in {from { opacity:0; transform: translate(-50%, -90%); }to { opacity:1; transform: translate(-50%, -100%); }}.irl-agent-label-name { display: block; }- /* Rich agent interaction sheet extras */- #irl-sheet-description {+ /* ── Inspect card v2 ── */+ /* Backdrop — dims the AR view behind the card so it reads as a focused dialog */+ #irl-sheet-backdrop {+ position: fixed;+ inset: 0;+ z-index: 19;+ background: rgba(4,6,11,0.45);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.28s ease;+ }+ #irl-sheet-backdrop.is-open { opacity: 1; pointer-events: all; }++ /* Header thumbnail */+ .irl-sheet-thumb {+ width: 48px;+ height: 48px;+ border-radius: 12px;+ object-fit: cover;+ flex-shrink: 0;+ background: rgba(255,255,255,0.06);+ border: 1px solid rgba(255,255,255,0.10);+ }+ .irl-sheet-title-row {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ }+ .irl-sheet-title-row .irl-sheet-title { flex: 0 1 auto; }++ /* Tier badge (header) — score + tier word, colour-coded by tier */+ .irl-tier-badge {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ flex-shrink: 0;+ font-size: 11.5px;+ font-weight: 700;+ padding: 2px 9px;+ border-radius: 999px;+ letter-spacing: 0.01em;+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+ background: rgba(255,255,255,0.08);+ border: 1px solid rgba(255,255,255,0.16);+ color: #e5e7eb;+ }+ .irl-tier-badge[data-tier="elite"] { background: rgba(250,204,21,0.16); border-color: rgba(250,204,21,0.45); color: #fde047; }+ .irl-tier-badge[data-tier="trusted"] { background: rgba(52,211,153,0.16); border-color: rgba(52,211,153,0.45); color: #34d399; }+ .irl-tier-badge[data-tier="emerging"] { background: rgba(96,165,250,0.16); border-color: rgba(96,165,250,0.45); color: #93c5fd; }+ .irl-tier-badge[data-tier="new"] { background: rgba(255,255,255,0.06); border-color: rgba(255,255,255,0.16); color: #9ca3af; }++ /* Card body — JS-rendered state container */+ .irl-card-body {+ display: flex;+ flex-direction: column;+ gap: 12px;+ margin-bottom: 14px;+ }+ .irl-card-body:empty { display: none; }++ /* Skeleton tuned for the card (overrides state-kit row min-heights) */+ .irl-card-body .tws-sk--row { padding: 6px 0; border: none; background: none; }++ /* Bio */+ .irl-card-bio {font-size: 13.5px;color: #9ca3af;line-height: 1.55;- margin-bottom: 12px;+ margin: 0;}- .irl-sheet-skills {++ /* Reputation strip */+ .irl-rep-strip {display: flex;+ align-items: center;+ gap: 8px;flex-wrap: wrap;- gap: 6px;- margin-bottom: 12px;+ font-size: 12.5px;+ color: #cbd5e1;+ font-variant-numeric: tabular-nums;}- .irl-skill-badge {- font-size: 11px;- font-weight: 600;- padding: 3px 10px;+ .irl-rep-star { color: #fbbf24; }+ .irl-rep-strip .irl-rep-sep { color: #4b5563; }+ .irl-rep-strip b { color: #e5e7eb; font-weight: 700; }+ /* "New here — no on-chain reputation yet" muted chip */+ .irl-rep-chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: #9ca3af;+ padding: 4px 10px;border-radius: 999px;- background: rgba(139,92,246,0.12);- border: 1px solid rgba(139,92,246,0.3);- color: #a78bfa;+ background: rgba(255,255,255,0.04);+ border: 1px dashed rgba(255,255,255,0.16);+ }++ /* Services list */+ .irl-services-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; margin-bottom: 8px; }+ .irl-services-list { display: flex; flex-direction: column; gap: 8px; }+ .irl-service-row {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 9px 11px;+ border-radius: 11px;+ background: rgba(255,255,255,0.04);+ border: 1px solid rgba(255,255,255,0.08);+ }+ .irl-service-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }+ .irl-service-name { color: #e5e7eb; font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .irl-service-desc { color: #9ca3af; font-size: 11.5px; line-height: 1.4; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .irl-service-price {+ color: #34d399;+ font-weight: 700;+ font-size: 12.5px;white-space: nowrap;+ font-variant-numeric: tabular-nums;+ padding: 3px 9px;+ border-radius: 999px;+ background: rgba(52,211,153,0.12);+ border: 1px solid rgba(52,211,153,0.28);}- #irl-sheet-views {- font-size: 12px;- color: #6b7280;- margin-bottom: 10px;+ .irl-service-use {+ flex-shrink: 0;+ padding: 6px 13px;+ border-radius: 9px;+ border: 1px solid rgba(255,255,255,0.14);+ background: rgba(255,255,255,0.07);+ color: #e5e7eb;+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ cursor: pointer;+ transition: background 0.15s, border-color 0.15s, transform 0.12s;}- /* Reputation bar */- .irl-sheet-rep { display: flex; align-items: center; gap: 9px; margin-bottom: 12px; }- .irl-rep-bar { flex: 1; height: 6px; border-radius: 3px; background: rgba(255,255,255,0.08); overflow: hidden; }- .irl-rep-fill { display: block; height: 100%; width: 0; border-radius: 3px; background: linear-gradient(90deg, #34d399, #88bbff); transition: width 0.5s ease; }- .irl-rep-text { font-size: 12px; font-weight: 600; color: #34d399; white-space: nowrap; font-variant-numeric: tabular-nums; }- /* Services list */- .irl-sheet-services { margin-bottom: 14px; }- .irl-services-label { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: #6b7280; margin-bottom: 6px; }- .irl-services-list { display: flex; flex-direction: column; gap: 6px; }- .irl-service-row { display: flex; align-items: center; gap: 10px; font-size: 13px; }- .irl-service-name { color: #e5e7eb; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }- .irl-service-price { color: #34d399; font-weight: 600; white-space: nowrap; font-variant-numeric: tabular-nums; }+ .irl-service-use:hover { background: rgba(52,211,153,0.18); border-color: rgba(52,211,153,0.4); color: #34d399; }+ .irl-service-use:active { transform: translateY(1px); }+ .irl-service-use:focus-visible { outline: 2px solid rgba(52,211,153,0.6); outline-offset: 2px; }+ .irl-service-use:disabled { opacity: 0.6; cursor: default; }/* Multiplayer indicator row */.irl-multiplayer-note {display: flex;@@ -967,6 +1212,10 @@<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.582-7 8-7s8 3 8 7"/></svg>Avatar</button>+ <button class="irl-pill-btn" id="irl-anchor-btn" type="button" hidden aria-label="Place agent on the floor with AR">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/><circle cx="12" cy="12" r="4"/></svg>+ Place on floor+ </button><button class="irl-pill-btn" id="irl-lock-btn" type="button" aria-pressed="false" aria-label="Pin avatar in real space"><svg id="irl-lock-icon" width="14" height="14" 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="irl-lock-label">Pin here</span>@@ -1010,6 +1259,20 @@</div></footer>+<!-- WebXR floor-anchor overlay (A1). Hidden until a session starts; surfaced as+ the immersive-ar dom-overlay root so the in-session hint + exit are visible+ over the AR view. Also the mount for the designed start-failure error card. -->+<div id="irl-xr-overlay" hidden>+ <div class="irl-xr-bar">+ <p id="irl-xr-hint" class="irl-xr-hint" aria-live="polite">Point at the floor and move your phone slowly</p>+ <button id="irl-xr-exit" type="button" class="irl-xr-exit" aria-label="Exit floor anchoring">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>+ Exit+ </button>+ </div>+ <div id="irl-xr-error" class="irl-xr-error" hidden></div>+</div>+<!-- Caption input panel (slides up before a pin is saved) --><div id="irl-caption-panel" role="dialog" aria-modal="true" aria-label="Add a caption to your pin"><div class="irl-sheet-handle" aria-hidden="true"></div>@@ -1021,6 +1284,20 @@</div></div>+<!-- Designed guidance sheet — recoverable motion/GPS permission states (A4) -->+<div id="irl-error-sheet" role="dialog" aria-modal="true" aria-label="Action needed">+ <div class="irl-sheet-handle" aria-hidden="true"></div>+ <div class="irl-error-icon" aria-hidden="true">+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>+ </div>+ <h3 id="irl-error-title">Action needed</h3>+ <p id="irl-error-body"></p>+ <div class="irl-error-row">+ <button id="irl-error-action" type="button">Try again</button>+ <button id="irl-error-dismiss" type="button" aria-label="Dismiss">×</button>+ </div>+</div>+<!-- My Pins management sheet --><div id="irl-mypins-sheet" role="dialog" aria-modal="true" aria-label="My active pins"><div class="irl-sheet-handle" aria-hidden="true"></div>@@ -1041,35 +1318,36 @@</div><!-- Agent interaction bottom sheet (slides up when user taps a nearby pin label or 3D model) -->-<div id="irl-sheet" role="dialog" aria-modal="false" aria-label="Nearby agent">+<!-- Dimmed backdrop behind the inspect card — click to dismiss. Stays in the DOM+ (opacity/pointer-events toggled via .is-open) so it can fade in and out. -->+<div id="irl-sheet-backdrop"></div>+<div id="irl-sheet" role="dialog" aria-modal="false" aria-label="Nearby agent" tabindex="-1"><div class="irl-sheet-handle" aria-hidden="true"></div><div class="irl-sheet-header">+ <img id="irl-sheet-thumb" class="irl-sheet-thumb" alt="" hidden /><div class="irl-sheet-meta">- <div class="irl-sheet-title" id="irl-sheet-name">Agent</div>+ <div class="irl-sheet-title-row">+ <span class="irl-sheet-title" id="irl-sheet-name">Agent</span>+ <span id="irl-sheet-tier" class="irl-tier-badge" hidden></span>+ </div><div class="irl-sheet-dist" id="irl-sheet-dist"></div></div><button class="irl-sheet-close" id="irl-sheet-close" type="button" aria-label="Close">×</button></div><p id="irl-sheet-caption" hidden></p>- <!-- Enriched agent data (populated async from /api/irl/agent-card) -->- <p id="irl-sheet-description" hidden></p>- <div id="irl-sheet-rep" class="irl-sheet-rep" hidden>- <span class="irl-rep-bar" aria-hidden="true"><span id="irl-rep-fill" class="irl-rep-fill"></span></span>- <span id="irl-rep-text" class="irl-rep-text"></span>- </div>- <div id="irl-sheet-skills" class="irl-sheet-skills" hidden></div>- <div id="irl-sheet-services" class="irl-sheet-services" hidden>- <div class="irl-services-label">Services</div>- <div id="irl-services-list" class="irl-services-list"></div>- </div>+ <!-- Rich card body — skeleton → bio + reputation + services | empty | error.+ Rendered entirely from /api/irl/agent-card by openPinSheet(). -->+ <div id="irl-card-body" class="irl-card-body"></div><div class="irl-multiplayer-note" id="irl-sheet-multiplayer" hidden><span class="irl-multiplayer-dot"></span><span id="irl-sheet-multiplayer-text">Visible to all users at this location</span></div>- <p id="irl-sheet-views" hidden></p>+ <!-- Honest GPS-accuracy line (A3) — never imply a centimetre-perfect pinpoint -->+ <p id="irl-sheet-accuracy" class="irl-sheet-accuracy" hidden></p><div class="irl-sheet-actions"><button id="irl-sheet-pay" class="irl-sheet-btn irl-sheet-btn-primary" type="button" hidden>Pay via x402</button>- <button id="irl-sheet-view" class="irl-sheet-btn" type="button">View agent</button>+ <button id="irl-sheet-calibrate" class="irl-sheet-btn" type="button" hidden>Calibrate position</button>+ <button id="irl-sheet-view" class="irl-sheet-btn" type="button">View profile</button></div><!-- Leave a message — POSTs an interaction the owner sees in their dashboard feed --><form id="irl-sheet-msg" class="irl-sheet-msg">@@ -1092,6 +1370,80 @@<div id="irl-agents-list"><p class="irl-agents-empty">Loading…</p></div></div>+<!-- ── Calibrate HUD (A3) — owner nudges a placed agent into its true spot ──── -->+<style>+ #irl-calibrate-panel {+ position: fixed; left: 0; right: 0; bottom: 0; z-index: 60;+ padding: 16px 18px calc(18px + env(safe-area-inset-bottom, 0px));+ background: linear-gradient(180deg, rgba(13,16,24,0.96), rgba(9,11,17,0.99));+ border-top: 1px solid rgba(255,255,255,0.10);+ border-radius: 18px 18px 0 0;+ box-shadow: 0 -12px 40px rgba(0,0,0,0.5);+ transform: translateY(108%); transition: transform .28s cubic-bezier(.22,.61,.36,1);+ max-width: 560px; margin: 0 auto;+ }+ #irl-calibrate-panel.is-open { transform: translateY(0); }+ #irl-calibrate-panel .irl-sheet-handle { width: 38px; height: 4px; border-radius: 99px; background: rgba(255,255,255,0.22); margin: 0 auto 12px; }+ .irl-cal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 4px; }+ .irl-cal-head h3 { margin: 0; font-size: 15.5px; font-weight: 700; color: #e8edf6; letter-spacing: -.01em; }+ #irl-cal-readout { font: 600 12.5px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace; color: #7dd3fc; margin: 2px 0 8px; }+ #irl-cal-accuracy { margin: 0 0 12px; font-size: 12.5px; line-height: 1.5; color: #93a1b5; }+ #irl-cal-accuracy.is-low { color: #fbbf73; }+ .irl-cal-hint { margin: 0 0 12px; font-size: 12px; line-height: 1.5; color: #6b7686; }+ .irl-cal-height { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; }+ .irl-cal-height-label { font-size: 12.5px; color: #93a1b5; flex: 1; }+ .irl-cal-height-val { font: 600 12.5px ui-monospace, monospace; color: #cdd6e4; min-width: 56px; text-align: right; }+ .irl-cal-step { width: 40px; height: 40px; border-radius: 11px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.06); color: #e5e7eb; font: 600 18px inherit; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: background .15s, border-color .15s; }+ .irl-cal-step:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.22); }+ .irl-cal-step:active { transform: translateY(1px); }+ .irl-cal-step:focus-visible { outline: 2px solid rgba(125,211,252,0.6); outline-offset: 2px; }+ #irl-cal-error { margin-bottom: 12px; }+ #irl-cal-error .tws-es { padding: 14px 8px 8px; }+ .irl-cal-actions { display: flex; gap: 10px; }+ #irl-cal-save { flex: 1; padding: 12px 16px; border-radius: 12px; border: 1px solid rgba(52,211,153,0.4); background: rgba(52,211,153,0.18); color: #34d399; font: 600 14px inherit; cursor: pointer; transition: background .15s; }+ #irl-cal-save:hover { background: rgba(52,211,153,0.28); }+ #irl-cal-save:disabled { opacity: .55; cursor: default; }+ #irl-cal-save:focus-visible { outline: 2px solid rgba(52,211,153,0.6); outline-offset: 2px; }+ #irl-cal-cancel { padding: 12px 16px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.12); background: rgba(255,255,255,0.06); color: #cbd3df; font: 600 14px inherit; cursor: pointer; transition: background .15s; }+ #irl-cal-cancel:hover { background: rgba(255,255,255,0.12); color: #fff; }+ #irl-cal-cancel:focus-visible { outline: 2px solid rgba(255,255,255,0.4); outline-offset: 2px; }+ /* While calibrating, suppress the walk joystick so a drag can't grab it. */+ body.is-calibrating #irl-joystick { display: none !important; }+ /* Denied toast — centred, fades in/out (opacity + pointer-events via .is-open). */+ #irl-cal-denied {+ position: fixed; left: 50%; top: 50%; transform: translate(-50%, -46%);+ z-index: 70; width: min(360px, calc(100vw - 40px));+ background: rgba(12,14,21,0.97); border: 1px solid rgba(255,255,255,0.12);+ border-radius: 16px; box-shadow: 0 16px 48px rgba(0,0,0,0.55);+ opacity: 0; pointer-events: none; transition: opacity .2s ease, transform .2s ease;+ }+ #irl-cal-denied.is-open { opacity: 1; pointer-events: auto; transform: translate(-50%, -50%); }+ /* Honest accuracy line inside the inspect sheet (A3). */+ .irl-sheet-accuracy { margin: 0 0 12px; font-size: 12px; line-height: 1.5; color: #8a94a6; }+ .irl-sheet-accuracy.is-low { color: #fbbf73; }+</style>+<div id="irl-calibrate-panel" role="dialog" aria-modal="false" aria-label="Calibrate agent position">+ <div class="irl-sheet-handle" aria-hidden="true"></div>+ <div class="irl-cal-head">+ <h3 id="irl-cal-title">Calibrate position</h3>+ </div>+ <div id="irl-cal-readout" aria-live="polite">0.00 m N · 0.00 m E · +0° · +0 cm</div>+ <p id="irl-cal-accuracy"></p>+ <p class="irl-cal-hint">Drag to nudge on the ground · twist with two fingers to rotate.</p>+ <div class="irl-cal-height">+ <span class="irl-cal-height-label">Floor height</span>+ <span class="irl-cal-height-val" id="irl-cal-height">+0 cm</span>+ <button class="irl-cal-step" id="irl-cal-down" type="button" aria-label="Lower agent 5 cm">−</button>+ <button class="irl-cal-step" id="irl-cal-up" type="button" aria-label="Raise agent 5 cm">+</button>+ </div>+ <div id="irl-cal-error" hidden></div>+ <div class="irl-cal-actions">+ <button id="irl-cal-save" type="button">Save position</button>+ <button id="irl-cal-cancel" type="button">Cancel</button>+ </div>+</div>+<div id="irl-cal-denied" role="alertdialog" aria-modal="false" aria-label="Calibration locked" hidden></div>+<script type="module" src="/src/irl.js"></script><script>diff --git a/public/changelog.json b/public/changelog.jsonindex 6afe34201..c2182dffe 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,73 @@{- "generated_at": "2026-06-17T00:14:19.759Z",+ "generated_at": "2026-06-17T02:22:10.871Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Everyone at a location now sees your IRL agent in the same real spot",+ "summary": "three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry.",+ "link": "/irl",+ "tags": [+ "feature",+ "improvement"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk",+ "summary": "iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated.",+ "link": "/irl",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "IRL agents now materialize as you walk up to them",+ "summary": "On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going.",+ "link": "/irl",+ "tags": [+ "fix",+ "improvement"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "IRL agents turn to look at you as you move around them",+ "summary": "On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you.",+ "link": "/irl",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Place your IRL agent on the real floor with AR anchoring",+ "summary": "On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.",+ "link": "/irl",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "Tapping an IRL agent is now reliable — hit the body, not just the tiny label",+ "summary": "On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap.",+ "link": "/irl",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-16","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 069f9cea3..6a7a40727 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,54 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Everyone at a location now sees your IRL agent in the same real spot</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Everyone at a location now sees your IRL agent in the same real spot</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry.</description>+ </item>+ <item>+ <title>iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:iPhone now world-locks your IRL agent — it holds its real spot as you pan and walk</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>iPhone Safari has no AR mode, so a placed agent used to drift with the camera. On three.ws/irl it now stays anchored to its real-world spot using the compass and GPS: pan your phone and the agent holds its real bearing instead of following the view, and walk toward it and it grows and keeps its place. Tapping Pin here saves the full placement — facing, ground height, and how good your GPS fix was — so iPhone placements match the AR-anchored version other phones see. If you pin before your location is ready, it waits for the first fix and pins precisely instead of dropping at a default spot. Permission states are designed and recoverable too: if motion or location access is off you get a clear card with the exact iOS Settings path and a Try again button, and if your phone can't read an absolute compass heading you're warned that others may see the agent rotated.</description>+ </item>+ <item>+ <title>IRL agents now materialize as you walk up to them</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:IRL agents now materialize as you walk up to them</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>On three.ws/irl, a 3D agent placed further away first appears as a glowing beacon to keep things light. Previously it stayed a beacon even after you walked right up to it; now it upgrades to the full 3D avatar the moment you come within range, so approaching an agent in real life actually reveals it. Distance to each nearby agent is also recalculated live as you move instead of being frozen at the moment you arrived. Long AR sessions are smoother too: agents that leave the area now fully release their 3D model from memory instead of quietly accumulating, which keeps the camera view fast when you're somewhere busy with lots of agents coming and going.</description>+ </item>+ <item>+ <title>IRL agents turn to look at you as you move around them</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:IRL agents turn to look at you as you move around them</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>On three.ws/irl, a placed 3D agent now notices the viewer. As you move your phone around it, it eases its body toward your camera and layers on a natural head turn so it appears to look right at you — the real-world version of a desktop avatar that follows your cursor. The head movement is clamped to a realistic neck range so it never over-rotates, and an avatar with no head bone falls back to a clean whole-body turn. Back away and the agent eases home to the heading it was placed at. When nobody is close it shows a subtle idle gaze drift instead of a frozen stare, and the first time you step within a few metres it gives a brief notice reaction. Motion is eased throughout and only the nearest on-screen agents are tracked each frame, so it stays smooth even with several agents around you.</description>+ </item>+ <item>+ <title>Place your IRL agent on the real floor with AR anchoring</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Place your IRL agent on the real floor with AR anchoring</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>On AR-capable phones (Android Chrome), three.ws/irl now lets you point at your actual floor through a placement ring and tap to set your agent on that exact spot. It binds to a real-world anchor, so it stays put as you walk around it instead of sliding with the camera or jittering with GPS — the world-locked placement you'd expect from a top AR app. Each placement is saved as a pin, capturing the floor height, facing, and how good your GPS fix was, so it reloads near the same place and nearby people can see it. iPhone, which doesn't support this AR mode, keeps the existing compass-based Pin here flow and simply doesn't show the floor button.</description>+ </item>+ <item>+ <title>Tapping an IRL agent is now reliable — hit the body, not just the tiny label</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-06-17:Tapping an IRL agent is now reliable — hit the body, not just the tiny label</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>On three.ws/irl you can now open an agent by tapping its 3D body, not only its small floating name tag. Tapping near a name also works, with a finger-sized target that meets Apple's 44-pixel minimum, so you no longer have to pixel-hunt on a phone. When two agents stand on top of each other, the one in front wins instead of a random pick. As you move, the nearest agent you can reach lights up with a soft focus ring so you can see what you'll tap before you tap it — and if you've turned on Reduce Motion, the ring stays still. Looking and panning around no longer misfires as a tap.</description>+ </item><item><title>Agent Activity — Oracle conviction in real time</title><link>https://three.ws/activity</link>diff --git a/public/features.json b/public/features.jsonindex 2ee8e5ca5..618f3fdc4 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T00:14:19.742Z",+ "generated_at": "2026-06-17T02:22:10.851Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 81eec51d8..41689933e 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,6 +56,20 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>++ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="Sitemap · three.ws">+ <meta property="og:description" content="Human-readable index of every page on three.ws.">+ <meta property="og:url" content="https://three.ws/sitemap">+ <meta property="og:image" content="https://three.ws/og-image.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="Sitemap · three.ws">+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">+ <meta name="twitter:image" content="https://three.ws/og-image.png">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script></head><body><header class="sm-topbar">diff --git a/src/ar/webxr.js b/src/ar/webxr.jsindex 1a960e236..25b169fef 100644--- a/src/ar/webxr.js+++ b/src/ar/webxr.js@@ -8,7 +8,7 @@// The live AR button on the main viewer enters XR with the full body, exactly// as it did before the half-body work was added.-import { Matrix4, Vector3 } from 'three';+import { Matrix4, Mesh, MeshBasicMaterial, Quaternion, RingGeometry, Vector3 } from 'three';const LOWER_BODY_FRAGMENTS = ['upleg', 'leg', 'thigh', 'knee', 'shin', 'calf',@@ -30,14 +30,40 @@ function _isLowerBody(name) {}export class WebXRSession {- constructor(viewer, { onEnd, halfBody = false } = {}) {+ /**+ * @param {object} viewer Object exposing { renderer, scene, content, controls,+ * activeCamera, animationManager, mixer, prevTime, _rafId, _afterAnimateHooks,+ * _needsRender, _updateRenderLoop } — see src/xr.js for the canonical shim.+ * @param {object} [opts]+ * @param {Function} [opts.onEnd] Called after the XR session ends + restores.+ * @param {boolean} [opts.halfBody] Collapse lower-body bones (demo mode).+ * @param {Function} [opts.onAnchored] Called once on first tap with the anchored+ * local-space pose `{ position: Vector3, quaternion: Quaternion }` for persistence.+ * @param {Function} [opts.onHit] Called with `true`/`false` as the hit-test+ * reticle gains/loses a surface — drives the "point at the floor" searching state.+ * @param {Element} [opts.domOverlayRoot] Element to surface as the WebXR+ * `dom-overlay` root (in-session hint + exit affordance). Optional.+ */+ constructor(viewer, { onEnd, halfBody = false, onAnchored, onHit, domOverlayRoot } = {}) {this._viewer = viewer;this._halfBody = halfBody;this._onEnd = onEnd;+ this._onAnchored = onAnchored;+ this._onHit = onHit;+ this._domOverlayRoot = domOverlayRoot ?? null;this._session = null;this._hitTestSource = null;this._localSpace = null;this._anchored = false;+ /** @type {XRAnchor|null} Real world anchor created on tap (feature-detected). */+ this._anchor = null;+ /** @type {XRHitTestResult|null} Most recent hit, used to create the anchor. */+ this._latestHit = null;+ /** Tap-moment hit pose, captured for persistence the instant the user taps. */+ this._latestHitMatrix = new Matrix4();+ this._hasHit = false;+ /** @type {import('three').Mesh|null} Ring reticle tracking the floor. */+ this._reticle = null;this._userPosition = new Vector3();this._savedBg = null;this._savedPos = null;@@ -63,9 +89,19 @@ export class WebXRSession {// Must be set before requestSessionrenderer.xr.enabled = true;- const session = await navigator.xr.requestSession('immersive-ar', {+ // `anchors` lets us bind the agent to a real XRAnchor (no drift); it is+ // optional so devices without it still run on hit-test-follow. `dom-overlay`+ // surfaces the in-session hint + exit affordance when a root is supplied.+ const sessionInit = {requiredFeatures: ['hit-test'],- });+ optionalFeatures: ['anchors', 'local-floor'],+ };+ if (this._domOverlayRoot) {+ sessionInit.optionalFeatures.push('dom-overlay');+ sessionInit.domOverlay = { root: this._domOverlayRoot };+ }++ const session = await navigator.xr.requestSession('immersive-ar', sessionInit);this._session = session;session.addEventListener('end', this._handleEnd);// 'select' fires on controller trigger or screen tap@@ -77,6 +113,10 @@ export class WebXRSession {const viewerSpace = await session.requestReferenceSpace('viewer');this._hitTestSource = await session.requestHitTestSource({ space: viewerSpace });+ // Floor reticle — a thin ring laid flat (geometry rotated into the XZ plane+ // so the hit pose's up-normal keeps it on the surface). Hidden until a hit.+ this._buildReticle();+// Transparent background — device camera provides the pass-throughthis._savedBg = viewer.scene.background;viewer.scene.background = null;@@ -120,25 +160,104 @@ export class WebXRSession {const xrCam = renderer.xr.getCamera();if (xrCam) this._userPosition.setFromMatrixPosition(xrCam.matrixWorld);- // Follow hit-test surface until the agent is anchored by a tap+ // Before anchoring: the reticle (and a content preview) track the floor the+ // phone is pointed at. After a tap, a real XRAnchor takes over (below).if (!this._anchored && frame && this._hitTestSource) {const hits = frame.getHitTestResults(this._hitTestSource);- if (hits.length > 0 && viewer.content) {- const pose = hits[0].getPose(this._localSpace);- if (pose) {- viewer.content.position.setFromMatrixPosition(- new Matrix4().fromArray(pose.transform.matrix),- );+ const pose = hits.length > 0 ? hits[0].getPose(this._localSpace) : null;+ if (pose) {+ this._latestHit = hits[0];+ this._latestHitMatrix.fromArray(pose.transform.matrix);+ if (this._reticle) {+ this._reticle.visible = true;+ this._reticle.position.setFromMatrixPosition(this._latestHitMatrix);+ this._reticle.quaternion.setFromRotationMatrix(this._latestHitMatrix);+ }+ if (viewer.content) {+ viewer.content.position.setFromMatrixPosition(this._latestHitMatrix);}+ this._setHit(true);+ } else {+ this._latestHit = null;+ if (this._reticle) this._reticle.visible = false;+ this._setHit(false);+ }+ }++ // Anchored: drive content from the live anchor pose every frame so it stays+ // glued to the real world as the camera moves (position only — the agent's+ // own orientation/scale are preserved). A null anchor (createAnchor missing)+ // leaves content frozen at the tap point — degraded hit-follow, never broken.+ if (this._anchor && frame) {+ const pose = frame.getPose(this._anchor.anchorSpace, this._localSpace);+ if (pose && viewer.content) {+ const p = pose.transform.position;+ viewer.content.position.set(p.x, p.y, p.z);}}renderer.render(viewer.scene, viewer.activeCamera);}- // First tap anchors the agent at the current hit-test position- _handleSelect() {+ // First tap anchors the agent at the current hit-test position. Creates a real+ // XRAnchor when the device supports it (survives the small tracking corrections+ // a raw hit pose does not); falls back to frozen hit-follow otherwise.+ async _handleSelect() {+ if (this._anchored || !this._latestHit) return;this._anchored = true;+ // Capture the tap-moment pose now — before the anchor's own drift correction+ // nudges it — so the persisted GPS pin matches where the user actually tapped.+ const anchorPose = this._readAnchorPose();+ if (this._reticle) this._reticle.visible = false;+ this._setHit(false);+ try {+ this._anchor = (await this._latestHit.createAnchor?.()) ?? null;+ } catch {+ // Anchor creation can reject on devices that advertise but can't honour+ // the feature — fall back to the frozen tap pose rather than failing.+ this._anchor = null;+ }+ this._onAnchored?.(anchorPose);+ }++ // Build the floor reticle: a flat ring whose geometry is pre-rotated into the+ // XZ plane so the hit pose (Y = surface normal) lays it on the surface.+ _buildReticle() {+ const geo = new RingGeometry(0.08, 0.11, 36).rotateX(-Math.PI / 2);+ const mat = new MeshBasicMaterial({+ color: 0x9b8cff, transparent: true, opacity: 0.9, depthTest: false,+ });+ const ring = new Mesh(geo, mat);+ ring.renderOrder = 999; // draw over the passthrough + agent+ ring.matrixAutoUpdate = true;+ ring.visible = false;+ this._reticle = ring;+ this._viewer.scene.add(ring);+ }++ _disposeReticle() {+ if (!this._reticle) return;+ this._viewer.scene.remove(this._reticle);+ this._reticle.geometry?.dispose();+ this._reticle.material?.dispose();+ this._reticle = null;+ }++ // Notify the host only on transitions (searching ↔ surface found), not per frame.+ _setHit(has) {+ if (has === this._hasHit) return;+ this._hasHit = has;+ this._onHit?.(has);+ }++ // Decompose the captured tap-moment hit matrix into a local-space pose the host+ // converts to a GPS pin (metres from the session origin → lat/lng + floor height).+ _readAnchorPose() {+ const position = new Vector3();+ const quaternion = new Quaternion();+ const scale = new Vector3();+ this._latestHitMatrix.decompose(position, quaternion, scale);+ return { position, quaternion };}// Returns the current XR camera (user head) position for lookAt('user')@@ -168,8 +287,12 @@ export class WebXRSession {} catch {}this._hitTestSource = null;}+ this._disposeReticle();this._session = null;this._anchored = false;+ this._anchor = null;+ this._latestHit = null;+ this._hasHit = false;// Restore backgroundviewer.scene.background = this._savedBg;diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.jsindex 69aaaf452..74393abfb 100644--- a/src/dashboard-next/pages/irl-placements.js+++ b/src/dashboard-next/pages/irl-placements.js@@ -23,7 +23,40 @@// DELETE /api/irl/pins?id=<id> → { ok: true }import { mountShell } from '../shell.js';-import { requireUser, get, patch, esc, relTime } from '../api.js';+import { requireUser, get, post, patch, esc, relTime } from '../api.js';+import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry } from '../../shared/state-kit.js';++// ── Services / x402 skill pricing ───────────────────────────────────────────+// Canonical prices live in agent_skill_prices and feed the x402 manifest ++// priceFor() (api/agents/x402/[action].js). The owner attaches a skill the+// agent exposes and sets a per-call price; a passer-by then pays for it IRL.++// Solana mint validity — matches api/agent-skill-price.js:14. Base-chain USDC is+// a 0x EVM address that fails this, so IRL skill pricing is Solana-mint only.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// The only currencies offered — the platform coin and Solana USDC. Both are+// 6-decimal SPL mints, so the displayed price (e.g. 0.05) converts to atomic+// units with 10**6. Never a third token.+const CURRENCIES = [+ { key: 'three', label: '$THREE', mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', decimals: 6, chain: 'solana' },+ { key: 'usdc', label: 'USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', decimals: 6, chain: 'solana' },+];+function currencyForMint(mint) {+ return CURRENCIES.find((c) => c.mint === mint)+ || { label: `${String(mint).slice(0, 4)}…${String(mint).slice(-4)}`, mint, decimals: 6, chain: 'solana' };+}+// Displayed decimal → integer atomic units (what the API stores).+function toAtomic(display, decimals) {+ return Math.round(Number(display) * 10 ** decimals);+}+// Integer atomic units → human price string (maximumFractionDigits drops any+// trailing zeros, so 50000 @ 6dp → "0.05", 1000000 @ 6dp → "1").+function fromAtomic(amount, decimals) {+ const n = Number(amount) / 10 ** decimals;+ if (!Number.isFinite(n)) return '0';+ return n.toLocaleString('en-US', { maximumFractionDigits: decimals });+}function haversineDist(lat1, lng1, lat2, lng2) {const R = 6371000;@@ -50,6 +83,19 @@ function expiryLabel(expiresAt) {return `<span class="irl-badge expiring">Expires in ${days}d ${hrs}h</span>`;}+// Live status pill from the agent-summary-derived status. Self-contained+// (inline token colours) so it has no external CSS dependency.+const STATUS_META = {+ online: { c: 'var(--nxt-success, #4ade80)', label: 'Online' },+ visible: { c: 'var(--nxt-warn, #fbbf24)', label: 'Visible' },+ expired: { c: 'var(--nxt-ink-faint, #555)', label: 'Expired' },+};+function statusBadge(status) {+ const s = STATUS_META[status] || STATUS_META.visible;+ return `<span class="irl-status-pill" title="${s.label}" style="display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;color:${s.c};flex-shrink:0">`+ + `<span style="width:7px;height:7px;border-radius:50%;background:${s.c}"></span>${s.label}</span>`;+}+// Derive the avatar-editor (wardrobe) URL from a pin's avatar_url. IRL pins store// either /api/avatars/<id>/glb or /avatars/<id>... — pull the id so "Change outfit"// deep-links to the real wardrobe; fall back to the avatars dashboard otherwise.@@ -137,6 +183,56 @@ const STYLE = `.irl-svc-price { color: var(--nxt-success); font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; }.irl-svc-empty { font-size: 12px; color: var(--nxt-ink-faint); }+/* Inline link-style button (matches section-label affordances) */+.irl-link-btn { background: none; border: none; padding: 0; cursor: pointer; color: var(--nxt-accent); font: inherit; font-size: 12px; font-weight: 600; }+.irl-link-btn:hover { text-decoration: underline; }+.irl-link-btn:disabled { opacity: .6; cursor: default; text-decoration: none; }+.irl-link-btn.danger { color: var(--nxt-danger, #f87171); }++/* ── Services management modal ─────────────────────────────────────────────── */+.irl-modal-root { position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center; padding: 16px; }+.irl-modal-back { position: absolute; inset: 0; background: rgba(0,0,0,.62); backdrop-filter: blur(2px); animation: irl-fade .16s ease; }+.irl-modal { position: relative; width: min(560px, 100%); max-height: min(86vh, 760px); display: flex; flex-direction: column; background: var(--nxt-panel, var(--nxt-bg-1)); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); box-shadow: 0 24px 64px rgba(0,0,0,.5); animation: irl-rise .2s cubic-bezier(.2,.7,.3,1); overflow: hidden; }+.irl-modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 16px 18px; border-bottom: 1px solid var(--nxt-stroke); }+.irl-modal-title { font-size: 16px; font-weight: 700; color: var(--nxt-ink); }+.irl-modal-sub { font-size: 12px; color: var(--nxt-ink-faint); margin-top: 2px; }+.irl-modal-x { background: none; border: none; color: var(--nxt-ink-faint); font-size: 22px; line-height: 1; cursor: pointer; padding: 0 4px; border-radius: 8px; transition: color .14s; }+.irl-modal-x:hover, .irl-modal-x:focus-visible { color: var(--nxt-ink); outline: none; }+.irl-modal-body { padding: 6px 18px 18px; overflow-y: auto; }+.irl-svc-sec { padding-top: 14px; }+.irl-svc-sec-h { font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: var(--nxt-ink-faint); margin-bottom: 10px; }+.irl-svc-count { color: var(--nxt-ink-dim); }++/* Priced-service rows */+.irl-pr-row { display: grid; grid-template-columns: 1fr auto; gap: 4px 12px; align-items: center; padding: 11px 13px; border-radius: 10px; border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); margin-bottom: 8px; transition: border-color .2s, background .2s; }+.irl-pr-row.paused { opacity: .72; }+.irl-pr-row.saved { border-color: color-mix(in srgb, var(--nxt-success) 60%, transparent); background: color-mix(in srgb, var(--nxt-success) 9%, var(--nxt-bg-2)); }+.irl-pr-name { font-size: 14px; font-weight: 600; color: var(--nxt-ink); display: flex; align-items: center; gap: 8px; }+.irl-pr-tag { font-size: 10px; text-transform: uppercase; letter-spacing: .04em; padding: 1px 6px; border-radius: 999px; background: var(--nxt-bg-1); border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-faint); font-weight: 600; }+.irl-pr-meta { font-size: 12px; color: var(--nxt-ink-faint); margin-top: 2px; }+.irl-pr-price { color: var(--nxt-success); font-weight: 700; font-variant-numeric: tabular-nums; }+.irl-pr-actions { grid-column: 2; grid-row: 1 / span 2; display: flex; align-items: center; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }+.irl-pr-input { width: 84px; padding: 5px 8px; border-radius: 8px; border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-1); color: var(--nxt-ink); font: inherit; font-size: 13px; }+.irl-pr-input:focus-visible { outline: none; border-color: var(--nxt-accent); }+.irl-pr-cur { font-size: 12px; color: var(--nxt-ink-faint); }+.irl-pr-confirm { font-size: 12px; color: var(--nxt-ink-dim); }+.irl-pr-err { grid-column: 1 / -1; font-size: 12px; color: var(--nxt-danger, #f87171); }++/* Add-service form */+.irl-add-form { display: flex; flex-direction: column; gap: 12px; }+.irl-add-grid { display: grid; grid-template-columns: 1.3fr .9fr .9fr; gap: 10px; }+.irl-add-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; }+.irl-add-field > span { font-size: 11px; color: var(--nxt-ink-faint); text-transform: uppercase; letter-spacing: .04em; }+.irl-add-field select, .irl-add-field input { padding: 9px 10px; border-radius: 9px; border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); font: inherit; font-size: 13px; width: 100%; }+.irl-add-field select:focus-visible, .irl-add-field input:focus-visible { outline: none; border-color: var(--nxt-accent); }+.irl-add-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }+.irl-add-hint { font-size: 11px; color: var(--nxt-ink-faint); }+.irl-add-err { font-size: 12px; color: var(--nxt-danger, #f87171); }+@media (max-width: 520px) { .irl-add-grid { grid-template-columns: 1fr 1fr; } .irl-add-field:first-child { grid-column: 1 / -1; } }++@keyframes irl-fade { from { opacity: 0; } to { opacity: 1; } }+@keyframes irl-rise { from { opacity: 0; transform: translateY(10px) scale(.99); } to { opacity: 1; transform: none; } }+/* Interactions feed */.irl-ix { display: flex; gap: 9px; padding: 6px 0; }.irl-ix-icon { font-size: 14px; line-height: 1.4; flex-shrink: 0; }@@ -210,7 +306,10 @@ function cardHtml(pin, ixList) {<div class="irl-card-head">${img}<div class="irl-info">- <div class="irl-name">${esc(pin.avatar_name || 'Placed agent')}</div>+ <div class="irl-name-row" style="display:flex;align-items:center;gap:8px;min-width:0">+ <span class="irl-name">${esc(pin.avatar_name || 'Placed agent')}</span>+ ${statusBadge(pin.status)}+ </div><div class="irl-meta"><span class="irl-meta-loc">${esc(metaLine(pin, null))}</span>${expiryLabel(pin.expires_at)}@@ -220,11 +319,14 @@ function cardHtml(pin, ixList) {<div class="irl-stats">${agentStats}- <div class="irl-stat"><span class="k">Visitors</span><span class="v">${visitors}</span></div>+ <div class="irl-stat"><span class="k">Interactions</span><span class="v">${Number(pin.interaction_count) || visitors}</span></div>+ <div class="irl-stat"><span class="k">Last seen</span><span class="v" style="font-size:12.5px">${esc(pin.last_interaction_at ? relTime(pin.last_interaction_at) : 'No visits')}</span></div></div><div class="irl-section" data-skills-section hidden>- <div class="irl-section-label">Skills</div>+ <div class="irl-section-label">Skills+ <button class="irl-link-btn" data-manage-services type="button">Manage prices →</button>+ </div><div class="irl-skills" data-skills-list></div></div>@@ -278,31 +380,35 @@ async function mount(el) {</div>`;const list = el.querySelector('#irl-list');- list.innerHTML = Array.from({ length: 3 }, () => `<div class="irl-skel"></div>`).join('');+ list.innerHTML = skeletonHTML(3, 'row');// Pins + interactions in parallel — interactions power both the banner and// each card's IRL feed.let pins, interactions = [], unread = 0;try {- const [pinsData, ixData] = await Promise.all([- get('/api/irl/pins?mine=1'),+ const [sumData, ixData] = await Promise.all([+ get('/api/irl/agent-summary?mine=1'),get('/api/irl/interactions?mine=1').catch(() => ({ interactions: [], unread: 0 })),]);- pins = pinsData.pins || [];+ // agent-summary keys each row by pin_id and adds derived monitoring signals+ // (status, interaction_count, last_interaction_at). Normalize pin_id→id so+ // the existing card code is unchanged.+ pins = (sumData.agents || []).map((a) => ({ ...a, id: a.pin_id }));interactions = ixData.interactions || [];unread = ixData.unread || 0;} catch {- list.innerHTML = `<div class="irl-empty"><b>Failed to load placements</b>Try refreshing the page.</div>`;+ list.innerHTML = errorStateHTML({ title: "Couldn't load your IRL agents", body: 'Check your connection and try again.', scope: 'irl' });+ attachRetry(list, () => mount(el));return;}if (!pins.length) {- list.innerHTML = `<div class="irl-empty">- <b>No agents placed yet</b>- Open IRL, enable your camera, and pin an agent to a real-world spot — it becomes visible to everyone who visits that location.- <br><br>- <a class="irl-btn primary" href="/irl">Open IRL →</a>- </div>`;+ list.innerHTML = emptyStateHTML({+ icon: '📍',+ title: 'No agents placed yet',+ body: 'Open IRL, enable your camera, and pin an agent to a real-world spot — it becomes visible to everyone who visits that location.',+ actions: [{ label: 'Open IRL', href: '/irl', primary: true }],+ });el.querySelector('#irl-place-btn').textContent = '+ Place agent ↗';return;}@@ -363,11 +469,16 @@ async function mount(el) {}).catch(() => {});- // Live wallet balance.- fetch(`/api/agents/${encodeURIComponent(pin.agent_id)}/solana`)+ // Live wallet balance. The authenticated owner path returns { data: { sol,+ // lamports, balance_error } } (no `balance` field — that only exists on the+ // public-read shape), so read `sol` and surface RPC throttling explicitly+ // instead of silently rendering "—" for every owned agent.+ fetch(`/api/agents/${encodeURIComponent(pin.agent_id)}/solana`, { credentials: 'include' }).then((r) => (r.ok ? r.json() : null)).then((data) => {- const bal = data?.data?.balance;+ const d = data?.data || data || {};+ if (d.balance_error) { fillStat(card, 'balance', 'Unavailable'); return; }+ const bal = d.balance ?? d.sol;fillStat(card, 'balance', bal == null ? '—' : `◎${Number(bal).toFixed(2)}`);}).catch(() => fillStatError(card, 'balance'));@@ -407,8 +518,11 @@ function renderServices(card, services) {return;}listEl.innerHTML = services.map((s) => {- const price = s.price_usdc != null ? `$${Number(s.price_usdc).toFixed(2)} ${(s.network || 'base').toUpperCase()}` : 'Free';- return `<div class="irl-svc"><span class="irl-svc-name">${esc(s.name || s.slug)}</span><span class="irl-svc-price">${esc(price)}</span></div>`;+ // agent-card v2 shape: services carry price_usd + chain + skill (was price_usdc/network/slug).+ const priceVal = s.price_usd ?? s.price_usdc;+ const chain = s.chain || s.network || 'base';+ const price = priceVal != null ? `$${Number(priceVal).toFixed(2)} ${String(chain).toUpperCase()}` : 'Free';+ return `<div class="irl-svc"><span class="irl-svc-name">${esc(s.name || s.skill || s.slug)}</span><span class="irl-svc-price">${esc(price)}</span></div>`;}).join('');}@@ -418,6 +532,16 @@ function wireCardEvents(list, pins) {if (!card) return;const id = card.dataset.id;+ // Manage paid services (x402 skill pricing) for this agent+ if (e.target.closest('[data-manage-services]')) {+ const agentId = card.dataset.agent;+ if (agentId) {+ const name = card.querySelector('.irl-name')?.textContent?.trim() || 'agent';+ openServicesModal(agentId, name);+ }+ return;+ }+// Removeconst removeBtn = e.target.closest('[data-remove]');if (removeBtn) {@@ -466,7 +590,9 @@ function wireCardEvents(list, pins) {if (!isFinite(lat) || !isFinite(lng)) { btn.textContent = 'Invalid coordinates'; return; }btn.disabled = true; btn.textContent = 'Saving…';try {- const r = await patch('/api/irl/pins', { id, lat, lng, heading: isFinite(heading) ? heading : 0 });+ // Omit heading when the field is blank so a blank input PRESERVES the+ // stored bearing instead of silently re-aiming the agent to North (0°).+ const r = await patch('/api/irl/pins', { id, lat, lng, ...(isFinite(heading) ? { heading } : {}) });if (r.pin) {const pin = pins.find((p) => p.id === id);if (pin) { pin.lat = r.pin.lat; pin.lng = r.pin.lng; pin.heading = r.pin.heading; }@@ -530,6 +656,358 @@ function restoreCaption(card, caption) {editEl?.replaceWith(node);}+// ── Services modal: attach/price the skills this agent offers IRL ───────────+function openServicesModal(agentId, agentName) {+ const root = makeNode(`<div class="irl-modal-root">+ <div class="irl-modal-back"></div>+ <div class="irl-modal" role="dialog" aria-modal="true" aria-label="Manage paid services">+ <div class="irl-modal-head">+ <div class="irl-modal-titles">+ <div class="irl-modal-title">Paid services</div>+ <div class="irl-modal-sub">${esc(agentName)} · pay-per-call via x402</div>+ </div>+ <button class="irl-modal-x" data-close type="button" aria-label="Close">×</button>+ </div>+ <div class="irl-modal-body" data-body>${skeletonHTML(3, 'row')}</div>+ </div>+ </div>`);+ ensureStateKitStyles();+ document.body.appendChild(root);+ document.body.style.overflow = 'hidden';++ const body = root.querySelector('[data-body]');+ const close = () => {+ root.remove();+ document.body.style.overflow = '';+ document.removeEventListener('keydown', onKey, true);+ };+ const onKey = (ev) => { if (ev.key === 'Escape') close(); };+ document.addEventListener('keydown', onKey, true);+ root.querySelector('[data-close]').addEventListener('click', close);+ root.querySelector('.irl-modal-back').addEventListener('click', close);+ setTimeout(() => root.querySelector('[data-close]')?.focus(), 0);++ // state.prices: active (+ in-session paused) agent_skill_prices rows.+ // state.skills: skills the agent actually exposes — the only priceable set.+ // state.catalog: best-effort slug→marketplace-skill metadata (name/suggested).+ const state = { prices: [], skills: [], catalog: {} };++ async function load() {+ try {+ const [pricing, agentResp] = await Promise.all([+ get(`/api/agents/${encodeURIComponent(agentId)}/skills-pricing`),+ get(`/api/agents/${encodeURIComponent(agentId)}`),+ ]);+ state.prices = (pricing?.prices || []).map((p) => ({ ...p }));+ state.skills = Array.isArray(agentResp?.agent?.skills) ? agentResp.agent.skills : [];+ try {+ const sk = await get('/api/skills?installed=true');+ const arr = Array.isArray(sk) ? sk : (sk?.skills || sk?.data?.skills || []);+ for (const s of arr) if (s?.slug) state.catalog[s.slug] = s;+ } catch { /* metadata is optional — raw skill names still work */ }+ renderShell();+ } catch {+ body.innerHTML = errorStateHTML({+ title: "Couldn't load services",+ body: 'Check your connection and try again.',+ });+ body.querySelector('[data-sk-retry]')?.addEventListener('click', () => {+ body.innerHTML = skeletonHTML(3, 'row');+ load();+ });+ }+ }++ function renderShell() {+ body.innerHTML = `+ <section class="irl-svc-sec">+ <div class="irl-svc-sec-h">Active services <span class="irl-svc-count" data-count></span></div>+ <div data-active></div>+ </section>+ <section class="irl-svc-sec">+ <div class="irl-svc-sec-h">Add a service</div>+ <div data-add></div>+ </section>`;+ renderActive();+ renderAdd();+ }++ function skillName(slug) { return state.catalog[slug]?.name || slug; }++ function renderActive() {+ const host = body.querySelector('[data-active]');+ const countEl = body.querySelector('[data-count]');+ if (countEl) countEl.textContent = state.prices.length ? `· ${state.prices.length}` : '';+ if (!host) return;+ if (!state.prices.length) {+ host.innerHTML = emptyStateHTML({+ compact: true,+ title: 'No paid services yet',+ body: 'Attach a skill below and set a per-call price so visitors can pay this agent in person.',+ });+ return;+ }+ host.innerHTML = state.prices.map(rowHtml).join('');+ }++ function rowHtml(p) {+ const cur = currencyForMint(p.currency_mint);+ const human = fromAtomic(p.amount, cur.decimals);+ const paused = !!p._paused;+ const free = Number(p.amount) === 0;+ const priceText = free ? 'Free' : `${human} ${esc(cur.label)}`;+ return `<div class="irl-pr-row${paused ? ' paused' : ''}" data-row="${esc(p.skill)}">+ <div class="irl-pr-main">+ <div class="irl-pr-name">${esc(skillName(p.skill))}${paused ? '<span class="irl-pr-tag">paused</span>' : ''}</div>+ <div class="irl-pr-meta"><span class="irl-pr-price">${priceText}</span> · ${esc(cur.label)} on ${esc(p.chain || 'solana')}</div>+ </div>+ <div class="irl-pr-actions" data-actions>+ <button class="irl-link-btn" data-edit="${esc(p.skill)}" type="button">Edit price</button>+ ${paused+ ? `<button class="irl-link-btn" data-resume="${esc(p.skill)}" type="button">Resume</button>`+ : `<button class="irl-link-btn" data-pause="${esc(p.skill)}" type="button">Pause</button>`}+ <button class="irl-link-btn danger" data-remove-svc="${esc(p.skill)}" type="button">Remove</button>+ </div>+ <div class="irl-pr-err" data-row-err hidden></div>+ </div>`;+ }++ function rowEl(skill) { return body.querySelector(`[data-row="${CSS.escape(skill)}"]`); }+ function rowError(skill, msg) {+ const e = rowEl(skill)?.querySelector('[data-row-err]');+ if (e) { e.textContent = msg; e.hidden = !msg; }+ }+ function pulse(skill) {+ const r = rowEl(skill);+ if (!r) return;+ r.classList.remove('saved'); void r.offsetWidth; r.classList.add('saved');+ }++ // Enter inline edit mode for a row's price.+ function beginEdit(skill) {+ const p = state.prices.find((x) => x.skill === skill);+ const row = rowEl(skill);+ if (!p || !row) return;+ const cur = currencyForMint(p.currency_mint);+ const actions = row.querySelector('[data-actions]');+ actions.innerHTML = `+ <input class="irl-pr-input" type="number" min="0" step="any" value="${esc(fromAtomic(p.amount, cur.decimals))}" aria-label="New price in ${esc(cur.label)}" />+ <span class="irl-pr-cur">${esc(cur.label)}</span>+ <button class="irl-link-btn" data-save-edit="${esc(skill)}" type="button">Save</button>+ <button class="irl-link-btn" data-cancel-edit type="button">Cancel</button>`;+ actions.querySelector('.irl-pr-input')?.focus();+ }++ // Write a price (atomic) for a skill via the canonical single-skill upsert.+ async function writePrice(skill, atomic, mint, chain) {+ return post(`/api/agent-skill-price?agentId=${encodeURIComponent(agentId)}`, {+ skill, amount: atomic, currency_mint: mint, chain,+ });+ }++ function renderAdd() {+ const host = body.querySelector('[data-add]');+ if (!host) return;+ const priced = new Set(state.prices.map((p) => p.skill));+ const available = state.skills.filter((s) => !priced.has(s));++ if (!state.skills.length) {+ host.innerHTML = emptyStateHTML({+ compact: true,+ title: 'This agent exposes no skills',+ body: 'Give the agent skills first, then price them here as paid services.',+ });+ return;+ }+ if (!available.length) {+ host.innerHTML = emptyStateHTML({+ compact: true,+ title: 'Every exposed skill is priced',+ body: 'Edit or pause a service above to change it.',+ });+ return;+ }++ const opts = available.map((s) => `<option value="${esc(s)}">${esc(skillName(s))}</option>`).join('');+ const curOpts = CURRENCIES.map((c, i) => `<option value="${i}">${esc(c.label)}</option>`).join('');+ host.innerHTML = `<form class="irl-add-form" data-add-form>+ <div class="irl-add-grid">+ <label class="irl-add-field">+ <span>Skill</span>+ <select data-f="skill">${opts}</select>+ </label>+ <label class="irl-add-field">+ <span>Price / call</span>+ <input data-f="amount" type="number" min="0" step="any" placeholder="0.05" inputmode="decimal" />+ </label>+ <label class="irl-add-field">+ <span>Currency</span>+ <select data-f="currency">${curOpts}</select>+ </label>+ </div>+ <div class="irl-add-row">+ <span class="irl-add-hint">0 = free / deactivated. Stored on-chain as atomic units.</span>+ <button class="irl-btn primary" data-add-submit type="submit">Add service</button>+ </div>+ <div class="irl-add-err" data-add-err hidden></div>+ </form>`;++ // Prefill a suggested price from the marketplace catalog when present.+ const form = host.querySelector('[data-add-form]');+ const skillSel = form.querySelector('[data-f="skill"]');+ const amountInput = form.querySelector('[data-f="amount"]');+ const syncSuggested = () => {+ const meta = state.catalog[skillSel.value];+ const sugg = meta && Number(meta.price_per_call_usd) > 0 ? Number(meta.price_per_call_usd) : null;+ amountInput.placeholder = sugg != null ? String(sugg) : '0.05';+ };+ skillSel.addEventListener('change', syncSuggested);+ syncSuggested();+ }++ function addError(msg) {+ const e = body.querySelector('[data-add-err]');+ if (e) { e.textContent = msg; e.hidden = !msg; }+ }++ // ── Delegated actions ────────────────────────────────────────────────────+ body.addEventListener('submit', async (e) => {+ if (!e.target.closest('[data-add-form]')) return;+ e.preventDefault();+ const form = e.target;+ const skill = form.querySelector('[data-f="skill"]').value;+ const amountRaw = form.querySelector('[data-f="amount"]').value;+ const cur = CURRENCIES[Number(form.querySelector('[data-f="currency"]').value)] || CURRENCIES[0];++ addError('');+ if (!skill) return addError('Pick a skill');+ const amount = Number(amountRaw);+ if (!(amount >= 0)) return addError('Price must be ≥ 0');+ if (!BASE58_RE.test(cur.mint)) return addError('Invalid mint');+ if (!state.skills.includes(skill)) return addError("This agent doesn't expose that skill");++ const atomic = toAtomic(amount, cur.decimals);+ const btn = form.querySelector('[data-add-submit]');+ btn.disabled = true; btn.textContent = 'Adding…';+ try {+ await writePrice(skill, atomic, cur.mint, cur.chain);+ // amount=0 deactivates server-side; only list it when it's a live price.+ const existing = state.prices.find((p) => p.skill === skill);+ if (atomic > 0) {+ if (existing) Object.assign(existing, { amount: atomic, currency_mint: cur.mint, chain: cur.chain, _paused: false });+ else state.prices.push({ skill, amount: atomic, currency_mint: cur.mint, chain: cur.chain });+ }+ renderActive(); renderAdd();+ if (atomic > 0) pulse(skill);+ } catch (err) {+ btn.disabled = false; btn.textContent = 'Add service';+ addError(err?.status === 403 ? 'Not your agent' : (err?.message || 'Could not save'));+ }+ });++ body.addEventListener('click', async (e) => {+ // Edit price+ const editBtn = e.target.closest('[data-edit]');+ if (editBtn) return beginEdit(editBtn.dataset.edit);++ // Cancel edit+ if (e.target.closest('[data-cancel-edit]')) return renderActive();++ // Save edited price+ const saveBtn = e.target.closest('[data-save-edit]');+ if (saveBtn) {+ const skill = saveBtn.dataset.saveEdit;+ const p = state.prices.find((x) => x.skill === skill);+ const input = rowEl(skill)?.querySelector('.irl-pr-input');+ if (!p || !input) return;+ const cur = currencyForMint(p.currency_mint);+ const amount = Number(input.value);+ rowError(skill, '');+ if (!(amount >= 0)) return rowError(skill, 'Price must be ≥ 0');+ const atomic = toAtomic(amount, cur.decimals);+ saveBtn.disabled = true; saveBtn.textContent = 'Saving…';+ try {+ await writePrice(skill, atomic, p.currency_mint, p.chain || cur.chain);+ if (atomic === 0) { state.prices = state.prices.filter((x) => x.skill !== skill); }+ else { p.amount = atomic; p._paused = false; }+ renderActive(); renderAdd();+ if (atomic > 0) pulse(skill);+ } catch (err) {+ saveBtn.disabled = false; saveBtn.textContent = 'Save';+ rowError(skill, err?.message || 'Could not save');+ }+ return;+ }++ // Pause (deactivate, keep amount for in-session resume)+ const pauseBtn = e.target.closest('[data-pause]');+ if (pauseBtn) {+ const skill = pauseBtn.dataset.pause;+ const p = state.prices.find((x) => x.skill === skill);+ if (!p) return;+ pauseBtn.disabled = true; pauseBtn.textContent = 'Pausing…';+ try {+ await writePrice(skill, 0, p.currency_mint, p.chain || 'solana');+ p._paused = true;+ renderActive();+ } catch (err) {+ pauseBtn.disabled = false; pauseBtn.textContent = 'Pause';+ rowError(skill, err?.message || 'Could not pause');+ }+ return;+ }++ // Resume (re-assert the retained price)+ const resumeBtn = e.target.closest('[data-resume]');+ if (resumeBtn) {+ const skill = resumeBtn.dataset.resume;+ const p = state.prices.find((x) => x.skill === skill);+ if (!p) return;+ const cur = currencyForMint(p.currency_mint);+ resumeBtn.disabled = true; resumeBtn.textContent = 'Resuming…';+ try {+ await writePrice(skill, Number(p.amount) || 0, p.currency_mint, p.chain || cur.chain);+ p._paused = false;+ renderActive();+ pulse(skill);+ } catch (err) {+ resumeBtn.disabled = false; resumeBtn.textContent = 'Resume';+ rowError(skill, err?.message || 'Could not resume');+ }+ return;+ }++ // Remove — inline confirm, then deactivate+ const removeBtn = e.target.closest('[data-remove-svc]');+ if (removeBtn) {+ const skill = removeBtn.dataset.removeSvc;+ const actions = rowEl(skill)?.querySelector('[data-actions]');+ if (!actions) return;+ actions.innerHTML = `<span class="irl-pr-confirm">Remove this service?</span>+ <button class="irl-link-btn" data-cancel-edit type="button">Keep</button>+ <button class="irl-link-btn danger" data-remove-yes="${esc(skill)}" type="button">Remove</button>`;+ return;+ }+ const removeYes = e.target.closest('[data-remove-yes]');+ if (removeYes) {+ const skill = removeYes.dataset.removeYes;+ const p = state.prices.find((x) => x.skill === skill);+ if (!p) return;+ removeYes.disabled = true; removeYes.textContent = 'Removing…';+ try {+ await writePrice(skill, 0, p.currency_mint, p.chain || 'solana');+ state.prices = state.prices.filter((x) => x.skill !== skill);+ renderActive(); renderAdd();+ } catch (err) {+ removeYes.disabled = false; removeYes.textContent = 'Remove';+ rowError(skill, err?.message || 'Could not remove');+ }+ }+ });++ load();+}+(async function boot() {const el = await mountShell();try {diff --git a/src/dashboard-next/pages/irl-reputation.js b/src/dashboard-next/pages/irl-reputation.jsnew file mode 100644index 000000000..98a11acc8--- /dev/null+++ b/src/dashboard-next/pages/irl-reputation.js@@ -0,0 +1,220 @@+// dashboard-next — IRL agent reputation panel (C3).+//+// A read-only, on-chain reputation surface attached to each placement card in+// irl-placements.js. The headline score + trust tier come from the agent-card+// the dashboard already fetched (the exact figures a passer-by sees on the B2+// tap card, so the owner sees what the public sees); the verified / credentialed+// / disputed breakdown is loaded lazily from /api/agents/solana-reputation the+// first time the owner opens the panel. Solana attestations are the canonical+// reputation source. Writing / disputing attestations lives on the passport —+// this panel only links out there.++import {+ skeletonHTML,+ emptyStateHTML,+ errorStateHTML,+ ensureStateKitStyles,+ attachRetry,+} from '../../shared/state-kit.js';++const STYLE_ID = 'irl-rep-styles';++function ensureStyles() {+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;+ const s = document.createElement('style');+ s.id = STYLE_ID;+ s.textContent = REP_CSS;+ (document.head || document.documentElement).appendChild(s);+}++// Score-band tiers (elite/trusted/emerging/new) — the same bands agent-card+// derives server-side, so the dashboard badge matches the public B2 tap card.+const TIERS = {+ elite: { label: 'Elite', color: '#fbbf24' },+ trusted: { label: 'Trusted', color: '#4ade80' },+ emerging: { label: 'Emerging', color: '#60a5fa' },+ new: { label: 'New', color: 'var(--nxt-ink-faint, #8a8f98)' },+};+const tierMeta = (tier) => TIERS[tier] || TIERS.new;++const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;++/**+ * Attach the reputation panel to a placement card. Idempotent per card.+ *+ * @param {HTMLElement} card The `.irl-card` element.+ * @param {object} opts+ * @param {object|null} opts.reputation `card.reputation` from /api/irl/agent-card —+ * `{ asset, available, score, tier, unique_attesters, ... }` or `{ asset:null, available:false }`.+ * @param {string} opts.agentId The placed agent's id, for the passport deep-link.+ * @param {string} [opts.pinId] The pin id, for the "View in IRL" deep-link.+ */+export function mountReputationPanel(card, { reputation, agentId, pinId } = {}) {+ if (!card || !agentId) return;+ if (card.querySelector('[data-reputation]')) return; // already mounted++ ensureStateKitStyles();+ ensureStyles();++ const asset = reputation?.asset || null;+ const network = reputation?.network || 'mainnet';+ const passport = `/agents/${encodeURIComponent(agentId)}`;+ const irlHref = pinId ? `/irl?highlight=${encodeURIComponent(pinId)}` : '/irl';++ // Collapsible section, inserted right after the stat chips.+ const section = document.createElement('div');+ section.className = 'irl-section irl-rep-section';+ section.setAttribute('data-reputation', '');+ section.hidden = true;+ section.id = `irl-rep-${pinId || agentId}`;+ section.innerHTML = `+ <div class="irl-section-label">Reputation+ <a href="${passport}" target="_blank" rel="noopener">Manage on passport →</a></div>+ <div class="irl-rep-body" data-rep-body></div>`;+ const stats = card.querySelector('.irl-stats');+ (stats || card).insertAdjacentElement(stats ? 'afterend' : 'beforeend', section);++ // The Reputation stat chip becomes the open/close affordance.+ const chip = card.querySelector('[data-stat="reputation"]');+ if (chip) {+ chip.classList.add('irl-stat--btn');+ chip.setAttribute('role', 'button');+ chip.setAttribute('tabindex', '0');+ chip.setAttribute('aria-expanded', 'false');+ chip.setAttribute('aria-controls', section.id);+ chip.title = 'View on-chain reputation';+ }++ const body = section.querySelector('[data-rep-body]');+ let loaded = false;++ function setOpen(open) {+ section.hidden = !open;+ chip?.setAttribute('aria-expanded', String(open));+ if (open && !loaded) { loaded = true; load(); }+ }++ async function load() {+ // No Solana asset → designed empty state, never an error.+ if (!asset) {+ body.innerHTML = emptyStateHTML({+ compact: true,+ icon: '',+ title: 'No on-chain identity yet',+ body: 'This agent has no Solana asset, so it can’t accrue attestations.',+ actions: [{ label: 'Open passport', href: passport, primary: true }],+ });+ return;+ }++ body.innerHTML = skeletonHTML(1, 'text');+ try {+ const r = await fetch(+ `/api/agents/solana-reputation?asset=${encodeURIComponent(asset)}&network=${encodeURIComponent(network)}`,+ );+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const data = await r.json();+ const fb = data.feedback || {};++ // Asset exists but no attestations yet → encourage sharing, not an error.+ if (!fb.total) {+ body.innerHTML = emptyStateHTML({+ compact: true,+ icon: '',+ title: 'No attestations yet',+ body: 'Share this agent so people can vouch for it — paid interactions and validations leave on-chain reputation here.',+ actions: [+ { label: 'Open passport', href: passport, primary: true },+ { label: 'View in IRL', href: irlHref },+ ],+ });+ return;+ }++ body.innerHTML = panelHtml(reputation, fb);+ } catch {+ body.innerHTML = errorStateHTML({+ title: 'Couldn’t load reputation',+ body: 'The on-chain reputation service didn’t respond. Check your connection and try again.',+ });+ attachRetry(body, () => { body.innerHTML = ''; load(); });+ }+ }++ chip?.addEventListener('click', () => setOpen(section.hidden));+ chip?.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); setOpen(section.hidden); }+ });+}++function panelHtml(rep, fb) {+ const score = Number.isFinite(rep?.score) ? rep.score : 0;+ const t = tierMeta(rep?.tier || 'new');+ const stars = Number(fb.score_avg_weighted || 0);+ const total = fb.total || 0;+ const uniq = fb.unique_attesters || 0;+ const verified = fb.verified || 0;+ const credentialed = fb.credentialed || 0;+ const disputed = fb.disputed || 0;++ return `+ <div class="irl-rep-panel">+ <div class="irl-rep-ring" style="--rep-pct:${score};--rep-color:${t.color}"+ role="img" aria-label="Reputation score ${score} out of 100">+ <span class="irl-rep-score">${score}</span><span class="irl-rep-of">/100</span>+ </div>+ <div class="irl-rep-main">+ <span class="irl-rep-tier" style="--rep-color:${t.color}">${t.label}</span>+ <div class="irl-rep-stars">${stars ? `★ ${stars.toFixed(1)}` : '☆ —'}+ <span class="irl-rep-sub">· ${plural(total, 'attestation')} · ${plural(uniq, 'attester')}</span></div>+ <div class="irl-rep-breakdown">+ <span class="irl-rep-chip ${verified ? 'ok' : ''}">${verified} verified</span>+ <span class="irl-rep-chip ${credentialed ? 'cred' : ''}">${credentialed} credentialed</span>+ <span class="irl-rep-chip ${disputed ? 'bad' : ''}">${disputed} disputed</span>+ </div>+ </div>+ </div>`;+}++const REP_CSS = `+.irl-rep-section .irl-rep-body { min-height: 24px; }+.irl-rep-panel { display: flex; align-items: center; gap: 14px; }+.irl-rep-ring {+ --sz: 58px;+ width: var(--sz); height: var(--sz); border-radius: 50%; flex-shrink: 0;+ display: flex; align-items: baseline; justify-content: center;+ background: conic-gradient(var(--rep-color) calc(var(--rep-pct) * 1%), var(--nxt-stroke, rgba(255,255,255,.1)) 0);+ position: relative;+}+.irl-rep-ring::before {+ content: ''; position: absolute; inset: 4px; border-radius: 50%;+ background: var(--nxt-panel, var(--nxt-bg-1, #0d1018));+}+.irl-rep-score { position: relative; font-size: 19px; font-weight: 800; color: var(--nxt-ink, #e8e8e8); font-variant-numeric: tabular-nums; line-height: 1; }+.irl-rep-of { position: relative; font-size: 10px; font-weight: 600; color: var(--nxt-ink-faint, #8a8f98); margin-left: 1px; }+.irl-rep-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; }+.irl-rep-tier {+ align-self: flex-start; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .04em;+ color: var(--rep-color); background: color-mix(in srgb, var(--rep-color) 14%, transparent);+ border: 1px solid color-mix(in srgb, var(--rep-color) 34%, transparent); padding: 2px 9px; border-radius: 999px;+}+.irl-rep-stars { font-size: 13px; font-weight: 700; color: #fbbf24; }+.irl-rep-sub { color: var(--nxt-ink-faint, #8a8f98); font-weight: 500; }+.irl-rep-breakdown { display: flex; flex-wrap: wrap; gap: 6px; }+.irl-rep-chip {+ font-size: 11px; padding: 2px 8px; border-radius: 999px; font-variant-numeric: tabular-nums;+ background: var(--nxt-bg-2, rgba(255,255,255,.05)); border: 1px solid var(--nxt-stroke, rgba(255,255,255,.1));+ color: var(--nxt-ink-dim, #aab1bb);+}+.irl-rep-chip.ok { color: var(--nxt-success, #4ade80); border-color: color-mix(in srgb, var(--nxt-success, #4ade80) 30%, transparent); }+.irl-rep-chip.cred { color: #a78bfa; border-color: color-mix(in srgb, #a78bfa 30%, transparent); }+.irl-rep-chip.bad { color: var(--nxt-danger, #f87171); border-color: color-mix(in srgb, var(--nxt-danger, #f87171) 30%, transparent); }+.irl-stat--btn { cursor: pointer; transition: border-color .12s, background .12s; }+.irl-stat--btn:hover { border-color: var(--nxt-stroke-strong, rgba(255,255,255,.25)); }+.irl-stat--btn:focus-visible { outline: 2px solid var(--nxt-accent, #4ea1ff); outline-offset: 2px; }+.irl-stat--btn .v { color: var(--nxt-accent, #4ea1ff); }+@media (prefers-reduced-motion: no-preference) {+ .irl-rep-section[data-reputation]:not([hidden]) .irl-rep-panel { animation: irl-rep-in .18s ease both; }+}+@keyframes irl-rep-in { from { opacity: 0; transform: translateY(-3px); } to { opacity: 1; transform: none; } }+`;diff --git a/src/irl.js b/src/irl.jsindex cebd6a6de..af47e434f 100644--- a/src/irl.js+++ b/src/irl.js@@ -21,6 +21,7 @@ import {PerspectiveCamera,PlaneGeometry,PMREMGenerator,+ Quaternion,Raycaster,Scene,ShadowMaterial,@@ -35,8 +36,10 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';+import { WebXRSession } from './ar/webxr.js';import { log } from './shared/log.js';import { createAvatarPicker } from './avatar-picker.js';+import { errorStateEl, skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';const AVATAR_URL_DEFAULT = '/avatars/default.glb';const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';@@ -58,7 +61,21 @@ const CAM_OFFSET = new Vector3(0, 1.85, 3.6);const CAM_LOOK_OFFSET = new Vector3(0, 1.1, 0);const SPAWN_DURATION = 0.38; // seconds for placed object scale-upconst TAP_THRESHOLD = 10; // px — beyond this it's a drag, not a tap-const NEARBY_FACE_LERP = 0.025; // speed at which nearby agents rotate to face camera+// ── Camera-aware agents ──────────────────────────────────────────────────+// Loaded nearby agents notice the viewer: they yaw their body toward the phone+// camera, lead with a head turn inside a natural neck cone, idle-drift when+// nobody's close, and perk up once when you first walk into range.+const AWARE_RADIUS_M = 12; // viewer must be this close (m) to engage tracking+const NOTICE_RADIUS_M = 4; // crossing this (m) fires the one-shot "notice"+const AWARE_MAX_AGENTS = 5; // only the nearest N get full per-frame head tracking+const HEAD_CLAMP = 0.7; // max neck yaw/pitch from rest (rad) — natural cone+const BODY_SLERP = 0.05; // eased body yaw toward the camera+const BODY_RETURN_SLERP = 0.03; // eased body yaw back to the placed heading+const HEAD_SLERP = 0.12; // eased head toward its gaze target+const HEAD_SLERP_NOTICE = 0.40; // boosted head slerp during a notice reaction+const NOTICE_BOOST_SEC = 0.40; // seconds the head-slerp boost lasts after a notice+const POP_DURATION = 0.45; // seconds for the perk-up scale pop+const POP_AMOUNT = 0.04; // peak +Y scale during the pop (1.0 → 1.04 → 1.0)// ── URL params ────────────────────────────────────────────────────────────const params = new URLSearchParams(location.search);@@ -93,14 +110,19 @@ const clearBtn = $('irl-clear-btn');const pickerEl = $('irl-picker');const avatarBtn = $('irl-avatar-btn');const lockBtn = $('irl-lock-btn');+const anchorBtn = $('irl-anchor-btn'); // WebXR "Place on floor" — revealed only when supported+const xrOverlay = $('irl-xr-overlay'); // WebXR dom-overlay root (in-session hint + exit + error)+const xrHintEl = $('irl-xr-hint');+const xrExitBtn = $('irl-xr-exit');// ── Status helpers ────────────────────────────────────────────────────────-function setStatus(msg, { error = false, loading = false, sticky = false } = {}) {+function setStatus(msg, { error = false, warn = false, loading = false, sticky = false } = {}) {clearTimeout(setStatus._t);if (!msg) { statusEl.classList.add('is-hidden'); return; }statusTxt.textContent = msg;statusEl.classList.remove('is-hidden');statusEl.classList.toggle('is-error', error);+ statusEl.classList.toggle('is-warn', warn && !error);spinner.classList.toggle('hidden', !loading);if (!sticky) setStatus._t = setTimeout(() => statusEl.classList.add('is-hidden'), 3000);}@@ -455,8 +477,11 @@ const raycaster = new Raycaster();const pointerNDC = new Vector2();let tapDownX = 0, tapDownY = 0;-canvas.addEventListener('pointerdown', e => { tapDownX = e.clientX; tapDownY = e.clientY; });+canvas.addEventListener('pointerdown', e => { tapDownX = e.clientX; tapDownY = e.clientY; armLongPress(e); });canvas.addEventListener('pointerup', e => {+ cancelLongPress();+ // While calibrating, taps belong to the nudge gesture — never re-open a sheet.+ if (calibrateActive) return;if (Math.hypot(e.clientX - tapDownX, e.clientY - tapDownY) > TAP_THRESHOLD) return;pointerNDC.set(@@ -480,24 +505,49 @@ canvas.addEventListener('pointerup', e => {clearBtn.hidden = false;_saveSession();} else {- // ── Tap on a nearby agent's 3D model ─────────────────────────────+ // ── Tap on a nearby agent: mesh body first, 2D label net as fallback ──+ // Mesh ray: the nearest intersection is closest to the camera, so two+ // agents projecting to the same pixel resolve to the FRONT body for free.+ let pin = null;const agentGroups = nearbyPins.map(p => p.group).filter(Boolean);if (agentGroups.length) {const hits = raycaster.intersectObjects(agentGroups, true);- if (hits.length) {- // Traverse up the scene graph to find which pin owns the hit mesh- const pin = _pinForObject(hits[0].object);- if (pin) { openPinSheet(pin); return; }- }+ if (hits.length) pin = _pinForObject(hits[0].object);}+ // Label net: a finger-sized slop around each on-screen name label catches+ // taps that miss the (often small or distant) body — the floor for tap+ // reliability on a phone. Front agent wins a cluster tie (see helper).+ if (!pin) pin = _nearestLabelWithinSlop(e.clientX, e.clientY);+ if (pin) openPinSheet(pin);}});+// Nearest on-screen name label within a finger-sized radius of the tap (B4).+// Uses the screen positions cached by updateLabels() each frame, so it costs a+// short loop and zero projection/allocation. A clear pixel winner takes it;+// near-ties resolve to the nearer (front) agent so clustered labels behave.+const TAP_SLOP = 28; // px — touch radius around a label centre, wider than the box+function _nearestLabelWithinSlop(px, py) {+ let best = null, bestPx = Infinity;+ for (const pin of nearbyPins) {+ if (!pin._labelOnScreen) continue;+ const d = Math.hypot(px - pin._labelSx, py - pin._labelSy);+ if (d > TAP_SLOP) continue;+ if (d < bestPx - 8) { best = pin; bestPx = d; }+ else if (Math.abs(d - bestPx) <= 8 &&+ (pin.distance_m ?? Infinity) < (best?.distance_m ?? Infinity)) {+ best = pin; bestPx = d;+ }+ }+ return best;+}+function _pinForObject(obj) {+ // Walk up to the agent group and read the pin cached on it (set in+ // spawnNearbyPin). O(depth) with no per-node array scan.let node = obj;while (node) {- const found = nearbyPins.find(p => p.group === node);- if (found) return found;+ if (node.userData && node.userData.pin) return node.userData.pin;node = node.parent;}return null;@@ -544,13 +594,16 @@ window.addEventListener('keyup', e => {{let dragging = false, lastX = 0, lastY = 0, downId = -1;canvas.addEventListener('pointerdown', e => {- if (placeModeActive) return;+ if (placeModeActive || calibrateActive) return;const r = joystickEl.getBoundingClientRect();if (e.clientX >= r.left && e.clientX <= r.right && e.clientY >= r.top && e.clientY <= r.bottom) return;dragging = true; downId = e.pointerId; lastX = e.clientX; lastY = e.clientY;canvas.setPointerCapture?.(e.pointerId);});const onMove = e => {+ // Calibration may engage mid-drag (long-press fires while still held) — yield+ // the pointer to the nudge gesture instead of orbiting the camera.+ if (calibrateActive) { dragging = false; return; }if (!dragging || e.pointerId !== downId) return;cameraYaw -= (e.clientX - lastX) * 0.005;cameraPitch = Math.max(PITCH_MIN, Math.min(PITCH_MAX, cameraPitch - (e.clientY - lastY) * 0.0035));@@ -709,17 +762,21 @@ window.addEventListener('deviceorientation', e => {let avatarLocked = false;async function setLocked(next) {- // iOS 13+ requires a user-gesture permission for DeviceOrientationEvent+ // iOS 13+ requires a user-gesture permission for DeviceOrientationEvent.+ // A declined prompt rejects (or returns 'denied') — either way the gyro+ // world-lock can't work, so surface the designed recovery state instead of+ // silently locking a glued, sensor-less avatar.if (next && typeof DeviceOrientationEvent?.requestPermission === 'function') {+ let perm = 'denied';try {- const perm = await DeviceOrientationEvent.requestPermission();- if (perm !== 'granted') {- setStatus('Motion sensor access denied', { error: true });- return;- }+ perm = await DeviceOrientationEvent.requestPermission();} catch (err) {log.error('[irl] orientation permission:', err);}+ if (perm !== 'granted') {+ showMotionPermissionHelp();+ return;+ }}avatarLocked = next;if (lockBtn) {@@ -738,25 +795,18 @@ async function setLocked(next) {arFrozenCamLook = null;document.body.classList.add('is-locked');- // GPS: anchor the avatar to real-world coordinates+ // GPS: anchor the avatar to real-world coordinates. If the first fix+ // isn't in yet, defer the precise pin to it (onGPSPosition) rather than+ // dropping the agent at a default origin — locking still works locally.if (gpsState.ready) {- const mLat = 110540;- const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));- const pinLat = gpsState.lat + (-avatarRig.position.z / mLat);- const pinLng = gpsState.lng + ( avatarRig.position.x / mLng);- gpsModeActive = true;- document.body.classList.add('gps-mode');- const headingDeg = ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;- // Snap the avatar to face the heading we're about to store so it- // matches how nearby users will see it — spawnNearbyPin() rotates- // foreign avatars with the same -(heading) → Y mapping. Keeping- // avatarYaw in sync means a later unlock+walk lerps from here too.- avatarYaw = -(headingDeg * Math.PI / 180);- avatarRig.quaternion.setFromAxisAngle(upY, avatarYaw);- openCaptionPanel(pinLat, pinLng, headingDeg);+ anchorGpsPin();+ } else {+ _pendingGpsLock = true;+ setStatus('Waiting for location to pin precisely…', { loading: true, sticky: true });}} else {devOrientBaseAlpha = null;+ _pendingGpsLock = false;arFrozenCamPos = camera.position.clone();arFrozenCamLook = camLookCurrent.clone();document.body.classList.remove('is-locked');@@ -770,10 +820,11 @@ async function setLocked(next) {gpsModeActive = false;}}- const gpsNote = gpsState.ready ? ' · others nearby can see you' : '';- setStatus(next- ? (arActive ? `Pinned in real space${gpsNote} — move phone to look around` : 'Agent pinned — drag to orbit')- : 'Agent unpinned');+ // In AR the lock path owns its own status — the deferred-GPS "Waiting…",+ // the no-compass warning, and the final "Pinned facing …" from commitPin —+ // so don't clobber it here. Only the non-AR orbit lock and unlock fall through.+ if (!arActive) setStatus(next ? 'Agent pinned — drag to orbit' : 'Agent unpinned');+ else if (!next) setStatus('Agent unpinned');_saveSession();}@@ -781,6 +832,53 @@ if (lockBtn) {lockBtn.addEventListener('click', () => setLocked(!avatarLocked));}+// ── Designed guidance sheet ───────────────────────────────────────────────+// iOS Safari has no WebXR, so the whole world-lock rides on motion + GPS+// permissions. When one is missing, a silent no-op leaves the user staring at+// a glued avatar with no idea why — so surface a recoverable state with the+// exact Settings path and a re-tap that re-requests the permission.+const errorSheet = document.getElementById('irl-error-sheet');+const errorTitleEl = document.getElementById('irl-error-title');+const errorBodyEl = document.getElementById('irl-error-body');+const errorActionEl = document.getElementById('irl-error-action');+const errorDismissEl = document.getElementById('irl-error-dismiss');+let _errorAction = null;++function showErrorState({ title, body, actionLabel, onAction }) {+ if (!errorSheet) { setStatus(title, { error: true, sticky: true }); return; }+ errorTitleEl.textContent = title;+ errorBodyEl.textContent = body;+ _errorAction = onAction || null;+ if (onAction) {+ errorActionEl.textContent = actionLabel || 'Try again';+ errorActionEl.hidden = false;+ } else {+ errorActionEl.hidden = true;+ }+ errorSheet.classList.add('is-open');+}++function hideErrorState() {+ if (errorSheet) errorSheet.classList.remove('is-open');+ _errorAction = null;+}++if (errorActionEl) errorActionEl.addEventListener('click', () => {+ const fn = _errorAction;+ hideErrorState();+ if (fn) fn();+});+if (errorDismissEl) errorDismissEl.addEventListener('click', hideErrorState);++function showMotionPermissionHelp() {+ showErrorState({+ title: 'Motion access needed to pin',+ body: 'Pinning your agent in real space uses your phone’s motion & orientation sensors. Turn them on in Settings › Safari › Motion & Orientation Access, then tap Try again.',+ actionLabel: 'Try again',+ onAction: () => setLocked(true),+ });+}+// ── GPS world-anchor system ───────────────────────────────────────────────//// When the user pins their agent we record the GPS latitude/longitude of that@@ -800,9 +898,12 @@ if (!_deviceToken) {localStorage.setItem('irl_device_token', _deviceToken);}-const gpsState = { lat: null, lng: null, ready: false, watchId: null };-let gpsPin = null; // { lat, lng, id? } — the user's own anchored pin+const gpsState = { lat: null, lng: null, ready: false, watchId: null, accuracy: null, altitude: null };+let gpsPin = null; // { lat, lng, id?, heightM } — the user's own anchored pinlet gpsModeActive = false;+// True when the user locked before the first GPS fix landed: onGPSPosition()+// finishes the anchor the instant a fix arrives, instead of pinning at origin.+let _pendingGpsLock = false;function gpsToWorld(agentLat, agentLng) {if (!gpsState.ready) return new Vector3(0, 0, 0);@@ -815,31 +916,107 @@ function gpsToWorld(agentLat, agentLng) {);}+// ── Cross-user anchor consistency (A3) ──────────────────────────────────────+// Foreign pins render from the placement's OWN stored absolute pose — compass+// yaw + floor height — not the viewer's incidental facing. Because both the+// placing device and every viewer reference absolute compass yaw and a shared+// geodetic (lat/lng) frame, the agent lands in the same bearing and floor spot+// for everyone. anchor_yaw_deg / anchor_height_m fall back to the legacy+// `heading` / ground plane when a pin predates the A2 pose columns.+function pinYawRad(pin) {+ const deg = Number.isFinite(pin.anchor_yaw_deg) ? pin.anchor_yaw_deg+ : (pin.heading != null ? pin.heading : 0);+ return -(deg * Math.PI / 180);+}+function pinHeightM(pin) {+ const h = pin.anchor_height_m;+ // Honour only a small, genuine floor offset — a deliberate calibrate height+ // nudge or a future depth-aware/VPS source. Larger magnitudes are eye-height /+ // session-origin conventions, not a cross-user floor delta, so the agent's feet+ // sit on the viewer's own ground plane (y=0) — the honest default until VPS lands.+ return (Number.isFinite(h) && Math.abs(h) <= 1) ? h : 0;+}++// Low-pass the viewer's GPS origin so anchored agents don't swim as GPS jitters+// frame-to-frame. We smooth the ORIGIN, never the pins. A fix worse than the+// reject threshold is dropped outright; a large jump (real walk or a big+// correction) snaps so the origin can't lag a block behind. Tighter fixes are+// trusted more (higher blend weight).+const ORIGIN_REJECT_M = 35; // ignore fixes noisier than this (m)+const ORIGIN_SNAP_M = 50; // beyond this delta, snap instead of blend (m)+function blendOrigin(prev, fix) {+ const acc = Number.isFinite(fix.accuracy) ? fix.accuracy : 20;+ if (acc > ORIGIN_REJECT_M) return prev;+ const jump = haversineMeters(prev.lat, prev.lng, fix.lat, fix.lng);+ if (jump > ORIGIN_SNAP_M) return { lat: fix.lat, lng: fix.lng };+ const k = Math.min(0.4, 12 / acc);+ return {+ lat: prev.lat + (fix.lat - prev.lat) * k,+ lng: prev.lng + (fix.lng - prev.lng) * k,+ };+}+let _lastNearbyFetch = 0;const NEARBY_RADIUS = 150; // metresconst NEARBY_INTERVAL = 15000; // msfunction onGPSPosition(pos) {const wasReady = gpsState.ready;- gpsState.lat = pos.coords.latitude;- gpsState.lng = pos.coords.longitude;- gpsState.ready = true;+ const rawLat = pos.coords.latitude;+ const rawLng = pos.coords.longitude;+ // Retain sensor metadata so a placement records how trustworthy the fix was+ // (A2 anchor pose). accuracy is metres of horizontal error; altitude is the+ // WGS-84 height above the ellipsoid (null where the device can't measure it).+ gpsState.accuracy = pos.coords.accuracy ?? null;+ gpsState.altitude = pos.coords.altitude ?? null;+ // Low-pass the viewer origin (A3) so anchored agents don't swim; the first fix+ // seeds the filter, later fixes are blended by blendOrigin().+ if (!wasReady) {+ gpsState.lat = rawLat;+ gpsState.lng = rawLng;+ } else {+ const blended = blendOrigin(+ { lat: gpsState.lat, lng: gpsState.lng },+ { lat: rawLat, lng: rawLng, accuracy: gpsState.accuracy },+ );+ gpsState.lat = blended.lat;+ gpsState.lng = blended.lng;+ }+ gpsState.ready = true;// First fix: GPS is live, so the user can place + manage pins from here.if (!wasReady) revealMyPinsBtn();- // Move pinned avatar to its GPS-anchored world position+ // A lock was requested before the first fix — finish anchoring now that we+ // have real coordinates, rather than dropping the agent at a default origin.+ if (_pendingGpsLock && avatarLocked && arActive) {+ _pendingGpsLock = false;+ anchorGpsPin();+ }++ // Move pinned avatar to its GPS-anchored world position. anchor_height_m (A2)+ // keeps the feet on the ground plane on slopes / indoors — 0 today, but read+ // it back so future floor-corrected placements render at the right height.if (gpsPin) {const wp = gpsToWorld(gpsPin.lat, gpsPin.lng);- avatarRig.position.set(wp.x, 0, wp.z);+ avatarRig.position.set(wp.x, gpsPin.heightM ?? 0, wp.z);}- // Update world positions of all nearby agents+ // Update world positions of all nearby agents. Because each agent's world+ // position is in metres relative to the user at the origin, its live+ // distance is simply hypot(x, z) — so recompute it every fix (the server's+ // distance_m goes stale the moment the user moves) and lazily upgrade the+ // glowing beacon to the real GLB the instant the user walks within range.for (const p of nearbyPins) {- if (p.group) {- const wp = gpsToWorld(p.lat, p.lng);- p.group.position.set(wp.x, 0, wp.z);- }+ if (!p.group) continue;+ // The agent being calibrated is driven by the nudge gesture this frame, not+ // by GPS — re-apply its working pose against the (possibly shifted) origin.+ if (calibrateActive && _cal && _cal.pin === p) { applyCalToGroup(); updatePinRing(p); continue; }+ const wp = gpsToWorld(p.lat, p.lng);+ p.group.position.set(wp.x, pinHeightM(p), wp.z);+ p.distance_m = Math.round(Math.hypot(wp.x, wp.z));+ updatePinRing(p);+ maybeLoadPinGLB(p);}const now = Date.now();@@ -849,11 +1026,56 @@ function onGPSPosition(pos) {}}+// Build the GPS world-anchor for the freshly locked own avatar and open the+// caption panel to persist its A2 pose. Requires a live GPS fix — setLocked()+// calls this directly when one is ready, or defers it here via _pendingGpsLock+// until onGPSPosition() lands the first fix.+function anchorGpsPin() {+ const mLat = 110540;+ const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));+ const pinLat = gpsState.lat + (-avatarRig.position.z / mLat);+ const pinLng = gpsState.lng + ( avatarRig.position.x / mLng);+ gpsModeActive = true;+ document.body.classList.add('gps-mode');+ const headingDeg = ((cameraYaw * 180 / Math.PI) % 360 + 360) % 360;+ // Snap the avatar to face the heading we're about to store so it matches how+ // nearby users will see it — spawnNearbyPin() rotates foreign avatars with the+ // same -(heading) → Y mapping. Keeping avatarYaw in sync means a later+ // unlock+walk lerps from here too.+ avatarYaw = -(headingDeg * Math.PI / 180);+ avatarRig.quaternion.setFromAxisAngle(upY, avatarYaw);+ // Dead-reckoning is only consistent across users when the heading is absolute+ // (compass-referenced). With only page-relative orientation the agent still+ // locks locally, but cross-user bearing (A3) degrades — record the distinction+ // in anchor_source (':rel') so A3 can down-weight it, and warn the user.+ const source = prefersAbsOrientation ? 'gyro-gps' : 'gyro-gps:rel';+ if (!prefersAbsOrientation) {+ setStatus('Compass heading unavailable — others may see this agent rotated', { warn: true });+ }+ openCaptionPanel(pinLat, pinLng, headingDeg, source);+}++function onGPSError(err) {+ // Only intervene when a placement is actively waiting on a fix — otherwise a+ // transient watchPosition timeout shouldn't disturb a working session.+ if (!_pendingGpsLock) return;+ _pendingGpsLock = false;+ const denied = err && err.code === err.PERMISSION_DENIED;+ showErrorState({+ title: denied ? 'Location access needed to pin' : 'Couldn’t get your location',+ body: denied+ ? 'Pinning your agent to a real spot needs your location. Enable it in Settings › Safari › Location, then tap Try again.'+ : 'We couldn’t read a GPS fix to pin precisely. Move somewhere with a clearer view of the sky, then tap Try again.',+ actionLabel: 'Try again',+ onAction: () => setLocked(true),+ });+}+function initGPS() {if (!navigator.geolocation) return;gpsState.watchId = navigator.geolocation.watchPosition(onGPSPosition,- () => {},+ onGPSError,{ enableHighAccuracy: true, maximumAge: 5000, timeout: 20000 },);}@@ -863,8 +1085,25 @@ function compassLabel(deg) {return dirs[Math.round(((deg % 360) + 360) % 360 / 45) % 8];}-async function savePin(lat, lng, heading = 0, caption = '') {+async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {try {+ // Anchor pose (A2): a reproducible record of where the agent stands —+ // floor height, orientation, and how trustworthy this GPS fix was — so a+ // later session or another user can reconstruct the placement. accuracy /+ // altitude always come from the live fix; heightM / yawDeg / quat / source+ // come from the placement mode (gyro-gps today, webxr later).+ const a = anchor || {};+ const anchorBody = {+ heightM: Number.isFinite(a.heightM) ? a.heightM : null,+ yawDeg: Number.isFinite(a.yawDeg) ? a.yawDeg : ((Math.round(heading) % 360) + 360) % 360,+ quat: Array.isArray(a.quat) ? a.quat : null,+ gpsAccuracyM: gpsState.accuracy,+ altitudeM: gpsState.altitude,+ // 'webxr' (A1) · 'gyro-gps' (absolute compass) · 'gyro-gps:rel'+ // (page-relative heading — A3 down-weights its cross-user bearing).+ source: a.source === 'webxr' ? 'webxr'+ : a.source === 'gyro-gps:rel' ? 'gyro-gps:rel' : 'gyro-gps',+ };const r = await fetch('/api/irl/pins', {method: 'POST',credentials: 'include',@@ -877,6 +1116,7 @@ async function savePin(lat, lng, heading = 0, caption = '') {avatarName: nameEl.textContent,deviceToken: _deviceToken,agentId: _currentAgentId || null,+ anchor: anchorBody,}),});if (!r.ok) return null;@@ -892,9 +1132,9 @@ const captionInput = document.getElementById('irl-caption-input');const captionConfirm = document.getElementById('irl-caption-confirm');const captionCancel = document.getElementById('irl-caption-cancel');-function openCaptionPanel(pinLat, pinLng, headingDeg) {+function openCaptionPanel(pinLat, pinLng, headingDeg, source = 'gyro-gps') {if (!captionPanel) {- commitPin(pinLat, pinLng, headingDeg, '');+ commitPin(pinLat, pinLng, headingDeg, '', source);return;}captionInput.value = '';@@ -902,7 +1142,7 @@ function openCaptionPanel(pinLat, pinLng, headingDeg) {setTimeout(() => captionInput.focus(), 300);captionConfirm.onclick = () => {captionPanel.classList.remove('is-open');- commitPin(pinLat, pinLng, headingDeg, captionInput.value.trim());+ commitPin(pinLat, pinLng, headingDeg, captionInput.value.trim(), source);};captionCancel.onclick = () => {captionPanel.classList.remove('is-open');@@ -910,11 +1150,19 @@ function openCaptionPanel(pinLat, pinLng, headingDeg) {};}-function commitPin(pinLat, pinLng, headingDeg, caption) {- gpsPin = { lat: pinLat, lng: pinLng };- savePin(pinLat, pinLng, headingDeg, caption).then(result => {+function commitPin(pinLat, pinLng, headingDeg, caption, source = 'gyro-gps') {+ gpsPin = { lat: pinLat, lng: pinLng, heightM: 0 };+ // Gyro-GPS placement pose (A2/A3): the agent stands on the floor. anchor_height_m+ // is a floor-relative offset, and gyro placement has no measured floor depth, so+ // it's 0 — every viewer renders the feet on their own ground plane (pinHeightM).+ // yawDeg is the absolute compass heading; source carries the absolute-vs-relative+ // distinction ('gyro-gps' | 'gyro-gps:rel') for A3. accuracy / altitude are filled+ // from the live GPS fix inside savePin().+ const anchor = { heightM: 0, yawDeg: headingDeg, source };+ savePin(pinLat, pinLng, headingDeg, caption, anchor).then(result => {if (result && gpsPin) {gpsPin.id = result.id;+ _myPinIds.add(result.id);const dir = compassLabel(headingDeg);setStatus(result.permanent? `Pinned facing ${dir} — permanently visible to nearby users`@@ -924,6 +1172,186 @@ function commitPin(pinLat, pinLng, headingDeg, caption) {});}+// ── WebXR floor anchor (A1) ────────────────────────────────────────────────+//+// On WebXR-capable devices (primarily Android Chrome) the user taps a real+// floor point through a hit-test reticle; the agent binds to a real XRAnchor+// so it stays glued to that world point as the phone moves — no GPS jitter, no+// camera-relative slide. The anchored local pose is converted to a GPS pin and+// persisted through savePin() (A2) so it reloads near the same spot and nearby+// users can see it. iOS Safari (no immersive-ar) never reaches here and stays+// on the gyro+GPS Pin path (A4).++// Viewer shim — the minimal interface WebXRSession drives (see src/xr.js for the+// canonical shape). `content` is the positioned avatar group the anchor glues to.+const xrViewer = {+ renderer,+ scene,+ content: avatarRig,+ controls: { enabled: true }, // stub: IRL drives its own camera, not OrbitControls+ mixer: null, // animMgr.update() already advances the mixer — avoid double-stepping+ animationManager: animMgr,+ _afterAnimateHooks: [],+ _rafId: null,+ prevTime: null,+ activeCamera: camera,+ _needsRender: true,+ _updateRenderLoop() { startTick(); },+};++// Single owner of the IRL render loop's RAF handle so WebXRSession can pause it+// (cancelAnimationFrame on xrViewer._rafId) while the XR animation loop runs,+// then resume it on exit via _updateRenderLoop().+function startTick() {+ if (xrViewer._rafId !== null) return;+ xrViewer._rafId = requestAnimationFrame(tick);+}++let xrSession = null;++async function detectFloorAnchorSupport() {+ try {+ if (!(await WebXRSession.isSupported())) return; // iOS Safari / desktop → Pin path only+ if (anchorBtn) anchorBtn.hidden = false;+ } catch {+ // No navigator.xr or a thrown support check → leave the entry hidden; the+ // Pin button (A4 gyro+GPS) remains the anchor path. No console noise.+ }+}++function setXrHint(text) {+ if (xrHintEl) {+ xrHintEl.textContent = text;+ xrHintEl.hidden = false;+ }+}++function clearXrError() {+ const mount = $('irl-xr-error');+ if (mount) { mount.replaceChildren(); mount.hidden = true; }+}++function showXrError(err) {+ const denied = err?.name === 'NotAllowedError' || err?.name === 'SecurityError';+ const body = denied+ ? 'Camera and motion access are needed to place your agent on the floor. Allow them in your browser, then retry — or use Pin here for compass + GPS placement.'+ : 'Your device couldn’t hold an AR session. Retry, or use Pin here to place with compass + GPS instead.';+ const mount = $('irl-xr-error');+ if (xrOverlay && mount) {+ if (xrHintEl) xrHintEl.hidden = true;+ mount.replaceChildren(errorStateEl({+ title: 'Floor anchoring couldn’t start',+ body,+ actions: [+ { label: 'Retry', id: 'xr-retry', primary: true },+ { label: 'Use Pin instead', id: 'xr-pin' },+ ],+ }));+ mount.hidden = false;+ xrOverlay.hidden = false;+ } else {+ setStatus('Floor anchoring couldn’t start — use Pin here instead', { error: true, sticky: true });+ }+}++async function enterFloorAnchor() {+ if (xrSession) { await xrSession.end(); return; }+ // immersive-ar owns the rear camera and the full screen; release the+ // getUserMedia passthrough first so the two don't contend for the camera.+ if (arActive) disableAR();++ clearXrError();+ if (anchorBtn) anchorBtn.classList.add('is-active');+ if (xrOverlay) xrOverlay.hidden = false;+ setXrHint('Point at the floor and move your phone slowly');++ try {+ xrSession = new WebXRSession(xrViewer, {+ domOverlayRoot: xrOverlay,+ onHit: (has) => setXrHint(has+ ? 'Tap to place your agent on the floor'+ : 'Point at the floor and move your phone slowly'),+ onAnchored: (pose) => onFloorAnchored(pose),+ onEnd: () => {+ xrSession = null;+ // WebXRSession restores an opaque clear color on exit; IRL renders+ // over the page gradient with a transparent canvas — put that back.+ renderer.setClearColor(0x000000, 0);+ if (!arActive) scene.background = null;+ if (anchorBtn) anchorBtn.classList.remove('is-active');+ if (xrOverlay) xrOverlay.hidden = true;+ },+ });+ await xrSession.start();+ setStatus('Floor anchoring on — point at the floor, then tap to place');+ } catch (err) {+ log.error('[irl] WebXR start failed:', err);+ xrSession = null;+ if (anchorBtn) anchorBtn.classList.remove('is-active');+ showXrError(err);+ }+}++// Yaw (rotation about world Y), in degrees clockwise from the local −Z axis —+// the same convention savePin stores and spawnNearbyPin reads back.+function yawFromQuat(q) {+ const siny = 2 * (q.w * q.y + q.z * q.x);+ const cosy = 1 - 2 * (q.y * q.y + q.x * q.x);+ return Math.atan2(siny, cosy) * 180 / Math.PI;+}++// Convert the anchored local-space pose to a GPS pin and persist it (A2). The+// in-session XRAnchor already holds the agent; this is the durable, shareable+// record. Horizontal offset → lat/lng uses the same metre-per-degree math as the+// gyro Pin path (local −Z = north, +X = east); height + yaw + GPS-fit trust ride+// along in the anchor object.+function onFloorAnchored(pose) {+ const { position, quaternion } = pose;+ if (!gpsState.ready) {+ // The anchor still glues the agent in-session; we just can't save a pin yet.+ setXrHint('Anchored here — enable location to save & share this spot');+ return;+ }+ const mLat = 110540;+ const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));+ const pinLat = gpsState.lat + (-position.z / mLat);+ const pinLng = gpsState.lng + ( position.x / mLng);+ const heading = ((Math.round(yawFromQuat(quaternion)) % 360) + 360) % 360;++ gpsPin = { lat: pinLat, lng: pinLng };+ gpsModeActive = true;+ setXrHint('Anchored — walk around, it stays put');+ savePin(pinLat, pinLng, heading, '', {+ heightM: position.y, // floor height relative to the eye-level session origin (negative = below)+ yawDeg: heading,+ quat: [quaternion.x, quaternion.y, quaternion.z, quaternion.w],+ source: 'webxr',+ }).then(result => {+ if (result && gpsPin) {+ gpsPin.id = result.id;+ revealMyPinsBtn();+ setXrHint(result.permanent+ ? 'Anchored & saved — permanently visible to nearby users'+ : 'Anchored & saved — nearby users can see you for 7 days');+ } else {+ setXrHint('Anchored here — couldn’t save the pin, retry on exit');+ }+ });+}++if (anchorBtn) anchorBtn.addEventListener('click', enterFloorAnchor);+if (xrExitBtn) xrExitBtn.addEventListener('click', () => { xrSession?.end(); });+// Taps on the overlay chrome (hint, exit, error actions) must not also fire the+// XR 'select' that places an anchor.+if (xrOverlay) {+ xrOverlay.addEventListener('beforexrselect', (e) => e.preventDefault());+ xrOverlay.addEventListener('click', (e) => {+ const action = e.target.closest('[data-sk-action]')?.dataset.skAction;+ if (action === 'xr-retry') { clearXrError(); enterFloorAnchor(); }+ else if (action === 'xr-pin') { clearXrError(); xrOverlay.hidden = true; setLocked(true); }+ });+}+// ── Nearby agents ─────────────────────────────────────────────────────────let nearbyPins = []; // [{ id, lat, lng, avatar_url, avatar_name, caption, x402_endpoint, distance_m, group, labelEl, glbLoaded }]@@ -939,10 +1367,12 @@ async function loadNearbyPins() {const incoming = pins.filter(p => !gpsPin?.id || p.id !== gpsPin.id);const inIds = new Set(incoming.map(p => p.id));- // Remove disappeared pins+ // Remove disappeared pins — dispose their GPU resources, don't just+ // detach. At a busy location agents come and go constantly; without+ // freeing geometries/materials/textures a long session leaks steadily.nearbyPins = nearbyPins.filter(p => {if (inIds.has(p.id)) return true;- if (p.group) scene.remove(p.group);+ if (p.group) { scene.remove(p.group); disposeObject3D(p.group); }if (p.labelEl) p.labelEl.remove();return false;});@@ -976,12 +1406,62 @@ async function loadNearbyPins() {} catch {}}+// ── Confidence ring (A3) ────────────────────────────────────────────────────+// A flat ground ring under each agent whose radius communicates the REAL GPS+// uncertainty (max of the viewer's live accuracy and the pin's stored+// gps_accuracy_m). Honest by design: consumer GPS is ~5–15 m open-sky and far+// worse in urban canyons / indoors, so we never imply a centimetre-perfect+// pinpoint. Amber when the lock is loose (> RING_LOW_ACC_M).+const RING_LOW_ACC_M = 25; // above this, the ring goes amber + copy warns+const RING_MIN_M = 1.4; // floor radius so a tight fix is still visible+const RING_MAX_M = 10; // cap render radius so a loose fix doesn't swallow the scene+const RING_OK_COLOR = 0x4cc9ff;+const RING_LOW_COLOR = 0xffb020;++// (Re)create the ring mesh on a pin's group. Called on spawn and again after a+// GLB swap (which disposes all group children, ring included).+function attachPinRing(pin) {+ if (!pin.group) return;+ if (pin.ringMesh) { pin.group.remove(pin.ringMesh); disposeObject3D(pin.ringMesh); pin.ringMesh = null; }+ // Unit-radius torus laid flat on the ground; scaled by updatePinRing().+ const ring = new Mesh(+ new TorusGeometry(1, 0.045, 8, 64),+ new MeshStandardMaterial({+ color: RING_OK_COLOR, emissive: RING_OK_COLOR, emissiveIntensity: 0.9,+ roughness: 0.4, metalness: 0, transparent: true, opacity: 0.55, depthWrite: false,+ }),+ );+ ring.rotation.x = Math.PI / 2;+ ring.position.y = 0.02;+ ring.renderOrder = 2;+ pin.group.add(ring);+ pin.ringMesh = ring;+}++// Size + colour the ring from the worse of viewer / pin accuracy. Cheap; called+// every GPS fix (viewer accuracy changes) and once on spawn.+function updatePinRing(pin) {+ const ring = pin.ringMesh;+ if (!ring) return;+ const viewerAcc = Number.isFinite(gpsState.accuracy) ? gpsState.accuracy : 12;+ const pinAcc = Number.isFinite(pin.gps_accuracy_m) ? pin.gps_accuracy_m : viewerAcc;+ const acc = Math.max(viewerAcc, pinAcc);+ const radius = Math.min(RING_MAX_M, Math.max(RING_MIN_M, acc));+ ring.scale.set(radius, radius, 1);+ const low = acc > RING_LOW_ACC_M;+ const m = ring.material;+ m.color.setHex(low ? RING_LOW_COLOR : RING_OK_COLOR);+ m.emissive.setHex(low ? RING_LOW_COLOR : RING_OK_COLOR);+ m.opacity = low ? 0.62 : 0.5;+}+function spawnNearbyPin(pin) {const g = new Group();const wp = gpsToWorld(pin.lat, pin.lng);- g.position.set(wp.x, 0, wp.z);- // Three.js Y rotation is CCW; compass heading is CW from north — negate- if (pin.heading != null) g.rotation.y = -(pin.heading * Math.PI / 180);+ // Absolute stored pose (A3): floor height + compass yaw, so two devices at the+ // same place see the agent in the same spot and bearing (see pinYawRad/pinHeightM).+ g.position.set(wp.x, pinHeightM(pin), wp.z);+ g.rotation.y = pinYawRad(pin);// Glowing beacon placeholder (replaced by real GLB when close)const beacon = new Mesh(@@ -995,13 +1475,23 @@ function spawnNearbyPin(pin) {beacon.castShadow = true;g.add(beacon);pin.group = g;+ // Cache the owning pin on the group so a mesh raycast (_pinForObject) maps a+ // hit back to its agent without scanning nearbyPins per node.+ g.userData.pin = pin;scene.add(g);+ // Confidence ring (A3) — a ground footprint sized to the real GPS uncertainty+ // so users see the true precision instead of being misled into thinking it's+ // centimetre-perfect. Amber when the lock is loose. Built before the label so+ // the agent reads as "somewhere in here", not a false pinpoint.+ attachPinRing(pin);+ updatePinRing(pin);+// Floating HTML name label — gold border if this is the owner's own pinconst el = document.createElement('div');el.className = 'irl-agent-label';- // Mark own pin (matched by device_token on anonymous OR user_id on authenticated)- if (pin.device_token === _deviceToken || (gpsPin?.id && pin.id === gpsPin.id)) {+ // Own pin = one this device placed (matched by id via /mine) or the live anchor.+ if (isOwnPin(pin)) {el.classList.add('is-own');}el.style.display = 'none';@@ -1010,9 +1500,9 @@ function spawnNearbyPin(pin) {document.body.appendChild(el);pin.labelEl = el;- // Load real GLB if nearby- const loadedCount = nearbyPins.filter(p => p.glbLoaded).length;- if (pin.distance_m < 80 && loadedCount < 5 && pin.avatar_url) loadPinGLB(pin);+ // Load the real GLB if the user is already close; otherwise it upgrades from+ // the beacon automatically as they approach (see maybeLoadPinGLB on GPS fix).+ maybeLoadPinGLB(pin);}function _escHtml(s) {@@ -1020,20 +1510,87 @@ function _escHtml(s) {({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));}+// Recursively free a detached Object3D's GPU resources (geometry, materials,+// and any texture maps on them) so removing a nearby agent doesn't leak.+function disposeObject3D(root) {+ root.traverse(n => {+ if (n.geometry) n.geometry.dispose();+ const mats = Array.isArray(n.material) ? n.material : n.material ? [n.material] : [];+ for (const m of mats) {+ for (const k in m) {+ const v = m[k];+ if (v && v.isTexture) v.dispose();+ }+ m.dispose();+ }+ });+}++// At most this many remote agents render their full GLB at once; the rest stay+// lightweight glowing beacons until the user gets close. Keeps a crowded+// location from loading a dozen rigged models simultaneously.+const MAX_LOADED_GLB = 5;++// Load a pin's real avatar GLB once the user is within range — idempotent, so+// it's safe to call every GPS fix. This is what turns the beacon into the agent+// as you walk up to it.+function maybeLoadPinGLB(pin) {+ if (pin.glbLoaded || pin._glbLoading || !pin.avatar_url) return;+ if (pin.distance_m >= 80) return;+ const loadedCount = nearbyPins.filter(p => p.glbLoaded || p._glbLoading).length;+ if (loadedCount >= MAX_LOADED_GLB) return;+ loadPinGLB(pin);+}+async function loadPinGLB(pin) {+ pin._glbLoading = true;try {const gltf = await new GLTFLoader().loadAsync(pin.avatar_url);- if (!pin.group) return;+ // The pin may have been removed (walked out of range) while the GLB+ // was in flight — free the just-loaded model rather than orphaning it.+ if (!pin.group) { disposeObject3D(gltf.scene); return; }const model = gltf.scene;model.traverse(n => { if (n.isMesh) n.castShadow = true; });const box = new Box3().setFromObject(model);model.position.y -= box.min.y;- while (pin.group.children.length) pin.group.remove(pin.group.children[0]);+ // Dispose the placeholder beacon before swapping in the real model.+ while (pin.group.children.length) {+ const child = pin.group.children[0];+ pin.group.remove(child);+ disposeObject3D(child);+ }pin.group.add(model);pin.glbLoaded = true;- // Re-apply heading — GLTFLoader can reset the group transform- if (pin.heading != null) pin.group.rotation.y = -(pin.heading * Math.PI / 180);- } catch {}+ // Re-apply the stored absolute pose — the GLTF swap (and the dispose loop+ // above, which also removed the confidence ring) reset the group transform.+ pin.group.rotation.y = pinYawRad(pin);+ pin.group.position.y = pinHeightM(pin);+ attachPinRing(pin);+ updatePinRing(pin);++ // Cache the head/torso bone + rest pose once so the per-frame awareness+ // step never walks the tree. baseYaw is the placed heading we ease back to+ // when the viewer leaves; the gaze bone (head preferred, torso fallback)+ // drives the "looks at you" turn. Agents with neither just turn whole-body.+ pin.baseYaw = pin.group.rotation.y;+ pin.headBone = null; pin.spineBone = null;+ 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 ? pin.headBone.quaternion.clone() : null;+ pin.restSpineQuat = pin.spineBone ? pin.spineBone.quaternion.clone() : null;+ pin.idleT = 0; // idle-drift phase clock+ pin.noticed = false; // has the viewer already crossed the notice radius?+ pin.noticeT = 0; // remaining head-slerp boost time after a notice+ pin.popT = -1; // perk-up pop clock (-1 = inactive)+ } catch {+ // Allow a later GPS fix to retry the load (transient network/CDN blip).+ } finally {+ pin._glbLoading = false;+ }}function updateNearbyBadge() {@@ -1092,12 +1649,26 @@ async function loadMyPins() {credentials: 'include',});if (!r.ok) return [];- return (await r.json()).pins ?? [];+ const pins = (await r.json()).pins ?? [];+ // Track which nearby pins this device owns so the calibrate affordance (and+ // the gold "your agent" label) light up. The server re-checks ownership on+ // PATCH, so this is purely a client-side gate.+ for (const p of pins) _myPinIds.add(p.id);+ refreshOwnLabels();+ return pins;} catch {return [];}}+// Re-mark already-spawned nearby labels as own once /mine resolves (the pins may+// have spawned before we knew which were ours).+function refreshOwnLabels() {+ for (const p of nearbyPins) {+ if (p.labelEl) p.labelEl.classList.toggle('is-own', isOwnPin(p));+ }+}+function renderMyPins(pins) {const list = document.getElementById('irl-mypins-list');if (!list) return;@@ -1164,6 +1735,241 @@ document.getElementById('irl-mypins-list')?.addEventListener('click', (e) => {if (btn) deleteMyPin(btn.dataset.del, btn);});+// ── Inspect card (v2) helpers ──────────────────────────────────────────────+// Tapping a nearby agent opens a rich card: avatar + name + tier badge, a bio+// line, an on-chain reputation strip, and the paid x402 services the agent+// offers — all from one /api/irl/agent-card aggregation call. Every state+// (skeleton, populated, empty services, no-reputation, error+retry) renders+// through the shared state-kit.++let _cardAbort = null; // aborts the in-flight agent-card fetch when switching agents+let _activePin = null; // the pin whose card is shown (drives retry)+let _lastFocus = null; // element focused before open (restored on close)++// Title-case a tier enum ('trusted' → 'Trusted').+function _tierLabel(tier) {+ return tier ? tier.charAt(0).toUpperCase() + tier.slice(1) : '';+}++// Reputation strip / chip. A real number only when the on-chain asset actually+// has attestations; otherwise an honest "new / unreviewed" chip — never a+// fabricated score.+function _repStripHTML(rep) {+ const hasRep = rep && rep.available && rep.attestation_count > 0;+ if (!hasRep) {+ const label = rep && rep.available+ ? 'On-chain · no reviews yet'+ : 'New here · no on-chain reputation yet';+ return `<div class="irl-rep-chip">✦ ${label}</div>`;+ }+ const n = rep.attestation_count;+ const parts = [+ `<span class="irl-rep-star">★</span> <b>${rep.score}</b>/100`,+ `${n} attestation${n === 1 ? '' : 's'}`,+ _tierLabel(rep.tier),+ ];+ if (rep.tasks_accepted > 0) {+ parts.push(`${rep.tasks_accepted} task${rep.tasks_accepted === 1 ? '' : 's'} done`);+ }+ return `<div class="irl-rep-strip">${parts.join('<span class="irl-rep-sep">·</span>')}</div>`;+}++// Header tier badge — only when reputation is real (an asset with attestations).+function _setTierBadge(rep) {+ const badge = document.getElementById('irl-sheet-tier');+ if (!badge) return;+ if (rep && rep.available && rep.attestation_count > 0 && rep.tier) {+ badge.textContent = `★ ${rep.score} · ${_tierLabel(rep.tier)}`;+ badge.dataset.tier = rep.tier;+ badge.hidden = false;+ } else {+ badge.hidden = true;+ badge.removeAttribute('data-tier');+ }+}++// Services menu, or a designed empty state when the agent sells nothing.+function _servicesHTML(services) {+ if (!services || !services.length) {+ return emptyStateHTML({+ icon: '',+ title: 'No paid services yet',+ body: 'This agent is here to meet, not to sell.',+ compact: true,+ });+ }+ const rows = services.map((s) => {+ const price = s.price_usd != null+ ? `$${Number(s.price_usd).toFixed(2)} ${s.currency || 'USDC'}`+ : 'Free';+ const ep = s.x402_endpoint || '';+ const useBtn = ep+ ? `<button type="button" class="irl-service-use" data-x402="${_escHtml(ep)}">Use</button>`+ : '';+ return `<div class="irl-service-row">+ <div class="irl-service-info">+ <span class="irl-service-name">${_escHtml(s.name || s.skill)}</span>+ ${s.description ? `<span class="irl-service-desc">${_escHtml(s.description)}</span>` : ''}+ </div>+ <span class="irl-service-price">${_escHtml(price)}</span>+ ${useBtn}+ </div>`;+ }).join('');+ return `<div class="irl-sheet-services">+ <div class="irl-services-label">Services</div>+ <div class="irl-services-list">${rows}</div>+ </div>`;+}++// Loading skeleton for the card body (a bio line + a few service rows).+function _cardSkeletonHTML() {+ ensureStateKitStyles();+ return `${skeletonHTML(1, 'text')}${skeletonHTML(3, 'row')}`;+}++// Render the resolved card into the open sheet.+function _applyCard(card, pin) {+ const agent = card.agent || {};+ const sheet = document.getElementById('irl-sheet');++ const thumb = document.getElementById('irl-sheet-thumb');+ if (thumb) {+ if (agent.thumbnail_url) { thumb.src = agent.thumbnail_url; thumb.hidden = false; }+ else { thumb.removeAttribute('src'); thumb.hidden = true; }+ }++ // The card may carry a richer name than the pin's avatar label.+ if (agent.name) {+ const nameEl = document.getElementById('irl-sheet-name');+ if (nameEl) nameEl.textContent = agent.name;+ if (sheet) sheet.dataset.agentName = agent.name;+ }+ if (sheet && agent.profile_url) sheet.dataset.profileUrl = agent.profile_url;++ _setTierBadge(card.reputation);++ const body = document.getElementById('irl-card-body');+ if (body) {+ const parts = [];+ const bio = agent.bio;+ // Skip the bio when it just repeats the pin caption shown above.+ if (bio && bio !== pin.caption) parts.push(`<p class="irl-card-bio">${_escHtml(bio)}</p>`);+ parts.push(_repStripHTML(card.reputation));+ parts.push(_servicesHTML(card.services));+ body.innerHTML = parts.join('');+ }++ // Prefer the card's resolved x402 endpoint for the footer Pay button.+ if (card.x402_endpoint) {+ const payBtn = document.getElementById('irl-sheet-pay');+ if (payBtn) { payBtn.hidden = false; payBtn.dataset.endpoint = card.x402_endpoint; }+ }+}++// Fetch + render the agent card. Aborts any in-flight request so switching+// agents never lands stale data. Re-callable for retry.+async function loadAgentCard(pin) {+ _cardAbort?.abort();+ const ctrl = new AbortController();+ _cardAbort = ctrl;++ const body = document.getElementById('irl-card-body');+ if (body) body.innerHTML = _cardSkeletonHTML();++ // Real agents resolve by agent_id; anonymous pins fall back to the pin id.+ const url = pin.agent_id+ ? `/api/irl/agent-card?agent_id=${encodeURIComponent(pin.agent_id)}`+ : `/api/irl/agent-card?pin=${encodeURIComponent(pin.id)}`;++ try {+ const r = await fetch(url, { signal: ctrl.signal });+ if (ctrl.signal.aborted) return;+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+ const { card } = await r.json();+ if (ctrl.signal.aborted) return;+ if (!card) throw new Error('empty card');+ _applyCard(card, pin);+ } catch (err) {+ if (ctrl.signal.aborted || err?.name === 'AbortError') return;+ if (body) {+ body.innerHTML = errorStateHTML({+ title: "Couldn't load this agent",+ body: 'Check your connection and try again.',+ });+ }+ }+}++function closeInspectSheet() {+ _cardAbort?.abort();+ document.getElementById('irl-sheet')?.classList.remove('is-open');+ document.getElementById('irl-sheet-backdrop')?.classList.remove('is-open');+ _activePin = null;+ if (_lastFocus && document.contains(_lastFocus)) {+ try { _lastFocus.focus({ preventScroll: true }); } catch { /* element gone */ }+ }+ _lastFocus = null;+}++// Run an x402 payment against a service endpoint, driving button state through+// the flow. Shared by the footer Pay button and per-service "Use" buttons.+async function runX402Payment(endpoint, btn) {+ if (!endpoint || !btn) return;++ if (!window.ethereum) {+ setStatus('Connect an Ethereum wallet (MetaMask) to pay via x402', { error: true });+ return;+ }++ btn.disabled = true;+ const origText = btn.textContent;++ // Gate on an authorized wallet before signing so we can bail cleanly if the+ // user declines, rather than letting the x402 adapter prompt mid-flow.+ btn.textContent = 'Connecting…';+ try {+ const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });+ if (!Array.isArray(accounts) || !accounts.length) {+ setStatus('Connect your wallet to pay via x402', { error: true });+ btn.disabled = false;+ btn.textContent = origText;+ return;+ }+ } catch (err) {+ const m = err?.message ?? String(err);+ setStatus(/reject|denied|4001/i.test(m) ? 'Wallet connection cancelled' : `Couldn't connect wallet — ${m}`, { error: true });+ btn.disabled = false;+ btn.textContent = origText;+ return;+ }++ btn.textContent = 'Sending…';+ try {+ const { withX402 } = await import('../packages/x402-fetch/dist/index.esm.js');+ const pay = withX402(window.ethereum, { maxPaymentUsd: 1.00 });+ const r = await pay(endpoint, { method: 'POST' });+ if (r.ok) {+ setStatus('Payment sent');+ btn.textContent = 'Paid ✓';+ btn.disabled = true;+ } else {+ const msg = await r.text().catch(() => r.status);+ setStatus(`Payment failed (${msg})`, { error: true });+ btn.disabled = false;+ btn.textContent = origText;+ }+ } catch (err) {+ const msg = err?.message ?? String(err);+ if (msg.includes('rejected') || msg.includes('denied')) {+ setStatus('Payment cancelled', { error: true });+ } else {+ setStatus(`Payment failed — ${msg}`, { error: true });+ }+ btn.disabled = false;+ btn.textContent = origText;+ }+}+// ── Interaction sheet ─────────────────────────────────────────────────────async function openPinSheet(pin) {const sheet = document.getElementById('irl-sheet');@@ -1183,6 +1989,33 @@ async function openPinSheet(pin) {payBtn.dataset.endpoint = pin.x402_endpoint ?? '';}+ // Calibrate (A3) — only the owner of this pin can fine-tune its real-world+ // spot. The server re-checks ownership; this is the discoverable entry point+ // alongside the long-press gesture.+ const calBtn = document.getElementById('irl-sheet-calibrate');+ if (calBtn) {+ const own = isOwnPin(pin);+ calBtn.hidden = !own;+ calBtn.onclick = own+ ? () => { sheet.classList.remove('is-open'); enterCalibrate(pin); }+ : null;+ }++ // Honest accuracy line (A3) — never imply the placement is centimetre-perfect.+ const accEl = document.getElementById('irl-sheet-accuracy');+ if (accEl) {+ const acc = Number.isFinite(pin.gps_accuracy_m) ? Math.round(pin.gps_accuracy_m) : null;+ if (acc != null) {+ accEl.textContent = acc > RING_LOW_ACC_M+ ? `Placed with ~${acc} m GPS accuracy — position can vary between phones. Find a spot with clearer sky for a tighter lock.`+ : `Placed with ~${acc} m GPS accuracy.`;+ accEl.classList.toggle('is-low', acc > RING_LOW_ACC_M);+ accEl.hidden = false;+ } else {+ accEl.hidden = true;+ }+ }+// Clear any previously loaded enriched contentconst descEl = document.getElementById('irl-sheet-description');const skillsEl = document.getElementById('irl-sheet-skills');@@ -1513,22 +2346,45 @@ function updateRadar() {// ── Label 3D→2D projection (called each frame) ───────────────────────────const _lblVec = new Vector3();+// Only flag a focus target when an agent is near enough to actually walk up to+// and interact with — a visible agent across the street shouldn't claim it.+const FOCUS_REACH_M = 60;+let _focusPin = null;function updateLabels() {+ // Pick the nearest on-screen agent within reach as the proximity focus target+ // (B4) in the same projection pass — the "you'll tap this" affordance.+ let focusPin = null, focusDist = Infinity;for (const pin of nearbyPins) {- if (!pin.labelEl || !pin.group) continue;+ if (!pin.labelEl || !pin.group) { pin._labelOnScreen = false; continue; }_lblVec.set(pin.group.position.x,pin.group.position.y + 2.5,pin.group.position.z,);_lblVec.project(camera);- if (_lblVec.z > 1) { pin.labelEl.style.display = 'none'; continue; }+ if (_lblVec.z > 1) { pin.labelEl.style.display = 'none'; pin._labelOnScreen = false; continue; }const sx = (_lblVec.x * 0.5 + 0.5) * window.innerWidth;const sy = (-_lblVec.y * 0.5 + 0.5) * window.innerHeight;const offscreen = sx < -80 || sx > window.innerWidth + 80 || sy < -80 || sy > window.innerHeight + 80;pin.labelEl.style.display = offscreen ? 'none' : 'block';pin.labelEl.style.left = `${sx}px`;pin.labelEl.style.top = `${sy}px`;+ // Cache the projected label centre + visibility for the tap handler's 2D+ // label net (_nearestLabelWithinSlop) — no re-projection on tap.+ pin._labelSx = sx;+ pin._labelSy = sy;+ pin._labelOnScreen = !offscreen;+ if (!offscreen) {+ const dm = pin.distance_m ?? Math.hypot(pin.group.position.x, pin.group.position.z);+ if (dm <= FOCUS_REACH_M && dm < focusDist) { focusDist = dm; focusPin = pin; }+ }+ }+ // Exactly one agent is focused at a time; the swap is eased by the label's+ // transform/box-shadow transition. Cheap: only touches the class on change.+ if (focusPin !== _focusPin) {+ _focusPin?.labelEl?.classList.remove('is-focus');+ focusPin?.labelEl?.classList.add('is-focus');+ _focusPin = focusPin;}}@@ -1554,6 +2410,154 @@ function lerpAngle(a, b, t) {return a + diff * t;}+const _clampSym = (v, max) => (v < -max ? -max : v > max ? max : v);++// ── Camera-aware agents ────────────────────────────────────────────────────+// Reused temporaries — the awareness step runs every frame over several agents,+// so it allocates nothing: all vectors/quaternions below are scratch space.+const _awareList = []; // nearest-first work list, reused+const _awareProj = new Vector3(); // NDC on-screen test+const _gazePitchAxis = new Vector3(); // horizontal axis the head pitches about+const _gazeBoneWorld = new Vector3(); // gaze bone world position+const _gazeYawQuat = new Quaternion();+const _gazePitchQuat = new Quaternion();+const _gazeOffsetQuat = new Quaternion();+const _gazeParentWorld = new Quaternion();+const _gazeParentInv = new Quaternion();+const _gazeRestWorld = new Quaternion();+const _gazeTargetWorld = new Quaternion();+const _gazeTargetLocal = new Quaternion();++function _byAwareDist(a, b) { return a._dist2D - b._dist2D; }++// Rotate a head/torso bone so its neutral (rest) orientation is offset by a+// clamped yaw + pitch about WORLD axes — natural neck movement that reads right+// on any rig without knowing the bone's local "face" axis. `_gazePitchAxis`+// must already hold the horizontal axis to pitch about. Slerps from the bone's+// current pose toward the target so the gaze eases in instead of snapping.+function driveGazeBone(bone, restLocalQuat, yaw, pitch, slerpT) {+ bone.parent.getWorldQuaternion(_gazeParentWorld);+ _gazeRestWorld.multiplyQuaternions(_gazeParentWorld, restLocalQuat);+ _gazeYawQuat.setFromAxisAngle(upY, yaw);+ _gazePitchQuat.setFromAxisAngle(_gazePitchAxis, pitch);+ _gazeOffsetQuat.multiplyQuaternions(_gazeYawQuat, _gazePitchQuat);+ _gazeTargetWorld.multiplyQuaternions(_gazeOffsetQuat, _gazeRestWorld);+ _gazeParentInv.copy(_gazeParentWorld).invert();+ _gazeTargetLocal.multiplyQuaternions(_gazeParentInv, _gazeTargetWorld);+ bone.quaternion.slerp(_gazeTargetLocal, slerpT);+}++// Turn loaded nearby agents toward the viewer. Called from tick() right after+// animMgr.update(dt) and before label projection. Pure client render logic over+// nearbyPins — no data, no network. Cheap: only the nearest few, on-screen,+// in-range agents get full head tracking; everyone else eases home and idles.+function updateAgentAwareness(dt) {+ // Camera forward (horizontal) drives the "is-aware" label glow.+ camera.getWorldDirection(_camWorldDir);+ _camDirH.set(_camWorldDir.x, 0, _camWorldDir.z);+ const camDirHLen = _camDirH.length();+ if (camDirHLen > 0.001) _camDirH.divideScalar(camDirHLen);++ // Collect loaded agents and order nearest-first so the AWARE_MAX_AGENTS cap+ // always spends its budget on the agents the viewer is most likely facing.+ _awareList.length = 0;+ for (const pin of nearbyPins) {+ if (!pin.glbLoaded || !pin.group) continue;+ // The agent under active calibration is driven by the nudge gesture; don't+ // let camera-aware tracking fight the owner's yaw adjustment (A3).+ if (calibrateActive && _cal && _cal.pin === pin) continue;+ pin._dist2D = Math.hypot(+ camera.position.x - pin.group.position.x,+ camera.position.z - pin.group.position.z,+ );+ _awareList.push(pin);+ }+ _awareList.sort(_byAwareDist);++ for (let i = 0; i < _awareList.length; i++) {+ const pin = _awareList[i];+ const dist = pin._dist2D;+ const dx = camera.position.x - pin.group.position.x;+ const dz = camera.position.z - pin.group.position.z;++ // On-screen test (cheap NDC bounds) so off-camera agents cost almost nothing.+ _awareProj+ .set(pin.group.position.x, pin.group.position.y + 1.4, pin.group.position.z)+ .project(camera);+ const onScreen = _awareProj.z < 1 &&+ Math.abs(_awareProj.x) < 1.25 && Math.abs(_awareProj.y) < 1.25;++ const engaged = i < AWARE_MAX_AGENTS && dist <= AWARE_RADIUS_M && onScreen;+ const gazeBone = pin.headBone || pin.spineBone;+ const restQuat = pin.headBone ? pin.restHeadQuat : pin.restSpineQuat;++ if (engaged) {+ // 1) Body: ease the whole agent's yaw toward the camera's ground point.+ const wantYaw = Math.atan2(dx, dz);+ pin.group.rotation.y = lerpAngle(pin.group.rotation.y, wantYaw, BODY_SLERP);++ // 2) Head/torso: lead the body toward the camera inside a natural cone.+ if (gazeBone && restQuat) {+ // Yaw the head should add beyond the body's current facing.+ let resYaw = ((wantYaw - pin.group.rotation.y + Math.PI) % (Math.PI * 2)) - Math.PI;+ if (resYaw < -Math.PI) resYaw += Math.PI * 2;+ resYaw = _clampSym(resYaw, HEAD_CLAMP);+ // Pitch toward the camera's height (look up/down at the viewer's face).+ gazeBone.getWorldPosition(_gazeBoneWorld);+ const pitch = _clampSym(+ Math.atan2(camera.position.y - _gazeBoneWorld.y, Math.max(dist, 1e-3)),+ HEAD_CLAMP,+ );+ const inv = 1 / Math.max(dist, 1e-6);+ _gazePitchAxis.set(-dz * inv, 0, dx * inv); // = cross(toward-camera, up)+ driveGazeBone(gazeBone, restQuat, resYaw, pitch,+ pin.noticeT > 0 ? HEAD_SLERP_NOTICE : HEAD_SLERP);+ }+ pin.idleT = 0;+ } else {+ // Not engaged: ease the body back to its placed heading...+ const baseYaw = pin.baseYaw != null ? pin.baseYaw : pin.group.rotation.y;+ pin.group.rotation.y = lerpAngle(pin.group.rotation.y, baseYaw, BODY_RETURN_SLERP);+ // ...and play a slow gaze drift so an idle agent never reads as frozen.+ if (gazeBone && restQuat) {+ pin.idleT = (pin.idleT || 0) + dt;+ const driftYaw = Math.sin(pin.idleT * 0.4) * 0.12;+ const driftPitch = Math.sin(pin.idleT * 0.27 + 1.3) * 0.05;+ const fy = pin.group.rotation.y; // body forward = (sin fy, 0, cos fy)+ _gazePitchAxis.set(-Math.cos(fy), 0, Math.sin(fy)); // cross(forward, up)+ driveGazeBone(gazeBone, restQuat, driftYaw, driftPitch, HEAD_SLERP * 0.5);+ }+ }++ // ── "Notice" one-shot — fire once each time the viewer enters NOTICE_RADIUS_M.+ // Hysteresis on the way out so a re-approach re-greets without flicker.+ if (!pin.noticed && dist < NOTICE_RADIUS_M) {+ pin.noticed = true;+ pin.noticeT = NOTICE_BOOST_SEC; // snap the head to attention briefly+ pin.popT = 0; // start the perk-up scale pop+ } else if (pin.noticed && dist > NOTICE_RADIUS_M + 1) {+ pin.noticed = false;+ }+ if (pin.noticeT > 0) pin.noticeT = Math.max(0, pin.noticeT - dt);+ if (pin.popT >= 0) {+ pin.popT += dt;+ if (pin.popT >= POP_DURATION) {+ pin.popT = -1;+ pin.group.scale.y = 1;+ } else {+ pin.group.scale.y = 1 + POP_AMOUNT * Math.sin(Math.PI * pin.popT / POP_DURATION);+ }+ }++ // ── "is-aware" label glow — is the camera roughly pointed at this agent? ──+ _toAgentH.set(-dx, 0, -dz);+ const d2 = _toAgentH.length();+ if (d2 > 0.001) _toAgentH.divideScalar(d2);+ const inView = camDirHLen > 0.001 && _camDirH.dot(_toAgentH) > 0.9 && d2 < 30;+ pin.labelEl?.classList.toggle('is-aware', inView);+ }+}+function tick() {clock.update();const dt = Math.min(clock.getDelta(), 0.05);@@ -1612,10 +2616,14 @@ function tick() {// Camera ─────────────────────────────────────────────────────────────────if (gpsModeActive && avatarLocked && arActive) {- // GPS mode: camera fixed at the user's physical eye level.- // The avatar (and nearby agents) are at GPS-derived world positions.- // Gyro delta continues to drive cameraYaw/cameraPitch so pointing the- // phone at the real spot where the agent was placed reveals it there.+ // GPS mode (iOS world-lock, A4). Viewer-centric frame: the user is always+ // the origin, so the camera sits at their eye level (0, EYE_HEIGHT, 0) and+ // every agent is positioned relative to them via gpsToWorld(). Walking is+ // the *world* translating past a fixed camera — onGPSPosition() re-derives+ // the locked avatar (and nearby agents) from their GPS pins each fix, so+ // they grow/hold their real spot instead of following the user. Panning+ // only rotates the camera (gyro cameraYaw/Pitch), leaving the avatar on its+ // real-world bearing. Net effect matches WebXR (A1) without any WebXR.camera.position.set(0, EYE_HEIGHT, 0);camera.rotation.order = 'YXZ';camera.rotation.y = cameraYaw;@@ -1653,47 +2661,352 @@ function tick() {}}+ // Nearby agents notice the viewer — body/head turn, idle drift, greet pop.+ updateAgentAwareness(dt);+// Project nearby agent labels to screen spaceupdateLabels();updateRadar();- // ── Camera-aware agents: each nearby agent slowly faces the camera ────────- // This creates the "mouse hover" effect the user knows from 2D — but in 3D:- // agents turn toward whoever is looking at them via gyro/camera rotation.- camera.getWorldDirection(_camWorldDir);- _camDirH.set(_camWorldDir.x, 0, _camWorldDir.z);- const camDirHLen = _camDirH.length();- if (camDirHLen > 0.001) _camDirH.divideScalar(camDirHLen);+ renderer.render(scene, camera);+ xrViewer._rafId = requestAnimationFrame(tick);+}- for (const pin of nearbyPins) {- if (!pin.glbLoaded || !pin.group) continue;+// ── Nudge-to-calibrate (A3) ────────────────────────────────────────────────+// Cross-user anchor consistency means a placed agent must land in the SAME real+// spot for everyone. Consumer GPS is only ~5–15 m accurate (worse in urban+// canyons / indoors), so the owner — or the anonymous device that placed it —+// can long-press their agent (or tap "Calibrate" in its card) and nudge it a few+// centimetres / degrees into its true spot. The corrected pose re-saves and every+// nearby viewer re-fetches it.+//+// Honest about the ceiling: sub-metre cross-user agreement needs visual+// positioning (VPS). A2 reserved `vps_provider` / `vps_id` for that future path —+// capture a feature snapshot at placement, relocalize viewers against it, and+// store the VPS frame in those columns. Until then the confidence ring + this+// nudge keep the UX truthful and correctable. No coin is involved anywhere here.++let calibrateActive = false;+let _cal = null; // active calibration session, or null++// Pin ids this device placed — gates the client-side calibrate affordance and the+// gold "your agent" label. The server re-checks ownership on every PATCH, so this+// is convenience, not a security boundary.+const _myPinIds = new Set();+function isOwnPin(pin) {+ return _myPinIds.has(pin.id) || (gpsPin?.id != null && pin.id === gpsPin.id);+}- // Rotate the agent on Y-axis to face the camera (horizontal only so feet- // stay on the ground). Uses the same lerpAngle used for the player avatar.- const dx = camera.position.x - pin.group.position.x;- const dz = camera.position.z - pin.group.position.z;- const targetYaw = Math.atan2(dx, dz);- pin.group.rotation.y = lerpAngle(pin.group.rotation.y, targetYaw, NEARBY_FACE_LERP);-- // "Awareness" detection: is the camera currently aimed at this agent?- // Dot product between camera forward vector and camera→agent vector.- _toAgentH.set(- pin.group.position.x - camera.position.x,- 0,- pin.group.position.z - camera.position.z,- );- const dist2D = _toAgentH.length();- if (dist2D > 0.001) _toAgentH.divideScalar(dist2D);- const dot = _camDirH.dot(_toAgentH);- // Within ~25° of camera center (dot > 0.9) and within 30 m → aware- const inView = camDirHLen > 0.001 && dot > 0.9 && dist2D < 30;- pin.labelEl?.classList.toggle('is-aware', inView);+// — Long-press to enter calibrate —+let _lpTimer = null, _lpPin = null, _lpX = 0, _lpY = 0, _lpPointerId = -1;+const LONG_PRESS_MS = 520;++function _pinUnderPointer(e) {+ const groups = nearbyPins.map(p => p.group).filter(Boolean);+ if (!groups.length) return null;+ pointerNDC.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);+ raycaster.setFromCamera(pointerNDC, camera);+ const hits = raycaster.intersectObjects(groups, true);+ if (!hits.length) return null;+ let node = hits[0].object;+ while (node) { const f = nearbyPins.find(p => p.group === node); if (f) return f; node = node.parent; }+ return null;+}++function armLongPress(e) {+ if (placeModeActive || calibrateActive) return;+ cancelLongPress();+ const pin = _pinUnderPointer(e);+ if (!pin) return;+ _lpPin = pin; _lpX = e.clientX; _lpY = e.clientY; _lpPointerId = e.pointerId;+ _lpTimer = setTimeout(() => {+ _lpTimer = null;+ const pin2 = _lpPin;+ if (!pin2) return;+ if (isOwnPin(pin2)) {+ try { navigator.vibrate?.(15); } catch {}+ enterCalibrate(pin2, { pointerId: _lpPointerId, x: _lpX, y: _lpY });+ } else {+ showCalibrateDenied();+ }+ }, LONG_PRESS_MS);+}+function cancelLongPress() { if (_lpTimer) { clearTimeout(_lpTimer); _lpTimer = null; } _lpPin = null; }+function cancelLongPressIfMoved(e) {+ if (_lpTimer && Math.hypot(e.clientX - _lpX, e.clientY - _lpY) > TAP_THRESHOLD) cancelLongPress();+}++// — Calibration session —+function enterCalibrate(pin, seed = null) {+ const panel = document.getElementById('irl-calibrate-panel');+ if (!panel || !pin) return;+ document.getElementById('irl-sheet')?.classList.remove('is-open');+ const yaw0 = Number.isFinite(pin.anchor_yaw_deg) ? pin.anchor_yaw_deg : (pin.heading ?? 0);+ const norm = ((yaw0 % 360) + 360) % 360;+ const h0 = pinHeightM(pin);+ _cal = { pin, origLat: pin.lat, origLng: pin.lng, origYaw: norm, origHeight: h0,+ lat: pin.lat, lng: pin.lng, yaw: norm, height: h0 };+ calibrateActive = true;+ document.body.classList.add('is-calibrating');+ pin.labelEl?.classList.add('is-calibrating');+ const titleEl = document.getElementById('irl-cal-title');+ if (titleEl) titleEl.textContent = `Calibrating ${pin.avatar_name || 'agent'}`;+ const errEl = document.getElementById('irl-cal-error');+ if (errEl) { errEl.hidden = true; errEl.replaceChildren(); }+ const saveBtn = document.getElementById('irl-cal-save');+ if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save position'; }+ updateCalReadout(); updateCalAccuracy(); updateCalHeightLabel();+ panel.classList.add('is-open');+ setStatus('Drag to nudge · twist with two fingers to rotate');+ // Reset gesture state; adopt the held finger (long-press) so the drag is live now.+ _calPtrs.clear(); _calTwistStart = null; _calGroundStart = null; _calDragStart = null;+ if (seed) {+ _calPtrs.set(seed.pointerId, { x: seed.x, y: seed.y });+ const gp = _groundPointXY(seed.x, seed.y);+ _calGroundStart = gp ? { x: gp.x, z: gp.z } : null;+ _calDragStart = { lat: _cal.lat, lng: _cal.lng };+ try { canvas.setPointerCapture?.(seed.pointerId); } catch {}}+}- renderer.render(scene, camera);- requestAnimationFrame(tick);+function exitCalibrate(revert) {+ document.getElementById('irl-calibrate-panel')?.classList.remove('is-open');+ document.body.classList.remove('is-calibrating');+ if (_cal) {+ _cal.pin.labelEl?.classList.remove('is-calibrating');+ if (revert) {+ _cal.lat = _cal.origLat; _cal.lng = _cal.origLng;+ _cal.yaw = _cal.origYaw; _cal.height = _cal.origHeight;+ applyCalToGroup();+ }+ }+ _cal = null;+ calibrateActive = false;+ _calPtrs.clear(); _calTwistStart = null; _calGroundStart = null; _calDragStart = null;+ const saveBtn = document.getElementById('irl-cal-save');+ if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save position'; }+}++// Clamp the working pose to a small correction — calibration, never relocation.+function clampCalToBounds() {+ if (!_cal) return;+ const mLat = 110540, mLng = 111320 * Math.cos(_cal.origLat * Math.PI / 180);+ const north = Math.max(-3, Math.min(3, (_cal.lat - _cal.origLat) * mLat));+ const east = Math.max(-3, Math.min(3, (_cal.lng - _cal.origLng) * mLng));+ _cal.lat = _cal.origLat + north / mLat;+ _cal.lng = _cal.origLng + east / mLng;+ let dy = ((_cal.yaw - _cal.origYaw + 540) % 360) - 180;+ dy = Math.max(-45, Math.min(45, dy));+ _cal.yaw = ((_cal.origYaw + dy) % 360 + 360) % 360;+ _cal.height = Math.max(-1, Math.min(1, _cal.height));}+// Apply the working pose to the live 3D group so the nudge is fully optimistic.+function applyCalToGroup() {+ if (!_cal?.pin.group) return;+ clampCalToBounds();+ const wp = gpsToWorld(_cal.lat, _cal.lng);+ _cal.pin.group.position.set(wp.x, _cal.height, wp.z);+ _cal.pin.group.rotation.y = -(_cal.yaw * Math.PI / 180);+ _cal.pin.baseYaw = _cal.pin.group.rotation.y; // keep the camera-aware rest target in sync+}++function _deltaMetres() {+ const mLat = 110540, mLng = 111320 * Math.cos(_cal.origLat * Math.PI / 180);+ const north = (_cal.lat - _cal.origLat) * mLat;+ const east = (_cal.lng - _cal.origLng) * mLng;+ const dyaw = ((_cal.yaw - _cal.origYaw + 540) % 360) - 180;+ return { north, east, dyaw };+}+function updateCalReadout() {+ const el = document.getElementById('irl-cal-readout');+ if (!el || !_cal) return;+ const { north, east, dyaw } = _deltaMetres();+ const ns = north >= 0 ? 'N' : 'S', ew = east >= 0 ? 'E' : 'W';+ const dh = (_cal.height - _cal.origHeight) * 100;+ el.textContent = `${Math.abs(north).toFixed(2)} m ${ns} · ${Math.abs(east).toFixed(2)} m ${ew} · ${dyaw >= 0 ? '+' : ''}${dyaw.toFixed(0)}° · ${dh >= 0 ? '+' : ''}${dh.toFixed(0)} cm`;+}+function updateCalAccuracy() {+ const el = document.getElementById('irl-cal-accuracy');+ if (!el || !_cal) return;+ const acc = Number.isFinite(_cal.pin.gps_accuracy_m) ? _cal.pin.gps_accuracy_m+ : (Number.isFinite(gpsState.accuracy) ? gpsState.accuracy : null);+ const low = acc != null && acc > RING_LOW_ACC_M;+ el.classList.toggle('is-low', low);+ el.textContent = acc != null+ ? (low+ ? `Position is GPS-accurate to ~${Math.round(acc)} m. Find a spot with clearer sky for a tighter lock, then drag to fine-tune.`+ : `Position is GPS-accurate to ~${Math.round(acc)} m. Drag to fine-tune.`)+ : 'Drag to fine-tune this agent’s real-world spot.';+}+function updateCalHeightLabel() {+ const el = document.getElementById('irl-cal-height');+ if (!el || !_cal) return;+ const dh = (_cal.height - _cal.origHeight) * 100;+ el.textContent = `${dh >= 0 ? '+' : ''}${dh.toFixed(0)} cm`;+}+function nudgeHeight(d) {+ if (!_cal) return;+ _cal.height = Math.max(-1, Math.min(1, (_cal.height || 0) + d));+ applyCalToGroup(); updateCalReadout(); updateCalHeightLabel();+}++// — Touch gestures (drag = move on the ground, two-finger twist = rotate yaw) —+const _calPtrs = new Map();+let _calDragStart = null, _calGroundStart = null, _calTwistStart = null;++function _groundPointXY(clientX, clientY) {+ pointerNDC.set((clientX / window.innerWidth) * 2 - 1, -(clientY / window.innerHeight) * 2 + 1);+ raycaster.setFromCamera(pointerNDC, camera);+ const hits = raycaster.intersectObject(rayPlane);+ return hits.length ? hits[0].point : null;+}+function _twoFingerAngle() {+ const pts = [..._calPtrs.values()];+ return Math.atan2(pts[1].y - pts[0].y, pts[1].x - pts[0].x);+}+function calPointerDown(e) {+ if (!calibrateActive) return;+ _calPtrs.set(e.pointerId, { x: e.clientX, y: e.clientY });+ try { canvas.setPointerCapture?.(e.pointerId); } catch {}+ if (_calPtrs.size >= 2) {+ _calTwistStart = { angle: _twoFingerAngle(), yaw: _cal.yaw };+ _calGroundStart = null;+ } else {+ const gp = _groundPointXY(e.clientX, e.clientY);+ _calGroundStart = gp ? { x: gp.x, z: gp.z } : null;+ _calDragStart = { lat: _cal.lat, lng: _cal.lng };+ }+}+function calPointerMove(e) {+ if (!calibrateActive || !_calPtrs.has(e.pointerId)) return;+ _calPtrs.set(e.pointerId, { x: e.clientX, y: e.clientY });+ if (_calPtrs.size >= 2) {+ // Two-finger twist → yaw nudge. Live feedback lets the owner aim it; clamp ±45°.+ if (!_calTwistStart) _calTwistStart = { angle: _twoFingerAngle(), yaw: _cal.yaw };+ let dDeg = (_twoFingerAngle() - _calTwistStart.angle) * 180 / Math.PI;+ dDeg = Math.max(-45, Math.min(45, dDeg));+ _cal.yaw = ((_calTwistStart.yaw + dDeg) % 360 + 360) % 360;+ applyCalToGroup(); updateCalReadout();+ return;+ }+ // Single-finger ground drag → horizontal nudge in metres (clamped ±3 m N/E).+ if (!_calGroundStart || !_calDragStart) {+ const gp0 = _groundPointXY(e.clientX, e.clientY);+ if (gp0) { _calGroundStart = { x: gp0.x, z: gp0.z }; _calDragStart = { lat: _cal.lat, lng: _cal.lng }; }+ return;+ }+ const gp = _groundPointXY(e.clientX, e.clientY);+ if (!gp) return;+ const dEast = Math.max(-3, Math.min(3, gp.x - _calGroundStart.x));+ const dNorth = Math.max(-3, Math.min(3, -(gp.z - _calGroundStart.z)));+ const mLat = 110540, mLng = 111320 * Math.cos(_calDragStart.lat * Math.PI / 180);+ _cal.lat = _calDragStart.lat + dNorth / mLat;+ _cal.lng = _calDragStart.lng + dEast / mLng;+ applyCalToGroup(); updateCalReadout();+}+function calPointerUp(e) {+ if (!_calPtrs.has(e.pointerId)) return;+ _calPtrs.delete(e.pointerId);+ try { canvas.releasePointerCapture?.(e.pointerId); } catch {}+ if (_calPtrs.size < 2) _calTwistStart = null;+ if (_calPtrs.size === 0) { _calGroundStart = null; _calDragStart = null; }+ else { _calGroundStart = null; _calDragStart = { lat: _cal.lat, lng: _cal.lng }; } // rebase, avoid a jump+}++// — Save / errors —+async function saveCalibrate() {+ if (!_cal) return;+ const saveBtn = document.getElementById('irl-cal-save');+ const errEl = document.getElementById('irl-cal-error');+ if (errEl) { errEl.hidden = true; errEl.replaceChildren(); }+ if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Saving…'; }+ const pin = _cal.pin;+ const body = { id: pin.id, deviceToken: _deviceToken, calibrate: {+ lat: _cal.lat, lng: _cal.lng, anchorYawDeg: _cal.yaw, anchorHeightM: _cal.height } };+ try {+ const r = await fetch('/api/irl/pins', {+ method: 'PATCH', credentials: 'include',+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),+ });+ if (!r.ok) {+ const m = r.status === 403 ? 'Only the owner can calibrate this agent.'+ : r.status === 422 ? 'That nudge is too large — calibration is for fine-tuning, not moving the agent.'+ : r.status === 404 ? 'This agent is no longer here.'+ : 'Could not save the new position.';+ throw new Error(m);+ }+ // Commit the corrected pose onto the live pin so it persists this session and+ // every nearby viewer's next re-fetch picks it up (realtime push rides on D1).+ pin.lat = _cal.lat; pin.lng = _cal.lng;+ pin.anchor_yaw_deg = _cal.yaw; pin.heading = Math.round(_cal.yaw);+ pin.anchor_height_m = _cal.height;+ setStatus('Position calibrated — everyone nearby now sees it here');+ exitCalibrate(false);+ loadNearbyPins();+ } catch (err) {+ // Optimistic-undo: keep the nudge on screen with a retry / undo chip — never+ // leave a half-applied, local-only correction.+ if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Save position'; }+ if (errEl) {+ errEl.replaceChildren(errorStateEl({+ title: 'Save failed',+ body: _escHtml(err.message || 'Could not save the new position.'),+ actions: [+ { label: 'Retry', id: 'cal-retry', primary: true },+ { label: 'Undo', id: 'cal-undo' },+ ],+ }));+ errEl.hidden = false;+ }+ }+}++function showCalibrateDenied() {+ const el = document.getElementById('irl-cal-denied');+ if (!el) { setStatus('Only the owner can calibrate this agent', { error: true }); return; }+ el.replaceChildren(errorStateEl({+ title: 'Calibration locked',+ body: 'Only the owner can calibrate this agent’s position.',+ actions: [{ label: 'Got it', id: 'cal-denied-ok', primary: true }],+ }));+ el.hidden = false;+ requestAnimationFrame(() => el.classList.add('is-open'));+ clearTimeout(showCalibrateDenied._t);+ showCalibrateDenied._t = setTimeout(() => {+ el.classList.remove('is-open');+ setTimeout(() => { el.hidden = true; }, 220);+ }, 4200);+}++// — Wiring —+canvas.addEventListener('pointermove', cancelLongPressIfMoved);+canvas.addEventListener('pointercancel', cancelLongPress);+// Capture phase so a calibrate gesture beats the orbit / tap handlers; no-op when+// calibration isn't active, so normal orbiting / tapping is untouched.+canvas.addEventListener('pointerdown', calPointerDown, true);+canvas.addEventListener('pointermove', calPointerMove, true);+canvas.addEventListener('pointerup', calPointerUp, true);+canvas.addEventListener('pointercancel', calPointerUp, true);++document.getElementById('irl-cal-save')?.addEventListener('click', saveCalibrate);+document.getElementById('irl-cal-cancel')?.addEventListener('click', () => exitCalibrate(true));+document.getElementById('irl-cal-up')?.addEventListener('click', () => nudgeHeight(0.05));+document.getElementById('irl-cal-down')?.addEventListener('click', () => nudgeHeight(-0.05));+document.getElementById('irl-cal-error')?.addEventListener('click', (e) => {+ const a = e.target.closest('[data-sk-action]');+ if (!a) return;+ if (a.dataset.skAction === 'cal-retry') saveCalibrate();+ else if (a.dataset.skAction === 'cal-undo') exitCalibrate(true);+});+document.getElementById('irl-cal-denied')?.addEventListener('click', (e) => {+ if (!e.target.closest('[data-sk-action]')) return;+ const el = document.getElementById('irl-cal-denied');+ el.classList.remove('is-open');+ setTimeout(() => { el.hidden = true; }, 220);+});+window.addEventListener('keydown', (e) => { if (e.key === 'Escape' && calibrateActive) exitCalibrate(true); });+// ── Boot ──────────────────────────────────────────────────────────────────initGPS();@@ -1707,7 +3020,7 @@ const _targetAvatarId = avatarIdParam || _savedSession?.avatarId || null;loadAvatar(_targetAvatarId).then(() => {_restoreSession();- requestAnimationFrame(tick);+ startTick();}).catch(err => {log.error('[irl] avatar load failed:', err);@@ -1715,5 +3028,10 @@ loadAvatar(_targetAvatarId)setStatus(`Couldn't load avatar: ${err?.message ?? err}`, { error: true, sticky: true });cameraBtn.disabled = false;cameraBtn.removeAttribute('aria-busy');- requestAnimationFrame(tick);+ startTick();});++// Detect WebXR floor-anchoring support and reveal the entry once ready. iOS+// Safari (no immersive-ar) never sees the button and stays on the gyro+GPS Pin+// path; desktop Chrome reports false and adds no console noise.+detectFloorAnchorSupport();diff --git a/tasks/irl-live/A1-webxr-world-anchor.md b/tasks/irl-live/A1-webxr-world-anchor.mdnew file mode 100644index 000000000..e04c4a262--- /dev/null+++ b/tasks/irl-live/A1-webxr-world-anchor.md@@ -0,0 +1,148 @@+# 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.diff --git a/tasks/irl-live/A2-anchor-persistence-schema.md b/tasks/irl-live/A2-anchor-persistence-schema.mdnew file mode 100644index 000000000..78369e589--- /dev/null+++ b/tasks/irl-live/A2-anchor-persistence-schema.md@@ -0,0 +1,145 @@+# 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`.diff --git a/tasks/irl-live/A3-cross-user-anchor-consistency.md b/tasks/irl-live/A3-cross-user-anchor-consistency.mdnew file mode 100644index 000000000..e94a46212--- /dev/null+++ b/tasks/irl-live/A3-cross-user-anchor-consistency.md@@ -0,0 +1,150 @@+# 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.diff --git a/tasks/irl-live/A4-ios-gyro-anchor-fallback.md b/tasks/irl-live/A4-ios-gyro-anchor-fallback.mdnew file mode 100644index 000000000..429f5d47a--- /dev/null+++ b/tasks/irl-live/A4-ios-gyro-anchor-fallback.md@@ -0,0 +1,154 @@+# 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`.diff --git a/tasks/irl-live/B1-camera-aware-lookat.md b/tasks/irl-live/B1-camera-aware-lookat.mdnew file mode 100644index 000000000..a624fa543--- /dev/null+++ b/tasks/irl-live/B1-camera-aware-lookat.md@@ -0,0 +1,128 @@+# 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.diff --git a/tasks/irl-live/B2-inspect-card-v2.md b/tasks/irl-live/B2-inspect-card-v2.mdnew file mode 100644index 000000000..0e63ead3b--- /dev/null+++ b/tasks/irl-live/B2-inspect-card-v2.md@@ -0,0 +1,151 @@+# 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.diff --git a/tasks/irl-live/B3-real-interactions-profile-pay.md b/tasks/irl-live/B3-real-interactions-profile-pay.mdnew file mode 100644index 000000000..319543873--- /dev/null+++ b/tasks/irl-live/B3-real-interactions-profile-pay.md@@ -0,0 +1,152 @@+# 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).diff --git a/tasks/irl-live/B4-raycast-tap-accuracy.md b/tasks/irl-live/B4-raycast-tap-accuracy.mdnew file mode 100644index 000000000..04f240411--- /dev/null+++ b/tasks/irl-live/B4-raycast-tap-accuracy.md@@ -0,0 +1,114 @@+# 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.diff --git a/tasks/irl-live/C1-dashboard-overview.md b/tasks/irl-live/C1-dashboard-overview.mdnew file mode 100644index 000000000..a6e0bec95--- /dev/null+++ b/tasks/irl-live/C1-dashboard-overview.md@@ -0,0 +1,137 @@+# C1 — Owner dashboard overview (live IRL agent monitoring)++> Epic C · Size **M** · Extends `src/dashboard-next/pages/irl-placements.js`.+> Foundation for C2–C6 — every per-agent action surface links off this card.++## Goal++Turn the flat "My Placed Avatars" list into a real **monitoring overview**. Each+placed-agent card surfaces, at a glance: live $THREE/SOL balance, online/visible+status, last-seen + last-interaction time, lifetime interaction count, and a+human location label. From each card the owner opens the management surfaces+(skills, reputation, location, outfit, inbox) built in C2–C6.++## Why it matters++A pin you can't observe is dead weight. Owners place an agent somewhere they+aren't standing, then leave. The dashboard is their only window onto whether+the agent is working, earning, and being interacted with. Without live signal+the product is a write-only toy. This card is the home base for the whole epic.++## Current state (real lines)++- `src/dashboard-next/pages/irl-placements.js:131` `mount(el)` renders skeletons+ (`:141`), fetches `GET /api/irl/pins?mine=1` (`:145`), renders `cardHtml` (`:97`),+ then reverse-geocodes each pin one-at-a-time (`:169`). Remove + caption edit are+ wired via delegation (`:184`).+- `api/irl/pins.js:80` the `?mine=1` branch already selects+ `id, lat, lng, heading, avatar_url, avatar_name, caption, agent_id, placed_at, expires_at`.+ **`agent_id` is already returned** — the link to the agent record exists.+- Balance source: `api/agents/solana-wallet.js:257` `handlePublicWalletRead`+ returns `{ data: { wallet, balance, lamports, balance_error } }` (no auth, 60 s+ cached). Route: `GET /api/agents/:id/solana`.+- No status/last-seen/interaction-count exists yet — C4 introduces `irl_interactions`.++## What to build++### 1. `GET /api/irl/agent-summary?mine=1` (new, in `api/irl/pins.js` or sibling)++One round-trip that joins each owned pin to its agent + derived activity, so the+card paints without N balance calls blocking first render.++```js+// auth required; returns one row per owned pin+const rows = await sql`+ SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,+ p.avatar_url, p.avatar_name, p.placed_at, p.expires_at,+ a.name AS agent_name, a.meta->>'solana_address' AS solana_address,+ a.meta->>'solana_asset' AS solana_asset,+ COALESCE(ix.total, 0) AS interaction_count,+ ix.last_at AS last_interaction_at+ FROM irl_pins p+ LEFT JOIN agent_identities a ON a.id = p.agent_id AND a.deleted_at IS NULL+ LEFT JOIN (+ SELECT pin_id, COUNT(*)::int AS total, MAX(created_at) AS last_at+ FROM irl_interactions GROUP BY pin_id -- table from C4+ ) ix ON ix.pin_id = p.id+ WHERE p.user_id = ${session.id}+ ORDER BY p.placed_at DESC LIMIT 100`;+```++If `irl_interactions` is not yet created (C4 not shipped), wrap the LEFT JOIN in a+`to_regclass('irl_interactions') IS NOT NULL` guard and fall back to `0`/`NULL` —+never 500. Status is **derived**: `online` if a nearby-fetch touched the pin in+the last 5 min (C4/D1 will write `last_seen_at`); until then derive `visible` from+`expires_at > NOW()`.++### 2. Card upgrade in `irl-placements.js`++Keep `mountShell` + `requireUser` + `get()` exactly as-is. Replace the+hand-rolled skeleton/empty/error with **state-kit**:++```js+import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles, attachRetry }+ from '../../shared/state-kit.js';++ensureStateKitStyles();+list.innerHTML = `<div class="irl-grid">${skeletonHTML(3, 'row')}</div>`;+// error → errorStateHTML({ title:'Couldn't load your IRL agents', scope:'irl' }); attachRetry(list, render)+// empty → emptyStateHTML({ title:'No agents placed yet', body:'…', actions:[{label:'Open IRL', href:'/irl', primary:true}] })+```++Extend `cardHtml(pin, geo)` with a stats strip (skeleton values first, hydrated+after). Render a **balance chip** (`—` skeleton → `0.42 SOL` / `Balance+unavailable` on `balance_error`), a **status dot** (green online / amber visible /+grey expired), **last interaction** (`relTime`), and an **interaction count**.+Add a tab/link row on each card to the C2–C6 surfaces:++```+[Skills] [Reputation] [Location] [Outfit] [Inbox •3] View in IRL ↗ Remove+```++Each is an anchor/button carrying `data-pin="${pin.id}" data-agent="${pin.agent_id}"`.+Disable Skills/Reputation/Outfit (with a tooltip) when `agent_id` is null — an+anonymously-placed avatar has no agent record to manage.++### 3. Balance hydration (parallel, non-blocking)++After cards paint, fan out exactly like `widgets.js:78` does with stats:++```js+const bals = await Promise.allSettled(rows.map(r =>+ r.agent_id ? get(`/api/agents/${encodeURIComponent(r.agent_id)}/solana`) : Promise.reject('no-agent')));+bals.forEach((res, i) => applyBalanceToCard(card(i),+ res.status === 'fulfilled' ? res.value.data : { balance_error: 'unavailable' }));+```++Render `balance_error` as the literal "Balance unavailable" chip (per the+wallet-card convention) — never show a misleading `0`.++## Data / API changes++- New: `GET /api/irl/agent-summary?mine=1` → `{ agents: [...] }` (auth). Register+ its route in `vercel.json` (mirror the `/api/irl/pins` entry).+- No `irl_pins` schema change. Reuses `agent_identities.meta.solana_address`.+- Reuses existing `GET /api/agents/:id/solana` for balance.++## Acceptance checklist++- [ ] `GET /api/irl/agent-summary?mine=1` returns agents w/ counts; degrades to+ `0`/`null` when `irl_interactions` absent; never 500s.+- [ ] Card shows balance chip, status dot, last-seen, interaction count, location.+- [ ] Balance hydrates in parallel after first paint; `balance_error` → "Balance+ unavailable", not `0`.+- [ ] state-kit skeleton/empty/error with working Retry.+- [ ] Each card links to C2–C6 surfaces (disabled + tooltip when `agent_id` null).+- [ ] Reverse-geocode label preserved; 320 / 768 / 1440px clean; no console errors.++## Out of scope++Realtime push of status (D1/D3), the management panels themselves (C2–C6), and+the interaction table itself (C4) — this card only *reads* and *links*.++## Verify++`npm run dev` → `/dashboard/irl-placements` with ≥1 placed agent: confirm the+Network tab shows one `agent-summary` call + parallel `…/solana` calls, balance+chips resolve to real on-chain values, and every card link navigates.diff --git a/tasks/irl-live/C2-skills-services-management.md b/tasks/irl-live/C2-skills-services-management.mdnew file mode 100644index 000000000..d9199ba2e--- /dev/null+++ b/tasks/irl-live/C2-skills-services-management.md@@ -0,0 +1,117 @@+# 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.diff --git a/tasks/irl-live/C3-reputation-surface.md b/tasks/irl-live/C3-reputation-surface.mdnew file mode 100644index 000000000..c0cd61e7d--- /dev/null+++ b/tasks/irl-live/C3-reputation-surface.md@@ -0,0 +1,90 @@+# 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.diff --git a/tasks/irl-live/C4-interaction-inbox-notifications.md b/tasks/irl-live/C4-interaction-inbox-notifications.mdnew file mode 100644index 000000000..b43cc4a00--- /dev/null+++ b/tasks/irl-live/C4-interaction-inbox-notifications.md@@ -0,0 +1,155 @@+# 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.diff --git a/tasks/irl-live/C5-remote-location-management.md b/tasks/irl-live/C5-remote-location-management.mdnew file mode 100644index 000000000..f3ca3ae93--- /dev/null+++ b/tasks/irl-live/C5-remote-location-management.md@@ -0,0 +1,144 @@+# 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.diff --git a/tasks/irl-live/C6-remote-outfit-change.md b/tasks/irl-live/C6-remote-outfit-change.mdnew file mode 100644index 000000000..987e3f104--- /dev/null+++ b/tasks/irl-live/C6-remote-outfit-change.md@@ -0,0 +1,144 @@+# 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.diff --git a/tasks/irl-live/D1-realtime-pin-sync.md b/tasks/irl-live/D1-realtime-pin-sync.mdnew file mode 100644index 000000000..02cc640fa--- /dev/null+++ b/tasks/irl-live/D1-realtime-pin-sync.md@@ -0,0 +1,185 @@+# 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".diff --git a/tasks/irl-live/D2-live-viewer-presence.md b/tasks/irl-live/D2-live-viewer-presence.mdnew file mode 100644index 000000000..e87f14c6f--- /dev/null+++ b/tasks/irl-live/D2-live-viewer-presence.md@@ -0,0 +1,137 @@+# 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.diff --git a/tasks/irl-live/D3-interaction-broadcast.md b/tasks/irl-live/D3-interaction-broadcast.mdnew file mode 100644index 000000000..be549389c--- /dev/null+++ b/tasks/irl-live/D3-interaction-broadcast.md@@ -0,0 +1,170 @@+# 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.diff --git a/tasks/irl-live/D4-moderation-safety-caps.md b/tasks/irl-live/D4-moderation-safety-caps.mdnew file mode 100644index 000000000..e39e31a27--- /dev/null+++ b/tasks/irl-live/D4-moderation-safety-caps.md@@ -0,0 +1,178 @@+# 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`.diff --git a/tasks/irl-live/E1-permissions-onboarding.md b/tasks/irl-live/E1-permissions-onboarding.mdnew file mode 100644index 000000000..d4d45cda1--- /dev/null+++ b/tasks/irl-live/E1-permissions-onboarding.md@@ -0,0 +1,142 @@+# 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.diff --git a/tasks/irl-live/E2-performance-scale.md b/tasks/irl-live/E2-performance-scale.mdnew file mode 100644index 000000000..447585459--- /dev/null+++ b/tasks/irl-live/E2-performance-scale.md@@ -0,0 +1,153 @@+# 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.diff --git a/tasks/irl-live/E3-deeplinks-share.md b/tasks/irl-live/E3-deeplinks-share.mdnew file mode 100644index 000000000..e27fc34da--- /dev/null+++ b/tasks/irl-live/E3-deeplinks-share.md@@ -0,0 +1,141 @@+# 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.diff --git a/tasks/irl-live/E4-designed-states.md b/tasks/irl-live/E4-designed-states.mdnew file mode 100644index 000000000..71a226bdf--- /dev/null+++ b/tasks/irl-live/E4-designed-states.md@@ -0,0 +1,104 @@+# 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.diff --git a/tasks/irl-live/README.md b/tasks/irl-live/README.mdnew file mode 100644index 000000000..a59cc3d55--- /dev/null+++ b/tasks/irl-live/README.md@@ -0,0 +1,118 @@+# IRL-Live — Multiplayer World-Anchored 3D AI Agents++The program that turns `three.ws/irl` from a single-user AR toy into a **shared,+persistent, multiplayer layer of 3D AI agents anchored to real-world places**.++Anyone who opens `three.ws/irl` at a location, points their camera, and sees the+agents other people have placed there — locked to the real world, aware of the+viewer, tappable for a profile + services card, and payable via x402. Owners+manage their placed agents (balance, skills, reputation, outfit, location,+interaction inbox) from a dashboard anywhere on earth.++---++## The four pillars (what the user asked for)++1. **Pick & lock** — choose which 3D AI agent is displayed and lock it into the+ real world so it stays put when you move the camera. *(Epic A)*+2. **Aware & interactive** — agents turn to face the viewer's camera (the+ "follow the cursor" trick, but the cursor is your phone). Tap one and a card+ pops up: name, info, reputation, services. *(Epic B)*+3. **Owner dashboard** — monitor your IRL agents: balance, skills/services,+ reputation, interaction prompts, outfit changes, and location — all+ remotely, even after you've left the spot. *(Epic C)*+4. **Multiplayer** — *anyone* at the location sees *anyone's* placed agent, live.+ Not just your own. *(Epic D)*++---++## What already exists (do NOT rebuild — extend)++Grounded in the current tree as of this plan:++| Piece | Location | State |+|---|---|---|+| IRL AR client | `pages/irl.html` + `src/irl.js` (~1424 lines) | Camera passthrough, gyro look (`cameraYaw`/`cameraPitch`), GPS watch, tap-to-place, avatar hot-swap picker, **Lock** button (`setLocked()` ~682), `savePin()` ~837, `loadNearbyPins()` ~901 (**already public / cross-user**), `spawnNearbyPin()` ~950, `loadPinGLB()` ~990, `openPinSheet()` ~1135, radar math ~1239, `tick()` ~1355 |+| Pins API + table | `api/irl/pins.js` (~213 lines) | Neon `irl_pins` (`id, user_id, agent_id, device_token, lat, lng, heading, avatar_url, avatar_name, caption, x402_endpoint, placed_at, expires_at`). GET nearby (public, haversine), GET `?mine=1`, POST, PATCH caption, DELETE |+| Owner dashboard page | `src/dashboard-next/pages/irl-placements.js` (~274 lines) | Lists your placed pins, reverse-geocode, remove — location management baseline |+| AR/XR infra | `src/ar/webxr.js`, `src/ar/quick-look.js`, `src/ar/scene-viewer.js`, `src/xr.js` | WebXR + iOS Quick Look + Android Scene Viewer entry points |+| Avatar picker | `src/avatar-picker.js` (`createAvatarPicker`) | Shared bottom-sheet picker, GLB hot-swap |+| Wardrobe / outfits | `src/avatar-wardrobe.js`, `src/agent-accessories.js` | Outfit + accessory system |+| Reputation | `GET /api/agents/solana-reputation?asset=` | Real Solana attestations — the canonical reputation source |+| Skills / services | `api/skills/index.js`, `api/skills/[id].js`, `api/skills/categories.js`, `api/skills-manifest.js` | Skill catalog + per-agent skills |+| Wallet / balance | `api/agents/solana-wallet.js`, `api/agents/x402/[action].js`, `api/billing/*` | Agent wallet + earnings |+| x402 client | already imported in `src/irl.js` and `src/marketplace.js` via `src/shared/x402-loader.js` | Pay-per-call flow |+| Realtime server | `wss://three-ws-multiplayer.fly.dev` (walk-server), client in `src/walk-net.js` | Existing multiplayer WS — reuse for IRL presence |+| Shared UI states | `src/shared/state-kit.js`, `src/shared/async-state.js` | Skeleton / empty / error / retry shells — use everywhere |++**Prior roadmap (folded into this program):** `tasks/irl/01-06`, `tasks/irl-xr/01-05`,+`tasks/task-irl-01/02/03`. Where a new task supersedes an old one it says so;+treat the old files as reference, not parallel work.++---++## Epics & task index++### Epic A — World-anchored locking ("stays put in real life")+- **A1** `A1-webxr-world-anchor.md` — WebXR hit-test reticle + real-world anchor placement (Android/Chrome). *L*+- **A2** `A2-anchor-persistence-schema.md` — Extend `irl_pins` to store a full anchor pose (height, orientation, accuracy); migrate `savePin`. *M*+- **A3** `A3-cross-user-anchor-consistency.md` — GPS+compass alignment + manual nudge calibration so every viewer sees the agent in the *same* real spot. *L*+- **A4** `A4-ios-gyro-anchor-fallback.md` — iOS Safari (no WebXR) world-lock via gyro+GPS dead-reckoning so the locked avatar stays anchored when panning. *M*++### Epic B — Agent awareness & interaction+- **B1** `B1-camera-aware-lookat.md` — Placed agents turn head/body to face the viewer's camera + idle gaze (the "follow the cursor" analog). *M*+- **B2** `B2-inspect-card-v2.md` — Rich tap card: name, info, reputation, services/prices. New `GET /api/irl/agent-card`. *M*+- **B3** `B3-real-interactions-profile-pay.md` — Wire View profile → `/agents/:id` and real x402 pay (supersedes `tasks/irl/02` + `03`). *M*+- **B4** `B4-raycast-tap-accuracy.md` — Reliable tap raycasting on billboard labels + meshes, nearest-agent proximity focus. *S*++### Epic C — Owner dashboard for IRL agents+- **C1** `C1-dashboard-overview.md` — Extend `irl-placements.js`: balance, status, last-seen, interaction count per placed agent. *M*+- **C2** `C2-skills-services-management.md` — Attach skills + set x402 service prices for an IRL agent from the dashboard. *M*+- **C3** `C3-reputation-surface.md` — Show reputation/attestations for the placed agent + manage link. *S*+- **C4** `C4-interaction-inbox-notifications.md` — New `irl_interactions` table; log taps/pays/messages; owner inbox + notifications. *L*+- **C5** `C5-remote-location-management.md` — Map with draggable marker to relocate/remove pins from anywhere. *M*+- **C6** `C6-remote-outfit-change.md` — Change a placed agent's outfit remotely; propagate to the rendered GLB for all viewers. *L*++### Epic D — Multiplayer realtime+- **D1** `D1-realtime-pin-sync.md` — Live add/remove/update of nearby pins without reload (geohash rooms over the existing WS, with poll fallback). *L*+- **D2** `D2-live-viewer-presence.md` — Show who else is viewing a location; optional ghost markers of live viewers. *M*+- **D3** `D3-interaction-broadcast.md` — IRL interaction → owner realtime event + ambient reaction visible to co-located viewers. *M*+- **D4** `D4-moderation-safety-caps.md` — Content checks on caption/avatar, report flow, per-area density + per-user pin caps, rate limits. *M*++### Epic E — Cross-cutting polish+- **E1** `E1-permissions-onboarding.md` — Camera/motion/location permission flow with designed states (incl. iOS motion gesture). *M*+- **E2** `E2-performance-scale.md` — Distance culling, GLB LOD, concurrent-load cap, draw budget for dense areas. *M*+- **E3** `E3-deeplinks-share.md` — "View in IRL" from agent/avatar pages + screenshot composite share (supersedes `irl-xr/03` + `05`). *M*+- **E4** `E4-designed-states.md` — Empty/error/permission/unsupported-device states across all IRL surfaces. *S*++---++## Recommended run order & dependency graph++**Critical path (do first):** A2 → A1/A4 → B1/B2/B3 → D1 → D3/C4.++```+A2 (schema) ─┬─> A1 (webxr anchor) ─┐+ └─> A4 (ios fallback) ─┴─> A3 (cross-user consistency)+B2 (card api) ─> B3 (interactions) ; B1 (look-at) ; B4 (raycast) independent+D1 (realtime sync) ─> D2 (presence) ; D3 (interaction broadcast) ─> C4 (inbox)+C1 ─> C2, C3, C5, C6 (dashboard surfaces, after overview)+E1, E2, E4 land alongside any epic; E3 after B/D.+```++Suggested phased execution:+1. **Phase 1 — Anchoring foundation:** A2, A1, A4, E1.+2. **Phase 2 — Make agents feel alive:** B1, B2, B3, B4, E4.+3. **Phase 3 — Multiplayer live:** D1, D2, D4, A3, E2.+4. **Phase 4 — Owner control + feedback loop:** C1, C4, D3, C5, C6, C2, C3, E3.++---++## Ground rules for every task++- **$THREE is the only coin** (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Never reference any other token anywhere.+- **No mocks, no placeholders, no fake data.** Real APIs, real RPC, real wallet, real DB.+- **Every state designed** — loading/empty/error/permission-denied/unsupported via `src/shared/state-kit.js`.+- **Errors at boundaries** — every `fetch`/sensor call fails into a retryable state, never a blank screen.+- **Mobile-first** — this is a phone-camera product. Test at real device widths; mind iOS Safari quirks (motion permission gesture, no WebXR).+- **Each task file is self-contained** — copy its prompt into a fresh agent and it can execute without this README.diff --git a/vercel.json b/vercel.jsonindex 06de5d4b6..18ae8200f 100644--- a/vercel.json+++ b/vercel.json@@ -172,6 +172,9 @@"api/irl/interactions.js": {"maxDuration": 15},+ "api/irl/agent-summary.js": {+ "maxDuration": 15+ },"api/irl/agent-card.js": {"maxDuration": 15},@@ -1953,6 +1956,10 @@"src": "/api/irl/interactions","dest": "/api/irl/interactions.js"},+ {+ "src": "/api/irl/agent-summary",+ "dest": "/api/irl/agent-summary.js"+ },{"src": "/api/irl/agent-card","dest": "/api/irl/agent-card.js"