Skip to content

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.

Add IRL map placement, agent custody wallet, sniper worker resilience

nirholas4c85eba9201d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 815b5755a..1a2ae9e18 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -42,6 +42,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **See how many people are viewing a spot with you on IRL** — three.ws/irl now shows when you're not alone. A small live count next to the nearby badge reads '3 viewing nearby' whenever other people have the same location open at the same time, so a place feels inhabited even before anyone has pinned an agent there — and it updates the instant someone arrives or leaves. Your location stays private: the count is built from a coarse ~1km area, never your precise GPS, and nobody can see where you are by default. If you want to be visible you can turn on 'Appear nearby' (off unless you choose it), which shows you to others as a faint, anonymous marker on their radar and in their view — no name, not tappable, clearly distinct from a placed agent. You can flip it on or off at any time and others see the change immediately. The count only appears while you have a live connection, so it never shows a stale or made-up number. (`/irl`) `[feature]`
- **See your IRL agent's on-chain reputation right from the dashboard** — On your IRL Agents dashboard, the Reputation chip on each placed agent now opens an on-chain reputation panel — the exact score and trust tier (Elite, Trusted, Emerging, New) a passer-by sees when they tap your agent in real life. It breaks down how many attestations are verified, credentialed, and disputed, shows the average star rating and how many distinct people vouched, and links straight to the agent's passport to manage it. Agents without a Solana identity, or without any attestations yet, get a clear next step instead of an error. (`/dashboard/irl-placements`) `[feature]`
- **Share a photo straight from the XR viewer** — three.ws/xr now has the same one-tap Share that three.ws/irl has had: it flattens your live camera view and the 3D agent into a single photo and hands it to your phone's share sheet to post or send — or downloads it as a PNG on desktop. With the camera on, the picture shows your agent standing in your real surroundings; with it off, it shares the 3D view on its own. If a snapshot can't be captured for any reason, Share falls back to sending the page link so it's never a dead end. The Share buttons on both pages now show a brief progress state while the image is being made, and the immersive buttons give keyboard users a clear focus outline. (`/xr`) `[feature, improvement]`
+- **Sniper dashboard: your live positions now show real-time profit and loss and reconnect on their own** — The Sniper Strategies dashboard now streams your agents' open positions with live unrealized profit and loss — both the SOL figure and the percentage — instead of a blank value, and fills them in the moment the page loads rather than waiting for the next trade to land. The live feed shows its own connection state (Live / Reconnecting) and re-establishes itself automatically with backoff if it drops, so you always know whether you're watching real-time data. Closed-trade history now calls out your single best and worst trade, and there are one-tap links to the public leaderboard and sniper arena so your track record is easy to share. (`/dashboard/sniper`) `[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]`
- **The Oracle's proof pages — wins, backtest, and live activity — load again** — The conviction Oracle's evidence views had stopped responding: the Wins gallery, the accuracy Backtest, and the global Activity feed were all erroring instead of returning data, and the live activity feed failed on every request. The cause was in how those queries were assembled — optional filters (time window, tier, agent) weren't being stitched into the database query correctly, so the database rejected them. All three views now build their filters cleanly and return the Oracle's track record, hit-rate, and real-time agent actions as intended. (`/oracle`) `[fix]`
- **Your IRL agent dashboard now lights up the instant someone interacts** — When a stranger taps, messages, or pays one of your agents placed out in the real world, your dashboard now reflects it within about a second — no refresh. The agent's card flashes, the unread count ticks up live, and a payment or a new message pops a notification so you feel the moment it happens, even from the other side of the planet. A small Live indicator shows when the realtime connection is up; if it ever drops, the inbox keeps updating on a short delay instead, so you never miss an encounter. Only your agent's name and the kind of interaction are ever shared with you — never the visitor's location or wallet. (`/dashboard/irl-placements`) `[feature, improvement]`
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.js
index 54f206079..0f785cbe8 100644
--- a/api/_lib/agent-wallet.js
+++ b/api/_lib/agent-wallet.js
@@ -408,6 +408,91 @@ export async function getSolanaAddressBalances(address, cluster = 'mainnet') {
return { sol, usdc };
}
+// Validate a string is a syntactically valid Solana (base58, 32-byte) address.
+// A truthy meta.solana_address that does not parse is treated as missing so the
+// wallet is re-provisioned rather than handed downstream to crash a PublicKey().
+async function isValidSolanaAddress(address) {
+ if (typeof address !== 'string' || address.length < 32 || address.length > 44) return false;
+ if (!/^[1-9A-HJ-NP-Za-km-z]+$/.test(address)) return false;
+ try {
+ const { PublicKey } = await import('@solana/web3.js');
+ // Constructing throws on a malformed (non-32-byte) base58 string.
+ // eslint-disable-next-line no-new
+ new PublicKey(address);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Idempotently guarantee an agent has a usable custodial Solana wallet.
+ *
+ * This is THE single entry point every wallet-touching endpoint (deposit, trade,
+ * x402 pay, withdraw) must call before assuming `meta.solana_address` /
+ * `meta.encrypted_solana_secret` exist. It:
+ * 1. loads the agent row,
+ * 2. returns the existing wallet if both the address is a valid Solana key and
+ * a recoverable encrypted secret is present ({ created: false }),
+ * 3. otherwise generates + persists a fresh keypair via the canonical
+ * generateSolanaAgentWallet() and audit-logs the lazy provision
+ * ({ created: true }).
+ *
+ * A row whose address fails to parse, or whose secret is missing, is repaired —
+ * never handed downstream to throw inside a PublicKey() / signing call. The
+ * secret never leaves the server and is never returned, logged, or put in an
+ * error message.
+ *
+ * @param {string} agentId
+ * @param {string|null} [userId] — owner, for the audit trail (optional)
+ * @param {{ reason?: string }} [opts]
+ * @returns {Promise<{ address: string, created: boolean }>}
+ */
+export async function ensureAgentWallet(agentId, userId = null, opts = {}) {
+ if (!agentId) throw new Error('agentId required');
+ const { sql } = await import('./db.js');
+ const [row] = await sql`
+ select id, user_id, meta from agent_identities
+ where id = ${agentId} and deleted_at is null
+ limit 1
+ `;
+ if (!row) throw new Error('agent not found');
+
+ const meta = { ...(row.meta || {}) };
+ const hasValidAddress = await isValidSolanaAddress(meta.solana_address);
+ const hasSecret = typeof meta.encrypted_solana_secret === 'string' && meta.encrypted_solana_secret.length > 0;
+ if (hasValidAddress && hasSecret) {
+ return { address: meta.solana_address, created: false };
+ }
+
+ const sol = await generateSolanaAgentWallet();
+ const nextMeta = {
+ ...meta,
+ solana_address: sol.address,
+ encrypted_solana_secret: sol.encrypted_secret,
+ solana_wallet_source: meta.solana_wallet_source || 'lazy_provision',
+ };
+ await sql`update agent_identities set meta = ${JSON.stringify(nextMeta)}::jsonb where id = ${agentId}`;
+
+ // Audit the lazy provision: custodial keys are real funds, every mint must be
+ // traceable. Fire-and-forget — telemetry must never block the wallet path.
+ // The address is public; the secret is never recorded.
+ try {
+ const { recordEvent } = await import('./usage.js');
+ recordEvent({
+ userId: userId ?? row.user_id ?? null,
+ agentId,
+ kind: 'solana_wallet_provision',
+ tool: opts.reason || 'ensure',
+ status: 'ok',
+ meta: { address: sol.address, source: 'lazy_provision', repaired: hasValidAddress !== hasSecret },
+ });
+ } catch {
+ /* audit best-effort */
+ }
+ return { address: sol.address, created: true };
+}
+
/**
* Recover a Solana Keypair from its encrypted form.
* Only call this when the agent needs to sign a transaction.
diff --git a/api/_lib/migrations/20260617000000_agent_custody.sql b/api/_lib/migrations/20260617000000_agent_custody.sql
new file mode 100644
index 000000000..8afe11829
--- /dev/null
+++ b/api/_lib/migrations/20260617000000_agent_custody.sql
@@ -0,0 +1,62 @@
+begin;
+
+-- Custody audit trail + spend ledger for agent custodial wallets.
+--
+-- Agent Solana wallets are custodial: the platform holds the AES-GCM-encrypted
+-- secret and signs server-side. This table is the single, owner-viewable record
+-- of everything sensitive that happens to those funds:
+-- - 'key_recover' the encrypted secret was decrypted to sign (with a reason)
+-- - 'withdraw' the owner swept SOL/SPL out to an address
+-- - 'spend' an outbound payment from an automated path
+-- (category: 'trade' | 'snipe' | 'x402' | 'withdraw')
+-- - 'limit_change' the owner edited the per-agent spend policy
+--
+-- It doubles as the spend ledger: the shared guardrail in
+-- api/_lib/agent-trade-guards.js sums `usd` over the last 24h of 'spend' rows to
+-- enforce the per-agent daily ceiling uniformly across every outbound path.
+-- Spend limits themselves live in agent_identities.meta.spend_limits (jsonb) —
+-- this table is the audit/accounting side, not the config side.
+create table if not exists agent_custody_events (
+ id bigserial primary key,
+ agent_id uuid not null,
+ user_id uuid, -- actor / owner (null when system)
+ event_type text not null, -- key_recover | withdraw | spend | limit_change
+ category text, -- spend path: trade | snipe | x402 | withdraw
+ network text not null default 'mainnet',
+ asset text, -- 'SOL' | mint base58 | 'USDC'
+ amount_lamports bigint, -- SOL amount (lamports)
+ amount_raw numeric, -- SPL token base units
+ usd numeric, -- normalized USD value (null when unpriceable)
+ destination text, -- withdraw recipient (base58)
+ signature text, -- on-chain tx signature
+ reason text, -- key_recover reason / freeform note
+ status text not null default 'ok', -- ok | pending | confirmed | failed
+ idempotency_key text, -- client-supplied; dedupes withdraw retries
+ meta jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+-- Idempotency: one row per (agent, idempotency_key). A withdraw retry with the
+-- same key reuses the claimed row instead of broadcasting a second transaction.
+create unique index if not exists agent_custody_events_idem
+ on agent_custody_events (agent_id, idempotency_key)
+ where idempotency_key is not null;
+
+-- The owner-facing audit feed reads newest-first per agent.
+create index if not exists agent_custody_events_agent_time
+ on agent_custody_events (agent_id, created_at desc);
+
+-- The daily-spend ceiling query sums recent 'spend' rows per agent+network.
+create index if not exists agent_custody_events_spend
+ on agent_custody_events (agent_id, network, created_at)
+ where event_type = 'spend';
+
+comment on table agent_custody_events is
+ 'Per-agent custody audit trail + spend ledger for custodial Solana wallets. '
+ 'Owner-viewable via GET /api/agents/:id/solana/custody. Spend rows back the '
+ 'daily ceiling enforced by api/_lib/agent-trade-guards.js across '
+ 'trade/snipe/x402/withdraw. Spend limits config lives in '
+ 'agent_identities.meta.spend_limits, not here.';
+
+commit;
diff --git a/api/_lib/migrations/20260617000000_agent_wallet_backfill.sql b/api/_lib/migrations/20260617000000_agent_wallet_backfill.sql
new file mode 100644
index 000000000..d81542816
--- /dev/null
+++ b/api/_lib/migrations/20260617000000_agent_wallet_backfill.sql
@@ -0,0 +1,38 @@
+-- Migration: guarantee every agent identity has a custodial Solana wallet.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260617000000_agent_wallet_backfill.sql
+-- Idempotent.
+--
+-- Every agent created via POST /api/agents (and the first-login default-agent
+-- bootstrap) auto-provisions a real Solana keypair, encrypts the secret, and
+-- stores it in agent_identities.meta.encrypted_solana_secret (+ the public
+-- meta.solana_address). Agents created before that behavior shipped — or via any
+-- path that skipped it — can be missing the wallet, which breaks the deposit /
+-- trade / x402 / withdraw surfaces that assume meta.solana_address exists.
+--
+-- Key generation is JavaScript (Ed25519 keypair + AES-256-GCM secret encryption),
+-- not SQL, so the actual provision runs in the paired Node backfill:
+--
+-- node scripts/backfill-agent-wallets.mjs # report only
+-- node scripts/backfill-agent-wallets.mjs --apply # provision via ensureAgentWallet()
+--
+-- That script calls ensureAgentWallet() — the same canonical custody path the
+-- request handlers use — so the backfill can never diverge from live behavior.
+-- It is idempotent (skips rows that already have a valid wallet) and re-runnable.
+--
+-- This SQL file exists so the change is tracked in schema_migrations alongside
+-- the runner and so the backfill state is observable. It only adds a partial
+-- index that makes "agents still missing a wallet" a constant-time lookup for
+-- the backfill query, monitoring, and a post-deploy verification that zero rows
+-- remain. It writes no keys.
+
+begin;
+
+-- Fast scan for agents that still need a custodial wallet (drives the backfill
+-- query and the "zero remaining" verification). Partial so it only indexes the
+-- shrinking set of un-provisioned rows.
+create index if not exists agent_identities_missing_solana
+ on agent_identities (created_at)
+ where deleted_at is null
+ and (meta is null or meta->>'solana_address' is null or meta->>'solana_address' = '');
+
+commit;
diff --git a/api/agents.js b/api/agents.js
index ef1b5f6af..334093b49 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -624,9 +624,27 @@ function requireScopeForMutation(auth, res, requiredScope) {
return null;
}
+// A base58 string in the 32–44 char range is a syntactically valid Solana
+// pubkey. Cheap structural check (no @solana/web3.js import on the hot GET path)
+// — the canonical strict parse lives in ensureAgentWallet().
+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
function decorate(row, isOwner = true) {
// Strip encrypted secrets from meta — never expose to the client.
const meta = { ...(row.meta || {}) };
+ // `walletReady` is computed from the secret BEFORE it is stripped: an agent
+ // is wallet-ready only when it has both a valid public address and a
+ // recoverable (encrypted) signing key. The UI gates "preparing wallet…" vs
+ // the live hub on this; the secret itself is never emitted.
+ const solanaAddress =
+ typeof meta.solana_address === 'string' && SOLANA_ADDRESS_RE.test(meta.solana_address)
+ ? meta.solana_address
+ : null;
+ const walletReady = Boolean(
+ solanaAddress &&
+ typeof meta.encrypted_solana_secret === 'string' &&
+ meta.encrypted_solana_secret.length > 0,
+ );
delete meta.encrypted_wallet_key;
delete meta.encrypted_solana_secret;
@@ -676,6 +694,14 @@ function decorate(row, isOwner = true) {
onchain,
token,
payments,
+ // Public on-chain identity: the agent's Solana receive address (the same
+ // value GET /api/agents/:id/solana serves anonymously) plus whether a
+ // signing wallet is fully provisioned. Lets any surface render the wallet
+ // hub (deposit is read-only-safe) without a second round-trip. The secret
+ // is never exposed — only this public address + the readiness boolean.
+ solana_address: solanaAddress,
+ wallet_ready: walletReady,
+ walletReady,
is_registered: Boolean(row.erc8004_agent_id) || !!onchain,
// Whether the requesting session owns this agent. Owner-only write paths
// (action log, memory sync) gate on this so public viewers don't fire
diff --git a/api/irl/pins.js b/api/irl/pins.js
index 07e5f3b16..0bdf903d6 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -9,6 +9,7 @@
* 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)
+ * DELETE /api/irl/pins?all=1&deviceToken= purge every pin from this device → { deleted }
* POST /api/irl/pins/interact { pinId, event, deviceToken } log a tap/view
*/
@@ -73,27 +74,55 @@ function contentReject(caption, name) {
// Tier-2 AI content risk over the free-text caption — Granite Guardian. Best-
// effort by design (Rule 9): when watsonx isn't configured, or the classifier
// errors/times out, we DON'T block — the always-on wordlist already caught the
-// hard cases, and a missing key must never 500 a placement. Bounded to 4s so a
-// slow upstream can't stall the POST.
+// hard cases, and a missing key must never 500 a placement.
+//
+// Resilience (task 12): a dead moderation upstream would otherwise cost EVERY
+// placement its full timeout. Once a check fails, we cache the "degraded" state
+// for ~60s and skip the upstream entirely during that window — so one failure
+// doesn't make the next minute of placements each wait the timeout. The per-
+// request timeout is tight (2s) so even the first failure after recovery can't
+// stall the POST. Both failure modes fail OPEN (allow the placement) with a log.
+const GUARDIAN_TIMEOUT_MS = 2000; // tight per-request bound on the upstream
+const GUARDIAN_DEGRADE_MS = 60_000; // skip-upstream window after a failure
+let _guardianDegradedUntil = 0; // epoch-ms; >now ⇒ short-circuit to allow
+
+// Exposed for tests + the cron-style recovery path: report whether the Guardian
+// short-circuit is currently engaged, and clear it (e.g. after a probe succeeds).
+export function guardianDegraded(now = Date.now()) {
+ return _guardianDegradedUntil > now;
+}
+export function resetGuardianDegraded() {
+ _guardianDegradedUntil = 0;
+}
+
async function guardianFlags(caption) {
const text = String(caption || '').trim();
if (!text) return false;
const cfg = guardianConfig();
if (!cfg.configured) return false;
+ // Short-circuit while the upstream is known-degraded: no network call, so the
+ // caption is allowed immediately rather than paying the timeout again.
+ if (guardianDegraded()) return false;
try {
const ctrl = new AbortController();
- const timer = setTimeout(() => ctrl.abort(), 4000);
+ const timer = setTimeout(() => ctrl.abort(), GUARDIAN_TIMEOUT_MS);
try {
const verdicts = await assess(cfg, {
input: text,
risks: ['harm', 'social_bias', 'violence', 'sexual_content'],
signal: ctrl.signal,
});
+ // A clean pass clears any lingering degraded window — the upstream is back.
+ _guardianDegradedUntil = 0;
return decide(verdicts).decision === 'block';
} finally {
clearTimeout(timer);
}
} catch (err) {
+ // Open the degraded window so the next ~60s of placements skip the upstream
+ // instead of each eating the timeout. Fail open (allow) — the hard wordlist
+ // already ran, and a moderation outage must never 500 or stall a placement.
+ _guardianDegradedUntil = Date.now() + GUARDIAN_DEGRADE_MS;
console.warn('[irl/pins] guardian content check degraded:', err?.message || err);
return false;
}
@@ -106,12 +135,38 @@ async function guardianFlags(caption) {
// IRL_X402_ALLOWED_HOSTS). Relative same-origin paths are always first-party.
// Registered-agent endpoints still flow to the Pay button via the trusted
// server-resolved agent-card path (card.x402_endpoint), which this never gates.
-const X402_ALLOWED_HOSTS = (
- process.env.IRL_X402_ALLOWED_HOSTS || 'three.ws,www.three.ws,3d-agent.vercel.app,3d.irish'
-)
- .split(',')
- .map((h) => h.trim().toLowerCase())
- .filter(Boolean);
+// Built-in first-party hosts — the floor under any operator override. The
+// allow-list is NEVER empty: an unset/blank/malformed IRL_X402_ALLOWED_HOSTS
+// falls back to these defaults rather than producing an empty list (which would
+// reject every absolute endpoint — fail-safe, but it would also silently break
+// every legit first-party pay target). A valid host token is a bare hostname
+// (letters/digits/dots/hyphens, no scheme/path/port), so a fat-fingered
+// "https://x" entry is dropped instead of poisoning the match.
+const X402_DEFAULT_HOSTS = ['three.ws', 'www.three.ws', '3d-agent.vercel.app', '3d.irish'];
+const X402_HOST_RE = /^[a-z0-9.-]+$/;
+
+// Parse + validate the configured allow-list. Returns ONLY well-formed bare
+// hostnames; when an operator override is set but yields no valid host, we log
+// once and fall back to the built-in first-party hosts so a misconfig can never
+// silently disable first-party pay targets nor accept an external one.
+function parseAllowedHosts(raw) {
+ const configured = String(raw ?? '').trim();
+ const parsed = configured
+ .split(',')
+ .map((h) => h.trim().toLowerCase())
+ .filter((h) => h && X402_HOST_RE.test(h));
+ if (configured && !parsed.length) {
+ console.warn(
+ '[irl/pins] IRL_X402_ALLOWED_HOSTS is set but parsed to no valid host; ' +
+ 'falling back to built-in first-party hosts. External x402 endpoints ' +
+ 'are only accepted for first-party / allow-listed hosts.',
+ );
+ }
+ // Always return a non-empty set: configured-valid hosts, else the defaults.
+ return parsed.length ? parsed : X402_DEFAULT_HOSTS.slice();
+}
+
+const X402_ALLOWED_HOSTS = parseAllowedHosts(process.env.IRL_X402_ALLOWED_HOSTS);
export function safePaymentEndpoint(raw) {
// allowRelative so a same-origin path (unambiguously first-party three.ws)
@@ -122,6 +177,9 @@ export function safePaymentEndpoint(raw) {
if (base.value.startsWith('/')) return { ok: true, value: base.value };
let host;
try { host = new URL(base.value).hostname.toLowerCase(); } catch { return { ok: false }; }
+ // Empty allow-list (defensive — parseAllowedHosts never returns one) must
+ // reject every absolute host: fail safe, never silently accept an external one.
+ if (!X402_ALLOWED_HOSTS.length) return { ok: false };
const allowed = X402_ALLOWED_HOSTS.some((h) => host === h || host.endsWith(`.${h}`));
return allowed ? { ok: true, value: base.value } : { ok: false };
}
@@ -179,6 +237,31 @@ function haversineDist(lat1, lng1, lat2, lng2) {
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
+// Rate-limit calls fail OPEN here (task 12). The shared limiter already degrades
+// internally for these non-critical buckets, but a Redis client can still reject
+// (or the limiter object can throw synchronously) — and an unhandled rejection
+// inside the handler would 500 the whole request. These write paths are bounded
+// by the DB caps (density / per-owner / report dedupe) downstream, so a limiter
+// outage should never block a legitimate placement: we log once and allow.
+// `name` ties the warning to the bucket; the cooldown keeps an outage that hits
+// every request from itself flooding the logs.
+const _rlWarnedAt = new Map();
+const RL_WARN_COOLDOWN_MS = 60_000;
+async function limitOrFailOpen(name, fn, ...args) {
+ try {
+ return await fn(...args);
+ } catch (err) {
+ const last = _rlWarnedAt.get(name) || 0;
+ const now = Date.now();
+ if (now - last >= RL_WARN_COOLDOWN_MS) {
+ _rlWarnedAt.set(name, now);
+ console.warn(`[irl/pins] rate limiter "${name}" failed, allowing request (fail-open):`, err?.message || err);
+ }
+ // Allow: a synthetic success verdict so the caller proceeds unthrottled.
+ return { success: true, reason: 'rate_limiter_degraded' };
+ }
+}
+
let _tableReady = false;
async function ensureTable() {
if (_tableReady) return;
@@ -268,6 +351,16 @@ const CAL_MAX_RISE_M = 3; // floor-height nudge ceiling, metres
const ROOM_ID_RE = /^[a-z0-9-]{1,64}$/;
const REL_MAX_M = 500;
+// Pin ids are server-minted UUIDs (gen_random_uuid()). Validate the format at the
+// top of every mutation path so an oversized / garbage id is a clean 400 and never
+// reaches the DB query or a log line. The SQL is already parameterized (this is
+// not the injection guard) — it's input hygiene + defense in depth, and it lets a
+// "not a pin id" request fail fast with a clear message instead of a confusing 404.
+const PIN_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+export function isValidPinId(id) {
+ return typeof id === 'string' && PIN_ID_RE.test(id);
+}
+
// Smallest signed distance between two compass bearings, 0–180°.
function circularYawDelta(a, b) {
let d = ((a - b) % 360 + 360) % 360;
@@ -275,6 +368,19 @@ function circularYawDelta(a, b) {
return Math.abs(d);
}
+// A pin is gone from the public world once it has expired (anonymous pins lapse
+// after 7 days) or been moderation-hidden. Owner-gated mutations (calibrate /
+// outfit / delete) must refuse to touch such a row — re-saving a pose or re-skin
+// onto a pin no nearby viewer can see is a silent no-op the owner would mistake
+// for success (task 13). `expires_at` NULL = a permanent (signed-in) pin.
+export function isExpiredOrHidden(pin, now = Date.now()) {
+ if (!pin) return false;
+ if (pin.hidden_at != null) return true;
+ if (pin.expires_at == null) return false;
+ const t = new Date(pin.expires_at).getTime();
+ return Number.isFinite(t) && t <= now;
+}
+
// 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
@@ -283,7 +389,8 @@ 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
+ SELECT id, user_id, device_token, lat, lng, heading, anchor_yaw_deg, anchor_height_m,
+ expires_at, hidden_at
FROM irl_pins
WHERE id = ${id}
`;
@@ -296,6 +403,10 @@ async function handleCalibrate(res, { id, session, body }) {
(!!pin.device_token && !!body.deviceToken && pin.device_token === body.deviceToken);
if (!owns) return json(res, 403, { error: 'only the owner can calibrate this agent' });
+ // An expired / moderation-hidden pin is gone from the public world — refuse to
+ // mutate it rather than re-saving a pose nobody will ever see (task 13).
+ if (isExpiredOrHidden(pin)) return json(res, 404, { error: 'not found' });
+
// New ground position — required, validated, range-checked.
const newLat = parseFloat(cal.lat);
const newLng = parseFloat(cal.lng);
@@ -339,8 +450,13 @@ async function handleCalibrate(res, { id, session, body }) {
heading = COALESCE(${headingToStore}, heading),
anchor_height_m = COALESCE(${newHeight}, anchor_height_m)
WHERE id = ${id}
+ AND hidden_at IS NULL
+ AND (expires_at IS NULL OR expires_at > NOW())
RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, gps_accuracy_m
`;
+ // A lapse between the SELECT above and this write (e.g. expiry / a reaping cron)
+ // leaves no row — surface that as not-found instead of returning { pin: null }.
+ if (!row) return json(res, 404, { error: 'not found' });
// The corrected spot reaches nearby viewers on their next proximity poll — pin
// positions are never broadcast as a roster, only read by someone standing near it.
return json(res, 200, { pin: row, calibrated: true });
@@ -370,7 +486,7 @@ async function handleOutfitChange(res, { id, session, body }) {
// is never editable from an anonymous device token — same stance as the
// avatar/location edits below.)
const [pin] = await sql`
- SELECT id, user_id, avatar_url, avatar_base_url, avatar_version
+ SELECT id, user_id, avatar_url, avatar_base_url, avatar_version, expires_at, hidden_at
FROM irl_pins
WHERE id = ${id}
`;
@@ -378,6 +494,9 @@ async function handleOutfitChange(res, { id, session, body }) {
if (!pin.user_id || pin.user_id !== session.id) {
return json(res, 403, { error: "only the owner can change this agent's outfit" });
}
+ // An expired / moderation-hidden pin is gone from the public world — refuse to
+ // burn a bake re-skinning a row no nearby viewer can see (task 13).
+ if (isExpiredOrHidden(pin)) return json(res, 404, { error: 'not found' });
// The base GLB the manifest dresses. Captured once (the agent as it looked
// before any outfit edit) so re-bakes always start from a clean model.
@@ -396,8 +515,11 @@ async function handleOutfitChange(res, { id, session, body }) {
}
// else: cleared / empty manifest → serve the bare base GLB again.
} catch (err) {
+ // Log the full detail server-side; NEVER echo err.message to the client — a
+ // bake/upstream error can carry filesystem paths, R2/CDN URLs, or libvips
+ // internals. The client gets a generic, actionable message only (task 13).
console.error('[irl/pins] outfit bake failed', { pinId: id, message: err?.message });
- return json(res, 502, { error: 'could not bake the new outfit', detail: err?.message });
+ return json(res, 502, { error: 'could not bake the new outfit' });
}
const [row] = await sql`
@@ -407,6 +529,8 @@ async function handleOutfitChange(res, { id, session, body }) {
avatar_url = ${newAvatarUrl},
avatar_version = avatar_version + 1
WHERE id = ${id} AND user_id = ${session.id}
+ AND hidden_at IS NULL
+ AND (expires_at IS NULL OR expires_at > NOW())
RETURNING id, lat, lng, avatar_url, avatar_manifest, avatar_version
`;
if (!row) return json(res, 404, { error: 'not found' });
@@ -428,7 +552,7 @@ export default wrap(async (req, res) => {
// scrape. A legit viewer polls nearby every ~10 s (≈6/min) — well under the
// 60/min public ceiling — while a scripted sweep trips it fast.
if (req.method === 'GET') {
- const rl = await limits.publicIp(clientIp(req));
+ const rl = await limitOrFailOpen('publicIp', limits.publicIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
}
@@ -496,7 +620,15 @@ export default wrap(async (req, res) => {
// Tight proximity gate: default 40 m, hard-capped at 60 m. Large enough to
// render an agent as you walk up and point your camera at its spot, small
// enough that one read only ever exposes the handful right where you stand.
- const radius = Math.min(60, Math.max(10, parseFloat(req.query.radius ?? '40')));
+ // A missing radius defaults to 40; a PRESENT but non-finite radius (e.g.
+ // ?radius=abc) is rejected — clamping NaN would silently yield NaN deltas and
+ // an always-empty feed, masking a malformed request behind a 200.
+ const rawRadius = req.query.radius;
+ const parsedRadius = rawRadius == null || rawRadius === '' ? 40 : parseFloat(rawRadius);
+ if (!Number.isFinite(parsedRadius)) {
+ return json(res, 400, { error: 'invalid radius' });
+ }
+ const radius = Math.min(60, Math.max(10, parsedRadius));
if (!isFinite(lat) || !isFinite(lng)) {
return json(res, 400, { error: 'lat and lng are required' });
@@ -583,7 +715,7 @@ export default wrap(async (req, res) => {
// carries a designed error code the client renders as an actionable message.
if (req.method === 'POST') {
const ip = clientIp(req);
- const rl = await limits.irlPinIp(ip);
+ const rl = await limitOrFailOpen('irlPinIp', limits.irlPinIp, ip);
if (!rl.success) return rateLimited(res, rl);
const body = req.body ?? {};
@@ -643,8 +775,8 @@ export default wrap(async (req, res) => {
// Redis outage (non-critical) so an infra hiccup never blocks a real placement.
const rateKey = `${deviceToken ?? userId ?? 'anon'}:${ip}`;
const [burst, hourly] = await Promise.all([
- limits.irlPinBurst(rateKey),
- limits.irlPinHourly(rateKey),
+ limitOrFailOpen('irlPinBurst', limits.irlPinBurst, rateKey),
+ limitOrFailOpen('irlPinHourly', limits.irlPinHourly, rateKey),
]);
const throttled = !burst.success ? burst : !hourly.success ? hourly : null;
if (throttled) {
@@ -784,7 +916,7 @@ 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));
+ const rl = await limitOrFailOpen('irlPinIp', limits.irlPinIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const session = await getSessionUser(req).catch(() => null);
@@ -875,13 +1007,33 @@ export default wrap(async (req, res) => {
// ── DELETE — remove own pin ───────────────────────────────────────────────
if (req.method === 'DELETE') {
- const rl = await limits.irlPinIp(clientIp(req));
+ const rl = await limitOrFailOpen('irlPinIp', limits.irlPinIp, clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const id = req.query.id;
const deviceToken = req.query.deviceToken ?? req.body?.deviceToken;
+ const purgeAll = req.query.all === '1' || req.query.all === 'true';
+
+ // ── Bulk purge — every pin from this device token, in one round-trip ──────
+ // Strictly scoped to a non-empty device token: the `IS NOT NULL` guard means
+ // a NULL/empty token matches nothing, so this can only ever delete the
+ // caller's own anonymous pins — never another device's, never a NULL-token
+ // row. Auth-only callers manage their permanent pins from the dashboard, so
+ // this branch requires a device token.
+ if (purgeAll) {
+ if (!deviceToken) return json(res, 400, { error: 'deviceToken required for bulk delete' });
+ const rows = await sql`
+ DELETE FROM irl_pins
+ WHERE device_token IS NOT NULL AND device_token = ${deviceToken}
+ RETURNING id
+ `;
+ return json(res, 200, { ok: true, deleted: rows.length });
+ }
if (!id) return json(res, 400, { error: 'id required' });
+ // A delete id is a server-minted UUID — reject a malformed one before it
+ // reaches the query or a log line.
+ if (!isValidPinId(id)) return json(res, 400, { error: 'invalid pin id' });
const session = await getSessionUser(req).catch(() => null);
const userId = session?.id ?? null;
@@ -899,6 +1051,7 @@ export default wrap(async (req, res) => {
const result = await sql`
DELETE FROM irl_pins
WHERE id = ${id}
+ AND (expires_at IS NULL OR expires_at > NOW())
AND (
(${userId}::uuid IS NOT NULL AND user_id = ${userId}::uuid)
OR (device_token IS NOT NULL AND device_token = ${deviceToken ?? ''})
diff --git a/data/changelog.json b/data/changelog.json
index bcd495318..15d859adf 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$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": "Sniper dashboard: your live positions now show real-time profit and loss and reconnect on their own",
+ "summary": "The Sniper Strategies dashboard now streams your agents' open positions with live unrealized profit and loss — both the SOL figure and the percentage — instead of a blank value, and fills them in the moment the page loads rather than waiting for the next trade to land. The live feed shows its own connection state (Live / Reconnecting) and re-establishes itself automatically with backoff if it drops, so you always know whether you're watching real-time data. Closed-trade history now calls out your single best and worst trade, and there are one-tap links to the public leaderboard and sniper arena so your track record is easy to share.",
+ "tags": ["feature"],
+ "link": "/dashboard/sniper"
+ },
{
"date": "2026-06-17",
"title": "Agent profiles now show the agent's real avatar — no more stray model over the name",
diff --git a/pages/ibm/HOSTING.md b/pages/ibm/HOSTING.md
new file mode 100644
index 000000000..946b86089
--- /dev/null
+++ b/pages/ibm/HOSTING.md
@@ -0,0 +1,107 @@
+# Hosting the x402 live demo on `live.ibm.com`
+
+`x402-demo.html` is a self-contained page that demonstrates the x402 micropayment
+protocol: a visitor pays **$0.001 USDC** from their own wallet to call a real three.ws data
+API, settled on-chain on Base or Solana. This guide is everything the IBM web team needs to
+host it.
+
+## What it demonstrates (one paragraph)
+
+x402 reactivates the dormant HTTP `402 Payment Required` status as a payment rail. A normal
+request to a paid endpoint returns `402` with machine-readable terms (amount, asset, network,
+recipient). The visitor's wallet signs a gasless stablecoin authorization, the request is
+retried with an `X-PAYMENT` header, and the call settles on-chain in about a second — no API
+key, no account, no invoice. The page shows the live `402` challenge, runs a real paid call,
+and renders the response plus the on-chain transaction receipt.
+
+## What to upload
+
+Copy these to the same directory on the host (paths are relative, so they must stay together):
+
+```
+x402-demo.html
+fonts/
+ IBMPlexSans-300.woff2
+ IBMPlexSans-400.woff2
+ IBMPlexSans-500.woff2
+ IBMPlexSans-600.woff2
+ IBMPlexMono-400.woff2
+ IBMPlexMono-500.woff2
+```
+
+Everything else (the payment widget, the API, the explorer links) is loaded at runtime from
+`https://three.ws` and the public chain explorers. There is **no build step** and **no
+backend** to deploy. IBM Plex is self-hosted from `fonts/` so the page needs no third-party
+font CDN.
+
+## Content-Security-Policy
+
+The page runs under **the host's CSP**. Pick one tier. (If `live.ibm.com` sends no CSP, the
+page works as-is; these are for hardened hosts.)
+
+### Tier 1 — Strict (Base / MetaMask only, recommended default)
+
+The Base payment path signs entirely in-browser; its only network dependencies are the
+three.ws widget and the three.ws API. Nothing loads from a third-party CDN.
+
+```
+Content-Security-Policy:
+ default-src 'none';
+ script-src 'self' https://three.ws 'unsafe-inline';
+ connect-src https://three.ws;
+ style-src 'self' 'unsafe-inline';
+ font-src 'self';
+ img-src 'self' data:;
+ base-uri 'self';
+```
+
+Under this policy the Solana button will fail gracefully (its dependencies are blocked) while
+the Base button works fully.
+
+> `'unsafe-inline'` covers the page's inline `<style>` and the small inline bootstrap
+> `<script>`. If IBM requires nonces, add a per-response nonce to the inline `<style>` and
+> `<script>` tags instead of `'unsafe-inline'`.
+
+### Tier 2 — Full (Base + Solana / Phantom)
+
+The Solana path dynamic-imports `@solana/web3.js` from `esm.sh` and calls a three.ws helper.
+Add those origins:
+
+```
+Content-Security-Policy:
+ default-src 'none';
+ script-src 'self' https://three.ws https://esm.sh 'unsafe-inline';
+ connect-src https://three.ws https://esm.sh;
+ style-src 'self' 'unsafe-inline';
+ font-src 'self';
+ img-src 'self' data:;
+ base-uri 'self';
+```
+
+## Visitor requirements
+
+- A browser wallet: **MetaMask** (Base) or **Phantom** (Solana).
+- At least **$0.001 USDC on mainnet** in that wallet. The payment is a gasless signature; the
+ network fee is sponsored by the x402 facilitator, so the visitor only spends the tenth of a
+ cent.
+- On mobile, wallets inject only inside their own in-app browser — the page tells visitors to
+ open it there. Without a wallet, the page still shows the live `402` challenge (read-only).
+
+## Top-level page vs. iframe
+
+Host it as a **top-level page** for best results: browser wallet extensions inject reliably
+into top-level documents, and the payment modal has full screen real estate. It can be
+embedded in an `<iframe>`, but some browsers restrict wallet-extension injection into
+cross-origin iframes — if you must iframe it, test the wallet flow in your target browsers
+first, or link out to the standalone page.
+
+## Cross-origin (already handled)
+
+three.ws serves the API and widget with `Access-Control-Allow-Origin: *` and exposes the x402
+payment headers, so calls from `live.ibm.com` work cross-origin with no extra configuration on
+either side.
+
+## Note on branding
+
+The page uses a neutral "IBM · Business Partner" wordmark lockup. Confirm the exact mark and
+partnership wording against IBM brand guidelines before public launch.
diff --git a/pages/irl.html b/pages/irl.html
index 53bf0b673..352773666 100644
--- a/pages/irl.html
+++ b/pages/irl.html
@@ -983,9 +983,62 @@
.irl-pin-meta { font-size: 11.5px; color: #6b7280; margin-top: 3px; }
.irl-pin-del { flex-shrink: 0; padding: 6px 8px; border-radius: 8px; border: 1px solid rgba(248,113,113,0.2); background: rgba(248,113,113,0.08); color: #f87171; font: 600 12px inherit; cursor: pointer; transition: background 0.15s; white-space: nowrap; }
.irl-pin-del:hover { background: rgba(248,113,113,0.18); }
+ .irl-pin-del:focus-visible { outline: 2px solid var(--danger); outline-offset: 2px; }
.irl-mypins-empty { font-size: 14px; color: #6b7280; text-align: center; padding: 18px 0; }
#irl-mypins-btn { display: none; }
+ /* Expiry chip in the meta line — countdown for anonymous pins, "permanent"
+ for signed-in ones. Near-expiry (≤24h) shifts amber to draw the eye. */
+ .irl-pin-exp { color: #6b7280; }
+ .irl-pin-exp.is-soon { color: #fbbf24; }
+ .irl-pin-exp.is-perm { color: #6b7280; }
+
+ /* Owned-pins overview map — a lazy Leaflet map above the list. Hidden until
+ markers are plotted; degrades to display:none on any CDN failure so the
+ list alone remains the source of truth. */
+ .irl-mypins-map { display: none; height: 168px; margin-bottom: 14px; border-radius: 12px; overflow: hidden; border: 1px solid rgba(255,255,255,0.10); background: rgba(8,10,16,0.6); position: relative; }
+ .irl-mypins-map.is-shown { display: block; }
+ .irl-mypins-map .irl-mypins-map-skel { position: absolute; inset: 0; background:
+ linear-gradient(100deg, rgba(255,255,255,0.03) 30%, rgba(255,255,255,0.08) 50%, rgba(255,255,255,0.03) 70%) 0 0 / 200% 100%;
+ animation: irl-mypins-shimmer 1.5s ease-in-out infinite; }
+ @keyframes irl-mypins-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) { .irl-mypins-map .irl-mypins-map-skel { animation: none; } }
+ /* Leaflet dark-theme touch-ups (zoom + attribution), scoped to this map */
+ .irl-mypins-map .leaflet-control-zoom a { background: rgba(18,20,28,0.92); color: #cbd5e1; border-color: rgba(255,255,255,0.12); }
+ .irl-mypins-map .leaflet-control-zoom a:hover { background: rgba(30,33,44,0.95); }
+ .irl-mypins-map .leaflet-bar { border-color: rgba(255,255,255,0.12); box-shadow: 0 1px 5px rgba(0,0,0,.5); }
+ .irl-mypins-map .leaflet-control-attribution { background: rgba(8,10,16,0.7); color: #99a; font-size: 10px; }
+ .irl-mypins-map .leaflet-control-attribution a { color: #9cf; }
+ .irl-mypins-map .leaflet-marker-icon.irl-mypins-pin { background: none; border: none; }
+ /* Gold dot marker — matches the "your agent" gold used on nearby labels */
+ .irl-mypins-marker { width: 14px; height: 14px; border-radius: 50%; background: #fbbf24; border: 2px solid rgba(12,14,20,0.9); box-shadow: 0 0 0 2px rgba(251,191,36,0.45), 0 0 10px rgba(251,191,36,0.55); cursor: pointer; }
+ /* Row flash when its marker is tapped */
+ .irl-pin-row.is-highlight { animation: irl-pin-flash 1.6s ease-out; }
+ @keyframes irl-pin-flash {
+ 0% { background: rgba(251,191,36,0.22); }
+ 100% { background: transparent; }
+ }
+ @media (prefers-reduced-motion: reduce) { .irl-pin-row.is-highlight { animation: none; background: rgba(251,191,36,0.12); } }
+
+ /* Footer: "Remove all from this device" purge + its inline confirm */
+ .irl-mypins-foot { margin-top: 14px; padding-top: 14px; border-top: 1px solid rgba(255,255,255,0.07); }
+ .irl-mypins-purge { display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; padding: 11px 14px; border-radius: 11px; border: 1px solid rgba(248,113,113,0.28); background: rgba(248,113,113,0.10); color: #f87171; font: 600 13.5px inherit; cursor: pointer; transition: background 0.15s, border-color 0.15s; }
+ .irl-mypins-purge:hover { background: rgba(248,113,113,0.18); border-color: rgba(248,113,113,0.45); }
+ .irl-mypins-purge:active { transform: scale(0.99); }
+ .irl-mypins-purge:focus-visible { outline: 2px solid var(--danger); outline-offset: 2px; }
+ .irl-mypins-purge:disabled { opacity: 0.6; cursor: default; }
+ .irl-mypins-purge svg { width: 15px; height: 15px; flex-shrink: 0; }
+ .irl-mypins-confirm { border: 1px solid rgba(248,113,113,0.3); background: rgba(248,113,113,0.06); border-radius: 12px; padding: 14px; }
+ .irl-mypins-confirm-q { font-size: 13.5px; line-height: 1.5; color: #e5e7eb; margin: 0 0 12px; }
+ .irl-mypins-confirm-row { display: flex; gap: 10px; }
+ .irl-mypins-confirm-cancel, .irl-mypins-confirm-go { flex: 1; padding: 10px 14px; border-radius: 10px; font: 600 13.5px inherit; cursor: pointer; transition: background 0.15s, border-color 0.15s; }
+ .irl-mypins-confirm-cancel { border: 1px solid rgba(255,255,255,0.14); background: rgba(255,255,255,0.06); color: #e5e7eb; }
+ .irl-mypins-confirm-cancel:hover { background: rgba(255,255,255,0.12); }
+ .irl-mypins-confirm-go { border: 1px solid transparent; background: #ef4444; color: #fff; }
+ .irl-mypins-confirm-go:hover { background: #dc2626; }
+ .irl-mypins-confirm-go:disabled, .irl-mypins-confirm-cancel:disabled { opacity: 0.6; cursor: default; }
+ .irl-mypins-confirm-cancel:focus-visible, .irl-mypins-confirm-go:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
/* 3D→2D agent labels (injected by JS per nearby pin) */
.irl-agent-label {
position: fixed;
@@ -1607,6 +1660,10 @@
<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>
</button>
+ <button class="irl-pill-btn" id="irl-mapplace-btn" type="button" aria-label="Place this agent at a spot you choose on a map">
+ <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="M21 10c0 6-9 12-9 12s-9-6-9-12a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
+ Place on map
+ </button>
<button class="irl-pill-btn" id="irl-place-btn" type="button" aria-pressed="false">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
Add object
@@ -1698,7 +1755,9 @@
<h3>My pins</h3>
<button class="irl-sheet-close" id="irl-mypins-close" type="button" aria-label="Close">×</button>
</div>
+ <div id="irl-mypins-map" class="irl-mypins-map" role="group" aria-label="Map of pins you've placed"></div>
<div id="irl-mypins-list"><p class="irl-mypins-empty">Loading…</p></div>
+ <div id="irl-mypins-foot" class="irl-mypins-foot" hidden></div>
</div>
<!-- Radar minimap — visible in GPS pin mode only -->
diff --git a/public/changelog.json b/public/changelog.json
index 56a5c3708..0029ebdb6 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T11:11:16.259Z",
+ "generated_at": "2026-06-17T11:52:57.271Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -380,6 +380,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "Sniper dashboard: your live positions now show real-time profit and loss and reconnect on their own",
+ "summary": "The Sniper Strategies dashboard now streams your agents' open positions with live unrealized profit and loss — both the SOL figure and the percentage — instead of a blank value, and fills them in the moment the page loads rather than waiting for the next trade to land. The live feed shows its own connection state (Live / Reconnecting) and re-establishes itself automatically with backoff if it drops, so you always know whether you're watching real-time data. Closed-trade history now calls out your single best and worst trade, and there are one-tap links to the public leaderboard and sniper arena so your track record is easy to share.",
+ "link": "/dashboard/sniper",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index a778bc20f..ffe148f76 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -294,6 +294,14 @@
<category>feature</category>
<description>three.ws/xr now has the same one-tap Share that three.ws/irl has had: it flattens your live camera view and the 3D agent into a single photo and hands it to your phone's share sheet to post or send — or downloads it as a PNG on desktop. With the camera on, the picture shows your agent standing in your real surroundings; with it off, it shares the 3D view on its own. If a snapshot can't be captured for any reason, Share falls back to sending the page link so it's never a dead end. The Share buttons on both pages now show a brief progress state while the image is being made, and the immersive buttons give keyboard users a clear focus outline.</description>
</item>
+ <item>
+ <title>Sniper dashboard: your live positions now show real-time profit and loss and reconnect on their own</title>
+ <link>https://three.ws/dashboard/sniper</link>
+ <guid isPermaLink="false">2026-06-17:Sniper dashboard: your live positions now show real-time profit and loss and reconnect on their own</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The Sniper Strategies dashboard now streams your agents' open positions with live unrealized profit and loss — both the SOL figure and the percentage — instead of a blank value, and fills them in the moment the page loads rather than waiting for the next trade to land. The live feed shows its own connection state (Live / Reconnecting) and re-establishes itself automatically with backoff if it drops, so you always know whether you're watching real-time data. Closed-trade history now calls out your single best and worst trade, and there are one-tap links to the public leaderboard and sniper arena so your track record is easy to share.</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>
diff --git a/public/features.json b/public/features.json
index e10367a00..1a9acb432 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T11:11:16.197Z",
+ "generated_at": "2026-06-17T11:52:55.529Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/backfill-agent-wallets.mjs b/scripts/backfill-agent-wallets.mjs
new file mode 100644
index 000000000..292f686c3
--- /dev/null
+++ b/scripts/backfill-agent-wallets.mjs
@@ -0,0 +1,133 @@
+#!/usr/bin/env node
+/**
+ * Backfill custodial Solana wallets for EVERY agent identity that is missing a
+ * valid one — not just avatar-linked agents (that narrower case is covered by
+ * backfill-avatar-wallets.mjs). This is the paired runner for the migration
+ * api/_lib/migrations/20260617000000_agent_wallet_backfill.sql.
+ *
+ * It provisions through ensureAgentWallet() — the SAME canonical custody path
+ * the request handlers use — so the backfill can never diverge from live
+ * behavior. ensureAgentWallet() also REPAIRS rows whose address is present but
+ * malformed, or whose encrypted secret is missing, so the set this script leaves
+ * behind is genuinely "every agent resolvable to a valid Solana wallet".
+ *
+ * SAFE BY DEFAULT: report-only unless --apply is passed.
+ *
+ * Usage:
+ * node scripts/backfill-agent-wallets.mjs # report pending, no writes
+ * node scripts/backfill-agent-wallets.mjs --apply # provision via ensureAgentWallet()
+ * node scripts/backfill-agent-wallets.mjs --apply --limit 1000
+ *
+ * Idempotent and re-runnable: a second --apply run is a no-op once every row has
+ * a wallet. Secrets are never printed — only the public address.
+ */
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(__dirname, '..');
+
+// ── tiny .env loader (matches apply-migrations.mjs) ───────────────────────────
+for (const envFile of ['.env.local', '.env']) {
+ try {
+ const raw = fs.readFileSync(path.resolve(REPO_ROOT, envFile), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z_][A-Z0-9_]*)=(.*)$/i);
+ if (!m || process.env[m[1]]) continue;
+ let val = m[2].trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
+ process.env[m[1]] = val;
+ }
+ break;
+ } catch {
+ /* file not present */
+ }
+}
+
+const args = process.argv.slice(2);
+const APPLY = args.includes('--apply');
+const LIMIT = (() => {
+ const i = args.indexOf('--limit');
+ return i !== -1 && args[i + 1] ? Math.max(1, parseInt(args[i + 1], 10) || 1000) : 5000;
+})();
+const CONCURRENCY = 4; // keypair gen is CPU-light; cap concurrent DB writes.
+
+if (!process.env.DATABASE_URL) {
+ console.error('ERROR: DATABASE_URL is required. Set it in .env.local or the environment.');
+ process.exit(1);
+}
+
+const { sql } = await import('../api/_lib/db.js');
+const { ensureAgentWallet } = await import('../api/_lib/agent-wallet.js');
+
+const rows = await sql`
+ SELECT id, name, user_id
+ FROM agent_identities
+ WHERE deleted_at IS NULL
+ AND (meta IS NULL OR meta->>'solana_address' IS NULL OR meta->>'solana_address' = '')
+ ORDER BY created_at ASC
+ LIMIT ${LIMIT}
+`;
+
+console.log(`Found ${rows.length} agent identit${rows.length === 1 ? 'y' : 'ies'} without a Solana wallet address.`);
+
+if (!APPLY) {
+ for (const row of rows) {
+ console.log(` [pending] agent ${row.id} name="${row.name ?? ''}"`);
+ }
+ console.log(
+ rows.length
+ ? `\nReport only — re-run with --apply to provision ${rows.length} wallet(s).`
+ : '\nNothing to backfill.',
+ );
+ process.exit(0);
+}
+
+if (rows.length === 0) {
+ console.log('All agents already have a Solana wallet. Nothing to do.');
+ await sql.end?.();
+ process.exit(0);
+}
+
+let created = 0;
+let alreadyHad = 0;
+let failed = 0;
+
+async function processOne(row) {
+ try {
+ const wallet = await ensureAgentWallet(row.id, row.user_id, { reason: 'backfill' });
+ if (wallet.created) {
+ created++;
+ console.log(` ✓ provisioned agent ${row.id} address=${wallet.address}`);
+ } else {
+ // Race: another process provisioned between the SELECT and now.
+ alreadyHad++;
+ console.log(` · exists agent ${row.id} address=${wallet.address}`);
+ }
+ } catch (err) {
+ failed++;
+ console.error(` ✗ failed agent ${row.id} error=${err?.message}`);
+ }
+}
+
+for (let i = 0; i < rows.length; i += CONCURRENCY) {
+ await Promise.all(rows.slice(i, i + CONCURRENCY).map(processOne));
+}
+
+console.log('\n── Results ──────────────────────────────────────────────────────');
+console.log(` Provisioned : ${created}`);
+console.log(` Already had : ${alreadyHad}`);
+console.log(` Failed : ${failed}`);
+
+// Verify zero rows remain (the success criterion). A non-empty remainder after a
+// full run means some provisions failed — surface a non-zero exit for CI/ops.
+const [{ remaining }] = await sql`
+ SELECT COUNT(*)::int AS remaining
+ FROM agent_identities
+ WHERE deleted_at IS NULL
+ AND (meta IS NULL OR meta->>'solana_address' IS NULL OR meta->>'solana_address' = '')
+`;
+console.log(` Remaining : ${remaining}`);
+
+await sql.end?.();
+process.exit(failed > 0 || remaining > 0 ? 1 : 0);
diff --git a/src/animation-manager.js b/src/animation-manager.js
index 436bc4e45..05142975c 100644
--- a/src/animation-manager.js
+++ b/src/animation-manager.js
@@ -280,6 +280,69 @@ export class AnimationManager {
try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
}
+ /**
+ * Play a one-shot clip exactly once, then settle into a looping clip
+ * (`idle` by default) with a crossfade — instead of clamping and freezing on
+ * the final frame, which reads as a hard snap on a looping thumbnail. This is
+ * the seamless path for manifest clips whose `loop` field is false
+ * (`celebrate`, `wave`, …). Lazily loads both the one-shot and the settle clip.
+ *
+ * @param {string} name
+ * @param {{ settleTo?: string|null, fade?: number }} [opts]
+ */
+ async playOnce(name, { settleTo = 'idle', fade = DEFAULT_CROSSFADE } = {}) {
+ fade = Math.max(0, Math.min(fade, 5));
+ const ready = await this.ensureLoaded(name);
+ const action = ready ? this.actions.get(name) : null;
+ if (!action) {
+ // One-shot unavailable on this rig — fall back to the settle clip so
+ // the avatar is never left frozen in its bind pose.
+ if (settleTo) return this.crossfadeTo(settleTo, fade);
+ return;
+ }
+
+ action.reset();
+ action.setLoop(LoopOnce, 1);
+ // Hold the final frame until the settle crossfade picks it up — without
+ // this the action would snap back to frame 0 the instant it completes.
+ action.clampWhenFinished = true;
+ action.play();
+ if (this.currentAction && this.currentAction !== action) {
+ this.currentAction.crossFadeTo(action, fade, true);
+ } else {
+ action.fadeIn(fade);
+ }
+ this.currentAction = action;
+ this.currentName = name;
+
+ if (settleTo && this.mixer) {
+ const onFinished = (e) => {
+ if (e.action !== action) return;
+ this.mixer.removeEventListener('finished', onFinished);
+ // Only settle if nothing else took over the avatar meanwhile.
+ if (this.currentAction === action) this.crossfadeTo(settleTo, fade);
+ };
+ this.mixer.addEventListener('finished', onFinished);
+ }
+ try { this.onChange?.(name); } catch (e) { log.warn('[AnimationManager] onChange threw:', e); }
+ }
+
+ /**
+ * Freeze the active clip on its current pose and release it as the active
+ * action so the host viewer's render loop can settle (it stops scheduling
+ * frames once nothing is animating). The paused action keeps applying its
+ * held pose whenever the mixer does tick again (e.g. on scroll-back-in), so
+ * the avatar shows a clean static pose rather than a T-pose.
+ *
+ * Used for `prefers-reduced-motion`: a calm held pose with no looping motion
+ * and no continuous GPU/CPU cost.
+ */
+ freeze() {
+ if (this.currentAction) this.currentAction.paused = true;
+ this.currentAction = null;
+ this.currentName = null;
+ }
+
/**
* Crossfade from the current clip to a named clip.
* Lazily loads if not yet in memory.
diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.js
index 62d396087..41cd70b21 100644
--- a/src/dashboard-next/pages/irl-placements.js
+++ b/src/dashboard-next/pages/irl-placements.js
@@ -26,6 +26,7 @@ import { mountShell } from '../shell.js';
import { requireUser, get, post, patch, esc, relTime } from '../api.js';
import { skeletonHTML, emptyStateHTML, errorStateHTML, ensureStateKitStyles } from '../../shared/state-kit.js';
import { loadInto } from '../../shared/async-state.js';
+import { loadLeaflet } from '../../shared/leaflet.js';
import { mountReputationPanel } from './irl-reputation.js';
// ── Services / x402 skill pricing ───────────────────────────────────────────
@@ -1078,10 +1079,8 @@ function restoreCaption(card, caption) {
// ── Location map (Leaflet, lazy-loaded) ─────────────────────────────────────
// A real OSM map with a draggable marker per placed agent, so the owner can
// relocate / re-aim / remove a pin from anywhere — not just standing at the
-// spot. Leaflet (JS + CSS) is imported from a CDN only when the panel opens, so
-// the rest of the dashboard never pays for it.
-const LEAFLET_JS = 'https://esm.sh/[email protected]';
-const LEAFLET_CSS = 'https://unpkg.com/[email protected]/dist/leaflet.css';
+// spot. The lazy CDN loader is shared with the /irl My-pins overview (one
+// source, one promise cache, one graceful-failure contract).
// North-up compass dial; the needle <g> is rotated by the heading at runtime.
const COMPASS_SVG = `<svg viewBox="-50 -50 100 100" aria-hidden="true">
@@ -1093,35 +1092,6 @@ const COMPASS_SVG = `<svg viewBox="-50 -50 100 100" aria-hidden="true">
<g class="needle" data-needle transform="rotate(0)"><polygon points="0,-30 6,6 0,1 -6,6"/></g>
</svg>`;
-let _leafletCssPromise = null;
-function ensureLeafletCss() {
- if (_leafletCssPromise) return _leafletCssPromise;
- _leafletCssPromise = new Promise((resolve, reject) => {
- if (document.getElementById('leaflet-css')) { resolve(); return; }
- const link = document.createElement('link');
- link.id = 'leaflet-css';
- link.rel = 'stylesheet';
- link.href = LEAFLET_CSS;
- link.crossOrigin = '';
- link.onload = () => resolve();
- link.onerror = () => { link.remove(); reject(new Error('leaflet css failed to load')); };
- document.head.appendChild(link);
- }).catch((e) => { _leafletCssPromise = null; throw e; });
- return _leafletCssPromise;
-}
-
-let _leafletPromise = null;
-function loadLeaflet() {
- if (_leafletPromise) return _leafletPromise;
- _leafletPromise = (async () => {
- const [mod] = await Promise.all([import(/* @vite-ignore */ LEAFLET_JS), ensureLeafletCss()]);
- const L = mod?.default || mod;
- if (!L || typeof L.map !== 'function') throw new Error('leaflet module missing');
- return L;
- })().catch((e) => { _leafletPromise = null; throw e; });
- return _leafletPromise;
-}
-
const norm360 = (h) => ((Math.round(Number(h) || 0) % 360) + 360) % 360;
// Relocation map modal. `pins` is the live page list (shared ref); `focusId` is
diff --git a/src/irl.js b/src/irl.js
index 59239e052..4a579f94d 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -57,6 +57,8 @@ import { roomOriginWorld, agentWorldPosition } from './irl/room-anchor.js';
import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch } from './irl/sensor-fusion.js';
import { pinBandAction } from './irl/proximity-band.js';
import { loadInto } from './shared/async-state.js';
+import { openMapPlacePicker } from './irl/map-place.js';
+import { loadLeaflet } from './shared/leaflet.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
const ANIMATIONS_MANIFEST_URL = '/animations/manifest.json';
@@ -1438,16 +1440,21 @@ async function savePin(lat, lng, heading = 0, caption = '', anchor = null) {
// altitude always come from the live fix; heightM / yawDeg / quat / source
// come from the placement mode (gyro-gps today, webxr later).
const a = anchor || {};
+ // 'webxr' (A1) · 'gyro-gps' (absolute compass) · 'gyro-gps:rel' (page-relative
+ // heading — A3 down-weights its cross-user bearing) · 'map' (L2: a point chosen
+ // on the map, NOT a live fix at that spot — so it carries no GPS accuracy/altitude
+ // and its bearing isn't compass-trustworthy).
+ const src = a.source === 'webxr' ? 'webxr'
+ : a.source === 'map' ? 'map'
+ : a.source === 'gyro-gps:rel' ? 'gyro-gps:rel' : 'gyro-gps';
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',
+ // accuracy / altitude describe the live fix; a map placement has neither.
+ gpsAccuracyM: src === 'map' ? null : gpsState.accuracy,
+ altitudeM: src === 'map' ? null : gpsState.altitude,
+ source: src,
};
const r = await fetch('/api/irl/pins', {
method: 'POST',
@@ -1554,6 +1561,56 @@ function commitPin(pinLat, pinLng, headingDeg, caption, source = 'gyro-gps') {
});
}
+// ── Place on the map (L2) ──────────────────────────────────────────────────
+//
+// A privacy-first, remote alternative to "Pin here": instead of writing the
+// user's exact standing GPS, they choose a spot on a map and the agent is placed
+// there. This path NEVER engages the local AR lock (no gpsPin, no gps-mode) — the
+// agent isn't in front of you, it's dropped at the chosen coordinate and surfaces
+// to anyone who walks near that spot (and to you here if you happen to be close).
+function startMapPlacement() {
+ const start = gpsState.ready ? { lat: gpsState.lat, lng: gpsState.lng } : null;
+ openMapPlacePicker({
+ start,
+ onConfirm: ({ lat, lng, label }) => openCaptionForMapPin(lat, lng, label),
+ });
+}
+
+// Optional caption step for a map-placed pin. Reuses the caption panel UI but
+// routes confirm/cancel to the remote commit — cancel just closes (there is no AR
+// lock to release, unlike the gyro/GPS caption flow).
+function openCaptionForMapPin(lat, lng, label) {
+ if (!captionPanel) { commitMapPin(lat, lng, '', label); return; }
+ captionInput.value = '';
+ captionPanel.classList.add('is-open');
+ setTimeout(() => captionInput.focus(), 300);
+ captionConfirm.onclick = () => {
+ captionPanel.classList.remove('is-open');
+ commitMapPin(lat, lng, captionInput.value.trim(), label);
+ };
+ captionCancel.onclick = () => { captionPanel.classList.remove('is-open'); };
+}
+
+async function commitMapPin(lat, lng, caption, label) {
+ setStatus('Placing agent…', { loading: true, sticky: true });
+ // source:'map' → the server records a non-GPS, non-compass placement; savePin
+ // nulls the GPS accuracy/altitude for it. heading 0 (no live bearing to store).
+ const result = await savePin(lat, lng, 0, caption, { heightM: 0, yawDeg: 0, source: 'map' });
+ if (result?.ok) {
+ _myPinIds.add(result.id);
+ const where = label ? ` at ${label}` : '';
+ setStatus(result.permanent
+ ? `Agent placed${where} — permanently visible to people nearby that spot`
+ : `Agent placed${where} — visible to people nearby for 7 days`);
+ revealMyPinsBtn();
+ // If the chosen spot happens to be near the viewer, surface it immediately
+ // instead of waiting for the next proximity poll.
+ if (gpsState.ready) loadNearbyPins();
+ } else {
+ setStatus(result?.message || saveErrorFallback(result?.error), { error: true });
+ }
+}
+
// ── WebXR floor anchor (A1) ────────────────────────────────────────────────
//
// On WebXR-capable devices (primarily Android Chrome) the user taps a real
@@ -2784,6 +2841,7 @@ function revealMyPinsBtn() {
}
document.getElementById('irl-mypins-btn')?.addEventListener('click', openMyPinsSheet);
+document.getElementById('irl-mapplace-btn')?.addEventListener('click', startMapPlacement);
// ── "Appear to others nearby" toggle (D2) ──────────────────────────────────
// Reflects the stored opt-in on the pill (default off) and flips it live: the
diff --git a/src/irl/map-place.js b/src/irl/map-place.js
new file mode 100644
index 000000000..7eeb48277
--- /dev/null
+++ b/src/irl/map-place.js
@@ -0,0 +1,270 @@
+// src/irl/map-place.js — "Pick a spot on the map" placement picker (L2).
+//
+// Lets a user place a 3D agent at ANY chosen coordinate instead of their exact
+// live GPS — the headline privacy win (drop an agent at a café or plaza, never
+// your home) and a UX upgrade (place where you're going, or somewhere that
+// matters). Self-contained: a bottom sheet with a Leaflet map, a draggable
+// marker, place search, a live reverse-geocoded label, and fully designed
+// loading / error / no-results states. Resolves via `onConfirm({lat,lng,label})`.
+//
+// Reuses the single shared Leaflet stack + Nominatim helpers (shared/leaflet-loader)
+// so there is never a second map stack. The map is the ONLY thing that can fail
+// hard here, and it fails into a retryable state — never a blank rectangle.
+
+import { loadLeaflet, reverseGeocode, searchPlaces } from '../shared/leaflet-loader.js';
+
+const STYLE_ID = 'irlmp-styles';
+
+function ensureStyles() {
+ if (document.getElementById(STYLE_ID)) return;
+ const el = document.createElement('style');
+ el.id = STYLE_ID;
+ el.textContent = `
+.irlmp-root{position:fixed;inset:0;z-index:10000;display:flex;align-items:flex-end;justify-content:center;}
+.irlmp-backdrop{position:absolute;inset:0;background:rgba(4,6,12,.62);backdrop-filter:blur(2px);animation:irlmp-fade .2s ease}
+.irlmp-sheet{position:relative;width:100%;max-width:560px;max-height:88vh;display:flex;flex-direction:column;
+ background:#0c0f17;border:1px solid #232838;border-bottom:none;border-radius:18px 18px 0 0;
+ box-shadow:0 -8px 40px rgba(0,0,0,.55);overflow:hidden;animation:irlmp-rise .26s cubic-bezier(.2,.8,.2,1)}
+@media(min-width:600px){.irlmp-root{align-items:center}.irlmp-sheet{border-radius:18px;border-bottom:1px solid #232838}}
+@keyframes irlmp-rise{from{transform:translateY(14px);opacity:.4}to{transform:translateY(0);opacity:1}}
+@keyframes irlmp-fade{from{opacity:0}to{opacity:1}}
+.irlmp-head{display:flex;align-items:center;justify-content:space-between;padding:14px 16px 10px;flex-shrink:0}
+.irlmp-title{font:600 15px/1.2 system-ui,sans-serif;color:#eef1f7}
+.irlmp-x{appearance:none;background:none;border:none;color:#8b93a7;font-size:24px;line-height:1;cursor:pointer;
+ width:34px;height:34px;border-radius:8px;display:flex;align-items:center;justify-content:center;transition:background .15s,color .15s}
+.irlmp-x:hover,.irlmp-x:focus-visible{background:#1a1f2e;color:#eef1f7;outline:none}
+.irlmp-search{position:relative;padding:0 16px 10px;flex-shrink:0}
+.irlmp-search input{width:100%;box-sizing:border-box;background:#11151f;border:1px solid #2a3042;border-radius:10px;
+ color:#eef1f7;font:500 14px/1.3 system-ui,sans-serif;padding:11px 12px;transition:border-color .15s,box-shadow .15s}
+.irlmp-search input:focus{outline:none;border-color:#4f7cff;box-shadow:0 0 0 3px rgba(79,124,255,.18)}
+.irlmp-results{position:absolute;left:16px;right:16px;top:calc(100% - 4px);z-index:5;background:#11151f;border:1px solid #2a3042;
+ border-radius:10px;overflow:hidden;max-height:220px;overflow-y:auto;box-shadow:0 8px 24px rgba(0,0,0,.5)}
+.irlmp-result{display:block;width:100%;text-align:left;background:none;border:none;border-bottom:1px solid #1b2030;
+ color:#dfe3ec;font:500 13px/1.35 system-ui,sans-serif;padding:10px 12px;cursor:pointer;transition:background .12s}
+.irlmp-result:last-child{border-bottom:none}
+.irlmp-result:hover,.irlmp-result.is-active{background:#1a2032}
+.irlmp-result small{display:block;color:#8b93a7;font-size:11px;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.irlmp-results-empty{padding:12px;color:#8b93a7;font:500 13px/1.4 system-ui,sans-serif;text-align:center}
+.irlmp-mapwrap{position:relative;flex:1;min-height:280px;background:#11151f}
+.irlmp-map{position:absolute;inset:0}
+.irlmp-map .leaflet-control-zoom a{background:#11151f;color:#eef1f7;border-color:#2a3042}
+.irlmp-map .leaflet-control-zoom a:hover{background:#1a2032}
+.irlmp-map .leaflet-control-attribution{background:rgba(8,10,16,.7);color:#99a;font-size:10px}
+.irlmp-map .leaflet-control-attribution a{color:#9cf}
+.irlmp-pin-icon{background:none;border:none}
+.irlmp-pin{width:36px;height:44px;transform:translateY(-6px);filter:drop-shadow(0 3px 4px rgba(0,0,0,.5))}
+.irlmp-overlay{position:absolute;inset:0;z-index:600;display:flex;flex-direction:column;align-items:center;justify-content:center;
+ gap:12px;background:#11151f;color:#aeb6c8;font:500 13px/1.4 system-ui,sans-serif;text-align:center;padding:24px}
+.irlmp-overlay.gone{opacity:0;pointer-events:none;transition:opacity .3s}
+.irlmp-spin{width:22px;height:22px;border-radius:50%;border:2px solid #2a3042;border-top-color:#4f7cff;animation:irlmp-rot .8s linear infinite}
+@keyframes irlmp-rot{to{transform:rotate(360deg)}}
+.irlmp-retry{appearance:none;background:#4f7cff;color:#fff;border:none;border-radius:9px;font:600 13px system-ui,sans-serif;
+ padding:9px 16px;cursor:pointer;transition:background .15s}
+.irlmp-retry:hover{background:#3d6af0}
+.irlmp-foot{flex-shrink:0;padding:12px 16px 16px;border-top:1px solid #1b2030;background:#0c0f17}
+.irlmp-coords{font:500 12px/1.4 system-ui,sans-serif;color:#aeb6c8;margin-bottom:10px;min-height:17px}
+.irlmp-coords b{color:#eef1f7;font-weight:600}
+.irlmp-actions{display:flex;gap:10px}
+.irlmp-actions button{flex:1;appearance:none;border-radius:11px;font:600 14px system-ui,sans-serif;padding:12px;cursor:pointer;transition:background .15s,opacity .15s,transform .06s}
+.irlmp-actions button:active{transform:translateY(1px)}
+.irlmp-cancel{background:#1a1f2e;color:#cfd5e3;border:1px solid #2a3042}
+.irlmp-cancel:hover{background:#222838}
+.irlmp-confirm{background:#4f7cff;color:#fff;border:1px solid #4f7cff}
+.irlmp-confirm:hover:not(:disabled){background:#3d6af0}
+.irlmp-confirm:disabled{opacity:.45;cursor:not-allowed}
+`;
+ document.head.appendChild(el);
+}
+
+const PIN_SVG = `<svg class="irlmp-pin" viewBox="0 0 24 30" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M12 0C5.9 0 1 4.9 1 11c0 7.5 9.4 17.6 9.8 18a1.6 1.6 0 0 0 2.4 0C13.6 28.6 23 18.5 23 11 23 4.9 18.1 0 12 0Z" fill="#4f7cff" stroke="#dfe6ff" stroke-width="1.4"/>
+ <circle cx="12" cy="11" r="4" fill="#fff"/></svg>`;
+
+const fmt = (v) => (Math.round(v * 1e5) / 1e5).toFixed(5);
+
+/**
+ * Open the placement picker. Returns nothing; calls `onConfirm({lat,lng,label})`
+ * when the user confirms a point, or `onCancel()` when they dismiss it.
+ * @param {{start?:{lat:number,lng:number}, onConfirm:Function, onCancel?:Function}} opts
+ */
+export function openMapPlacePicker({ start = null, onConfirm, onCancel } = {}) {
+ ensureStyles();
+
+ const root = document.createElement('div');
+ root.className = 'irlmp-root';
+ root.setAttribute('role', 'dialog');
+ root.setAttribute('aria-modal', 'true');
+ root.setAttribute('aria-label', 'Pick a spot on the map');
+ root.innerHTML = `
+ <div class="irlmp-backdrop" data-cancel></div>
+ <div class="irlmp-sheet">
+ <div class="irlmp-head">
+ <div class="irlmp-title">Pick a spot on the map</div>
+ <button class="irlmp-x" type="button" data-cancel aria-label="Cancel">×</button>
+ </div>
+ <div class="irlmp-search">
+ <input type="search" autocomplete="off" placeholder="Search a place — “Dolores Park, SF”" aria-label="Search for a place" />
+ <div class="irlmp-results" role="listbox" hidden></div>
+ </div>
+ <div class="irlmp-mapwrap">
+ <div class="irlmp-map"></div>
+ <div class="irlmp-overlay" data-state>
+ <div class="irlmp-spin"></div><div>Loading map…</div>
+ </div>
+ </div>
+ <div class="irlmp-foot">
+ <div class="irlmp-coords" aria-live="polite">Drag the pin or tap the map to choose a spot.</div>
+ <div class="irlmp-actions">
+ <button class="irlmp-cancel" type="button" data-cancel>Cancel</button>
+ <button class="irlmp-confirm" type="button" disabled>Place here</button>
+ </div>
+ </div>
+ </div>`;
+ document.body.appendChild(root);
+ const prevOverflow = document.body.style.overflow;
+ document.body.style.overflow = 'hidden';
+
+ const searchInput = root.querySelector('.irlmp-search input');
+ const resultsEl = root.querySelector('.irlmp-results');
+ const mapEl = root.querySelector('.irlmp-map');
+ const overlay = root.querySelector('[data-state]');
+ const coordsEl = root.querySelector('.irlmp-coords');
+ const confirmBtn = root.querySelector('.irlmp-confirm');
+
+ let L = null, map = null, marker = null;
+ let picked = null; // { lat, lng }
+ let pickedLabel = null; // reverse-geocoded label string
+ let geoSeq = 0; // guards out-of-order reverse-geocode responses
+ let searchSeq = 0; // guards out-of-order search responses
+ let searchAbort = null;
+ let destroyed = false;
+
+ const close = (confirmed) => {
+ if (destroyed) return;
+ destroyed = true;
+ document.removeEventListener('keydown', onKey, true);
+ try { map?.remove(); } catch { /* leaflet teardown best-effort */ }
+ root.remove();
+ document.body.style.overflow = prevOverflow;
+ if (!confirmed) onCancel?.();
+ };
+
+ const onKey = (ev) => {
+ if (ev.key === 'Escape') { ev.stopPropagation(); close(false); }
+ };
+ document.addEventListener('keydown', onKey, true);
+ root.querySelectorAll('[data-cancel]').forEach((b) => b.addEventListener('click', () => close(false)));
+
+ // ── Picked-point state ──────────────────────────────────────────────────
+ function setPicked(lat, lng) {
+ picked = { lat, lng };
+ confirmBtn.disabled = false;
+ pickedLabel = null;
+ coordsEl.innerHTML = `<b>${fmt(lat)}, ${fmt(lng)}</b> · finding place…`;
+ const seq = ++geoSeq;
+ reverseGeocode(lat, lng).then((label) => {
+ if (destroyed || seq !== geoSeq) return;
+ pickedLabel = label;
+ coordsEl.innerHTML = label
+ ? `<b>${esc(label)}</b> · ${fmt(lat)}, ${fmt(lng)}`
+ : `<b>${fmt(lat)}, ${fmt(lng)}</b>`;
+ });
+ }
+
+ function moveMarker(lat, lng, recenter) {
+ if (!marker) return;
+ marker.setLatLng([lat, lng]);
+ if (recenter) map.panTo([lat, lng], { animate: true });
+ setPicked(lat, lng);
+ }
+
+ // ── Map boot (the only hard-failure path) ───────────────────────────────
+ async function boot() {
+ overlay.classList.remove('gone');
+ overlay.innerHTML = `<div class="irlmp-spin"></div><div>Loading map…</div>`;
+ try {
+ L = await loadLeaflet();
+ if (destroyed) return;
+ const center = start && Number.isFinite(start.lat) ? [start.lat, start.lng] : [20, 0];
+ const zoom = start && Number.isFinite(start.lat) ? 16 : 3;
+ map = L.map(mapEl, { zoomControl: true, attributionControl: true }).setView(center, zoom);
+ L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
+ maxZoom: 19,
+ attribution: '© OpenStreetMap',
+ }).addTo(map);
+
+ const icon = L.divIcon({ className: 'irlmp-pin-icon', html: PIN_SVG, iconSize: [36, 44], iconAnchor: [18, 40] });
+ marker = L.marker(center, { draggable: true, icon, keyboard: true, title: 'Drag to your chosen spot' }).addTo(map);
+ marker.on('dragend', () => { const p = marker.getLatLng(); setPicked(p.lat, p.lng); });
+ map.on('click', (e) => moveMarker(e.latlng.lat, e.latlng.lng, false));
+
+ // A known start point IS a valid pick; an unknown one waits for the user.
+ if (start && Number.isFinite(start.lat)) setPicked(start.lat, start.lng);
+
+ // Leaflet needs a size recalculation after the sheet's open animation.
+ setTimeout(() => { try { map.invalidateSize(); } catch {} }, 260);
+ overlay.classList.add('gone');
+ } catch (err) {
+ if (destroyed) return;
+ overlay.classList.remove('gone');
+ overlay.innerHTML = `<div>Couldn’t load the map.</div>
+ <button class="irlmp-retry" type="button">Try again</button>
+ <div style="font-size:11px;color:#7b8398">Check your connection and retry.</div>`;
+ overlay.querySelector('.irlmp-retry')?.addEventListener('click', boot);
+ }
+ }
+
+ // ── Search (debounced, abortable, out-of-order safe) ────────────────────
+ function renderResults(rows) {
+ if (!rows.length) {
+ resultsEl.innerHTML = `<div class="irlmp-results-empty">No matching places.</div>`;
+ resultsEl.hidden = false;
+ return;
+ }
+ resultsEl.innerHTML = rows.map((r, i) =>
+ `<button class="irlmp-result" type="button" role="option" data-i="${i}">${esc(r.short)}<small>${esc(r.label)}</small></button>`
+ ).join('');
+ resultsEl.hidden = false;
+ resultsEl.querySelectorAll('.irlmp-result').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const r = rows[Number(btn.dataset.i)];
+ resultsEl.hidden = true;
+ searchInput.value = r.short;
+ if (map) { map.setView([r.lat, r.lng], 16, { animate: true }); moveMarker(r.lat, r.lng, false); }
+ });
+ });
+ }
+
+ let searchTimer = null;
+ searchInput.addEventListener('input', () => {
+ clearTimeout(searchTimer);
+ const q = searchInput.value.trim();
+ if (q.length < 2) { resultsEl.hidden = true; return; }
+ searchTimer = setTimeout(async () => {
+ const seq = ++searchSeq;
+ try { searchAbort?.abort(); } catch {}
+ searchAbort = new AbortController();
+ const rows = await searchPlaces(q, { signal: searchAbort.signal });
+ if (destroyed || seq !== searchSeq) return;
+ renderResults(rows);
+ }, 320);
+ });
+ searchInput.addEventListener('keydown', (ev) => { if (ev.key === 'Escape' && !resultsEl.hidden) { ev.stopPropagation(); resultsEl.hidden = true; } });
+ // Tapping the map area dismisses an open results list.
+ mapEl.addEventListener('pointerdown', () => { resultsEl.hidden = true; }, true);
+
+ confirmBtn.addEventListener('click', () => {
+ if (!picked) return;
+ const out = { lat: picked.lat, lng: picked.lng, label: pickedLabel };
+ close(true);
+ onConfirm?.(out);
+ });
+
+ setTimeout(() => searchInput.focus(), 80);
+ boot();
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
diff --git a/src/shared/leaflet-loader.js b/src/shared/leaflet-loader.js
new file mode 100644
index 000000000..d6de56ba8
--- /dev/null
+++ b/src/shared/leaflet-loader.js
@@ -0,0 +1,91 @@
+// src/shared/leaflet-loader.js — single, lazy Leaflet stack + Nominatim helpers.
+//
+// One CDN version, one CSS injection, one in-flight promise — so every surface
+// that needs a map (the IRL placement picker, the dashboard relocate modal, the
+// My-pins overview) shares the same Leaflet instance and never ships a second map
+// stack. Leaflet (JS + CSS) loads only when a map actually opens; the rest of the
+// app never pays for it.
+
+const LEAFLET_JS = 'https://esm.sh/[email protected]';
+const LEAFLET_CSS = 'https://unpkg.com/[email protected]/dist/leaflet.css';
+
+let _cssPromise = null;
+export function ensureLeafletCss() {
+ if (_cssPromise) return _cssPromise;
+ _cssPromise = new Promise((resolve, reject) => {
+ if (document.getElementById('leaflet-css')) { resolve(); return; }
+ const link = document.createElement('link');
+ link.id = 'leaflet-css';
+ link.rel = 'stylesheet';
+ link.href = LEAFLET_CSS;
+ link.crossOrigin = '';
+ link.onload = () => resolve();
+ link.onerror = () => { link.remove(); reject(new Error('leaflet css failed to load')); };
+ document.head.appendChild(link);
+ }).catch((e) => { _cssPromise = null; throw e; });
+ return _cssPromise;
+}
+
+let _jsPromise = null;
+export function loadLeaflet() {
+ if (_jsPromise) return _jsPromise;
+ _jsPromise = (async () => {
+ const [mod] = await Promise.all([import(/* @vite-ignore */ LEAFLET_JS), ensureLeafletCss()]);
+ const L = mod?.default || mod;
+ if (!L || typeof L.map !== 'function') throw new Error('leaflet module missing');
+ return L;
+ })().catch((e) => { _jsPromise = null; throw e; });
+ return _jsPromise;
+}
+
+// ── Nominatim geocoding (shared, memoized, polite) ──────────────────────────
+// OSM's Nominatim is rate-limited and asks for a descriptive UA. We memoize per
+// ~11 m cell and never let a geocode failure block the caller — a null label is
+// a soft, designed state, never an error.
+
+const _reverseCache = new Map();
+
+// Reverse: coords → a short human place label (city/town/first display part).
+export async function reverseGeocode(lat, lng) {
+ if (lat == null || lng == null) return null;
+ const key = `${Number(lat).toFixed(4)},${Number(lng).toFixed(4)}`;
+ if (_reverseCache.has(key)) return _reverseCache.get(key);
+ const p = (async () => {
+ try {
+ const r = await fetch(
+ `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lng}&format=json`,
+ { headers: { 'User-Agent': 'three.ws/1.0' } },
+ );
+ if (!r.ok) return null;
+ const d = await r.json();
+ return d.address?.city || d.address?.town || d.address?.village
+ || d.address?.county || d.display_name?.split(',')[0] || null;
+ } catch { return null; }
+ })();
+ _reverseCache.set(key, p);
+ return p;
+}
+
+// Forward: free-text query → up to `limit` candidate places. Returns [] on any
+// failure (empty query, network, non-OK) so the caller renders a "no results"
+// state rather than throwing. `signal` lets the caller abort a stale search.
+export async function searchPlaces(query, { limit = 6, signal } = {}) {
+ const q = String(query || '').trim();
+ if (q.length < 2) return [];
+ try {
+ const r = await fetch(
+ `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(q)}&format=json&limit=${limit}`,
+ { headers: { 'User-Agent': 'three.ws/1.0' }, signal },
+ );
+ if (!r.ok) return [];
+ const rows = await r.json();
+ return (Array.isArray(rows) ? rows : [])
+ .map((d) => ({
+ lat: parseFloat(d.lat),
+ lng: parseFloat(d.lon),
+ label: d.display_name || '',
+ short: d.display_name?.split(',').slice(0, 2).join(',') || d.display_name || '',
+ }))
+ .filter((r) => Number.isFinite(r.lat) && Number.isFinite(r.lng));
+ } catch { return []; }
+}
diff --git a/src/shared/leaflet.js b/src/shared/leaflet.js
new file mode 100644
index 000000000..3f186d494
--- /dev/null
+++ b/src/shared/leaflet.js
@@ -0,0 +1,44 @@
+/**
+ * Shared lazy Leaflet loader.
+ *
+ * Leaflet's JS + CSS are fetched from a CDN only on first use, so surfaces that
+ * never open a map (most of the app) pay nothing for it. Every map surface — the
+ * dashboard placement editor and the /irl My-pins overview — shares this one
+ * loader, so there is a single CDN source, a single promise cache (Leaflet loads
+ * at most once per session), and a single graceful-failure contract: a blocked or
+ * offline CDN rejects, and every caller degrades to a map-free fallback instead of
+ * a broken surface.
+ */
+
+export const LEAFLET_JS = 'https://esm.sh/[email protected]';
+export const LEAFLET_CSS = 'https://unpkg.com/[email protected]/dist/leaflet.css';
+
+let _cssPromise = null;
+export function ensureLeafletCss() {
+ if (_cssPromise) return _cssPromise;
+ _cssPromise = new Promise((resolve, reject) => {
+ if (typeof document === 'undefined') { reject(new Error('no document')); return; }
+ if (document.getElementById('leaflet-css')) { resolve(); return; }
+ const link = document.createElement('link');
+ link.id = 'leaflet-css';
+ link.rel = 'stylesheet';
+ link.href = LEAFLET_CSS;
+ link.crossOrigin = '';
+ link.onload = () => resolve();
+ link.onerror = () => { link.remove(); reject(new Error('leaflet css failed to load')); };
+ document.head.appendChild(link);
+ }).catch((e) => { _cssPromise = null; throw e; });
+ return _cssPromise;
+}
+
+let _jsPromise = null;
+export function loadLeaflet() {
+ if (_jsPromise) return _jsPromise;
+ _jsPromise = (async () => {
+ const [mod] = await Promise.all([import(/* @vite-ignore */ LEAFLET_JS), ensureLeafletCss()]);
+ const L = mod?.default || mod;
+ if (!L || typeof L.map !== 'function') throw new Error('leaflet module missing');
+ return L;
+ })().catch((e) => { _jsPromise = null; throw e; });
+ return _jsPromise;
+}
diff --git a/src/viewer.js b/src/viewer.js
index cc0097142..83f4ff7e5 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -59,6 +59,37 @@ Mesh.prototype.raycast = acceleratedRaycast;
Cache.enabled = true;
+/**
+ * Vertical framing geometry for a humanoid bounding box.
+ *
+ * `full` (default) frames the whole body: the look-at sits at the vertical
+ * centre and the visible height is the full bounding box. `portrait` crops to
+ * roughly head-to-mid-thigh so the avatar fills a wide or short card instead of
+ * standing tiny-and-low in it — the read that works best for a small embedded
+ * thumbnail.
+ *
+ * Pure (no THREE dependency) so it is unit-testable and can be shared by both
+ * `setContent()` (initial framing) and `frameContent()` (re-framing on resize).
+ * Both must agree or a resize would jump the camera. For `full` the result is
+ * mathematically identical to the previous inline computation, so non-portrait
+ * embeds are byte-for-byte unchanged.
+ *
+ * @param {number} bodyHeight full bounding-box height in world units
+ * @param {number} topY world-y of the top of the head in the working frame
+ * @param {'full'|'portrait'} [mode]
+ * @returns {{ visH:number, baseY:number }} visible height + look-at y
+ */
+export function computeFramingExtent(bodyHeight, topY, mode = 'full') {
+ if (mode === 'portrait') {
+ const PORTRAIT_FRAC = 0.62; // head → ~mid-thigh
+ const HEADROOM_FRAC = 0.04; // a little air above the crown
+ const visH = bodyHeight * PORTRAIT_FRAC;
+ const windowTop = topY + bodyHeight * HEADROOM_FRAC;
+ return { visH, baseY: windowTop - visH / 2 };
+ }
+ return { visH: bodyHeight, baseY: topY - bodyHeight / 2 };
+}
+
/**
* @class Viewer
*
@@ -464,14 +495,19 @@ export class Viewer {
const PAD_V = 1.25;
const PAD_H = 1.15;
- const extentV = (bbSize.y / 2) * PAD_V / usableFrac;
+ // `portrait` framing crops to head-to-mid-thigh so the avatar fills the
+ // frame in a wide/short card; `full` is unchanged (baseY == bbCenter.y).
+ const framingMode = this.options?.framing === 'portrait' ? 'portrait' : 'full';
+ const { visH, baseY } = computeFramingExtent(bbSize.y, box.max.y, framingMode);
+
+ const extentV = (visH / 2) * PAD_V / usableFrac;
const distV = extentV / Math.tan(vFovRad / 2);
const distH = (bbSize.x / 2) * PAD_H / Math.tan(hFovRad / 2);
const dist = Math.max(distV, distH);
- // Center look-at on the usable area: with no panel focusY = bbCenter.y;
+ // Center look-at on the usable area: with no panel focusY = baseY;
// with a bottom panel, shift down so the avatar rises into the upper area.
- const focusY = bbCenter.y - extentV * panelFrac;
+ const focusY = baseY - extentV * panelFrac;
const target = new Vector3(bbCenter.x, focusY, bbCenter.z);
const pos = new Vector3(bbCenter.x + dist * 0.12, focusY, bbCenter.z + dist);
@@ -485,6 +521,20 @@ export class Viewer {
}
}
+ /**
+ * Switch the framing mode ('full' | 'portrait') at runtime and re-frame.
+ * Used by the <agent-3d> `framing` attribute so an embed can opt into the
+ * head-to-mid-thigh crop without reloading the model.
+ * @param {'full'|'portrait'} mode
+ */
+ setFraming(mode) {
+ const next = mode === 'portrait' ? 'portrait' : 'full';
+ if (!this.options) this.options = {};
+ if (this.options.framing === next) return;
+ this.options.framing = next;
+ if (this.content) this.frameContent({ animate: true });
+ }
+
/** Fraction of canvas height occupied by the animation panel (0 when no panel). */
_panelFrac() {
if (!this._animPanelEl) return 0;
@@ -1001,16 +1051,21 @@ export class Viewer {
const PAD_V = 1.25;
const PAD_H = 1.15;
- const extentV = (bbSize.y / 2) * PAD_V / usableFrac;
+ // Model has been recentered so the body spans [-bbSize.y/2, +bbSize.y/2]
+ // and the crown is at +bbSize.y/2. `portrait` crops to head-to-mid-thigh;
+ // `full` reduces to the original full-body framing (baseY == 0).
+ const framingMode = this.options?.framing === 'portrait' ? 'portrait' : 'full';
+ const { visH, baseY } = computeFramingExtent(bbSize.y, bbSize.y / 2, framingMode);
+
+ const extentV = (visH / 2) * PAD_V / usableFrac;
const distV = extentV / Math.tan(vFovRad / 2);
const distH = (bbSize.x / 2) * PAD_H / Math.tan(hFovRad / 2);
const dist = Math.max(distV, distH);
- // Model has been recentered so bbCenter is at world origin (see
- // setContent above). Center the look-at on the usable area: with no
- // panel focusY=0; with a bottom panel shift down so the avatar rises
- // into the usable upper portion of the canvas.
- const focusY = -extentV * panelFrac;
+ // Center the look-at on the usable area: with no panel focusY=baseY;
+ // with a bottom panel shift down so the avatar rises into the usable
+ // upper portion of the canvas.
+ const focusY = baseY - extentV * panelFrac;
// Final framed camera (the position the user should end up at).
// Avatar sits dead-centered front-on by default — no lateral offset.
diff --git a/tests/animation-upright-invariant.test.js b/tests/animation-upright-invariant.test.js
new file mode 100644
index 000000000..3854a1051
--- /dev/null
+++ b/tests/animation-upright-invariant.test.js
@@ -0,0 +1,323 @@
+/**
+ * Cross-rig upright-invariant corpus — the "stays shipped" regression lock.
+ *
+ * The lying-down bug shipped because nothing asserted that an animated avatar
+ * stays upright. michelle.glb (a Mixamo export) rendered flat on its back the
+ * moment it played `celebrate`, because the retargeter copied the clip's Hips
+ * rotation verbatim and wiped the rig's −90°X up-axis convention. This suite
+ * locks the invariant — the Hips world up-axis stays within tolerance of
+ * vertical at EVERY keyframe — across a corpus of rig conventions × the
+ * FEATURED clips, using the same world-matrix reconstruction the bug was
+ * diagnosed with, in plain Node (raw GLB JSON-chunk parse, no GLTFLoader, no
+ * network) so it gates every Vercel build.
+ *
+ * Empirical tilt data (measured on the committed real avatars during
+ * development; re-derive by logging `max` below):
+ *
+ * max Hips tilt across all keyframes, retargeted WITH the bind correction:
+ * cz: idle 7.2° walk 6.7° jump 14.0° wave 15.4° dance 30.0° celebrate 14.0°
+ * michelle: idle 7.3° walk 6.7° jump 14.1° wave 15.4° dance 29.9° celebrate 14.1°
+ * same clips retargeted WITHOUT the correction (the pre-fix, verbatim path):
+ * cz: identical (cz IS the authoring convention → byte-for-byte no-op)
+ * michelle: idle 92° walk 93° jump 94° wave 89° dance 115° celebrate 94°
+ *
+ * `dance` legitimately leans the hips to ~30° at peak — that's choreography, not
+ * a fault — so the corpus tolerance must clear it. We use 40°: comfortably above
+ * the worst healthy clip (dance 30°) yet far below the catastrophe floor (the
+ * verbatim michelle case never drops below ~89°). The runtime guard fires at
+ * >45° but only samples the at-rest pose, where healthy clips peak at ~18°.
+ */
+
+import { describe, it, expect, beforeAll } from 'vitest';
+import { fileURLToPath } from 'node:url';
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import {
+ Bone,
+ Object3D,
+ SkinnedMesh,
+ Skeleton,
+ BufferGeometry,
+ Quaternion,
+ Vector3,
+} from 'three';
+import {
+ canonicalNodeMapFromObject,
+ canonicalRestMapFromObject,
+ retargetClip,
+ parseClipJSON,
+ MIN_COVERAGE,
+} from '../src/animation-retarget.js';
+import { FEATURED } from '../src/animation-presets.js';
+import { loadBoneGraph, hipsTiltAcrossClip } from './_helpers/glb-bone-graph.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '..');
+const avatar = (name) => resolve(repoRoot, 'public/avatars', name);
+const clipPath = (name) => resolve(repoRoot, 'public/animations/clips', `${name}.json`);
+
+// Tolerance for the upright invariant: see the empirical table in the module
+// header. 40° clears the worst healthy clip (dance ~30°) with margin and sits
+// well below the catastrophe floor (~89°), so a regression that tips a rig flat
+// cannot pass.
+const UPRIGHT_TOLERANCE_DEG = 40;
+// A retarget that produces a fallen pose lands near 90°. The "this test has
+// teeth" assertions prove the pre-fix path crosses this; the runtime guard uses
+// 45° (CATASTROPHE_TILT_DEG in src/animation-manager.js) for the same reason.
+const CATASTROPHE_DEG = 80;
+
+// Load the featured clips once.
+/** @type {Map<string, import('three').AnimationClip>} */
+const CLIPS = new Map();
+beforeAll(() => {
+ for (const name of FEATURED) {
+ const json = JSON.parse(readFileSync(clipPath(name), 'utf8'));
+ CLIPS.set(name, parseClipJSON(json, name));
+ }
+});
+
+// Retarget a featured clip onto a reconstructed rig the way AnimationManager
+// does, then return the Hips tilt scan. `withFix=false` drops the bind
+// correction (the pre-fix verbatim path) to prove the fix is load-bearing.
+function scanClip(root, clipName, { withFix = true } = {}) {
+ const map = canonicalNodeMapFromObject(root);
+ const targetRest = withFix ? canonicalRestMapFromObject(root) : new Map();
+ const { clip } = retargetClip(CLIPS.get(clipName), map, { targetRest });
+ const hipsName = map.get('Hips');
+ if (!hipsName) return null;
+ return hipsTiltAcrossClip(root, hipsName, clip);
+}
+
+// ── Real committed avatars ──────────────────────────────────────────────────
+
+describe('upright invariant — real avatars (cz Avaturn, michelle Mixamo)', () => {
+ for (const [label, file] of [
+ ['cz.glb (Avaturn, identity convention)', 'cz.glb'],
+ ['michelle.glb (Mixamo, −90°X Hips)', 'michelle.glb'],
+ ]) {
+ describe(label, () => {
+ for (const clip of FEATURED) {
+ it(`${clip} keeps Hips within ${UPRIGHT_TOLERANCE_DEG}° of vertical at every keyframe`, () => {
+ const { root } = loadBoneGraph(avatar(file));
+ const scan = scanClip(root, clip);
+ expect(scan).not.toBeNull();
+ expect(scan.samples).toBeGreaterThan(0);
+ expect(scan.max).toBeLessThan(UPRIGHT_TOLERANCE_DEG);
+ });
+ }
+ });
+ }
+});
+
+// ── Named regression lock: the exact bug ────────────────────────────────────
+
+describe('regression lock — the michelle lying-down bug', () => {
+ it('michelle + celebrate stays upright (regression lock for the lying-down bug)', () => {
+ const { root } = loadBoneGraph(avatar('michelle.glb'));
+ const scan = scanClip(root, 'celebrate');
+ expect(scan).not.toBeNull();
+ expect(scan.max).toBeLessThan(UPRIGHT_TOLERANCE_DEG);
+ });
+
+ it('the test has teeth: WITHOUT the bind correction, michelle + celebrate falls flat', () => {
+ // Prove the fix is load-bearing — the verbatim path (no targetRest) must
+ // reproduce the catastrophe, so this suite would have caught the bug and
+ // will catch any regression that removes the correction.
+ const { root } = loadBoneGraph(avatar('michelle.glb'));
+ const verbatim = scanClip(root, 'celebrate', { withFix: false });
+ expect(verbatim).not.toBeNull();
+ expect(verbatim.max).toBeGreaterThan(CATASTROPHE_DEG);
+ });
+});
+
+// ── Synthetic rigs (Bone graph built by hand — no GLB needed) ───────────────
+
+// Build a synthetic rig: an armature root carrying `armatureRot`, a Hips
+// carrying `hipsRot`, and a full enough canonical skeleton under it that a
+// featured clip clears MIN_COVERAGE. Bone names come from `nameFor` so the same
+// builder exercises canonical, DEF-/snake_case, and partial-coverage rigs.
+const CANONICAL_LIMBS = [
+ 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',
+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',
+ 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',
+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',
+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',
+ 'LeftHandThumb1', 'LeftHandIndex1', 'LeftHandMiddle1',
+ 'RightHandThumb1', 'RightHandIndex1', 'RightHandMiddle1',
+];
+
+function buildSyntheticRig({ armatureRot, hipsRot, nameFor, limbs = CANONICAL_LIMBS }) {
+ const root = new Object3D();
+ const armature = new Bone();
+ armature.name = 'Armature';
+ if (armatureRot) armature.quaternion.copy(armatureRot);
+
+ const hips = new Bone();
+ hips.name = nameFor('Hips');
+ if (hipsRot) hips.quaternion.copy(hipsRot);
+ armature.add(hips);
+
+ const bones = [armature, hips];
+ for (const canonical of limbs) {
+ const b = new Bone();
+ b.name = nameFor(canonical);
+ // Slight non-identity rest so limb rest capture is exercised, not all-zero.
+ b.quaternion.setFromAxisAngle(new Vector3(0, 0, 1), 0.05);
+ hips.add(b);
+ bones.push(b);
+ }
+
+ root.add(armature);
+ const mesh = new SkinnedMesh(new BufferGeometry());
+ root.add(mesh);
+ mesh.bind(new Skeleton(bones));
+ root.updateMatrixWorld(true);
+ return root;
+}
+
+const identityName = (canonical) => canonical;
+// DEF-/snake_case vendor names that canonicalizeBoneName still resolves.
+const SNAKE = {
+ Hips: 'DEF-hips', Spine: 'DEF-spine', Spine1: 'DEF-spine1', Spine2: 'DEF-spine2',
+ Neck: 'DEF-neck', Head: 'DEF-head',
+ LeftShoulder: 'left_shoulder', LeftArm: 'left_arm', LeftForeArm: 'left_forearm', LeftHand: 'left_hand',
+ RightShoulder: 'right_shoulder', RightArm: 'right_arm', RightForeArm: 'right_forearm', RightHand: 'right_hand',
+ LeftUpLeg: 'left_upleg', LeftLeg: 'left_leg', LeftFoot: 'left_foot', LeftToeBase: 'left_toebase',
+ RightUpLeg: 'right_upleg', RightLeg: 'right_leg', RightFoot: 'right_foot', RightToeBase: 'right_toebase',
+ LeftHandThumb1: 'left_handthumb1', LeftHandIndex1: 'left_handindex1', LeftHandMiddle1: 'left_handmiddle1',
+ RightHandThumb1: 'right_handthumb1', RightHandIndex1: 'right_handindex1', RightHandMiddle1: 'right_handmiddle1',
+};
+const snakeName = (canonical) => SNAKE[canonical] || canonical;
+
+const rotX = (deg) => new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), (deg * Math.PI) / 180);
+const rotZ = (deg) => new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), (deg * Math.PI) / 180);
+
+describe('upright invariant — synthetic rig conventions', () => {
+ // A non-±90 / non-X convention: +90°Z armature, compensating −90°Z Hips.
+ // Proves the correction generalises beyond the michelle (−90°X) case.
+ describe('non-±90X convention (+90°Z armature / −90°Z Hips)', () => {
+ for (const clip of FEATURED) {
+ it(`${clip} stays upright`, () => {
+ const root = buildSyntheticRig({
+ armatureRot: rotZ(90),
+ hipsRot: rotZ(-90),
+ nameFor: identityName,
+ });
+ const scan = scanClip(root, clip);
+ expect(scan).not.toBeNull();
+ expect(scan.max).toBeLessThan(UPRIGHT_TOLERANCE_DEG);
+ });
+ }
+
+ it('has teeth: the same rig without the correction tips over', () => {
+ const root = buildSyntheticRig({
+ armatureRot: rotZ(90),
+ hipsRot: rotZ(-90),
+ nameFor: identityName,
+ });
+ const verbatim = scanClip(root, 'celebrate', { withFix: false });
+ expect(verbatim).not.toBeNull();
+ expect(verbatim.max).toBeGreaterThan(CATASTROPHE_DEG);
+ });
+ });
+
+ // DEF-/snake_case bone names (Rigify / Blender exports) that still retarget.
+ describe('DEF-/snake_case bone names with a −90°X Hips', () => {
+ for (const clip of FEATURED) {
+ it(`${clip} maps the vendor names and stays upright`, () => {
+ const root = buildSyntheticRig({
+ armatureRot: rotX(90),
+ hipsRot: rotX(-90),
+ nameFor: snakeName,
+ });
+ const scan = scanClip(root, clip);
+ expect(scan).not.toBeNull();
+ expect(scan.max).toBeLessThan(UPRIGHT_TOLERANCE_DEG);
+ });
+ }
+ });
+
+ // A rig sharing too few canonical bones to perform the motion: retargetClip
+ // returns a null clip (coverage below MIN_COVERAGE). That means "this rig
+ // can't be driven", NOT a fallen pose — the corpus must handle it gracefully
+ // (no throw) and skip it.
+ describe('missing-bones rig (coverage below MIN_COVERAGE)', () => {
+ const FEW = ['Spine', 'Head', 'LeftArm']; // 4 of 52 canonical tracks map → < 0.5
+
+ it('retargets to a null clip rather than throwing or producing a fallen pose', () => {
+ const root = buildSyntheticRig({
+ armatureRot: rotX(90),
+ hipsRot: rotX(-90),
+ nameFor: identityName,
+ limbs: FEW,
+ });
+ const map = canonicalNodeMapFromObject(root);
+ const targetRest = canonicalRestMapFromObject(root);
+ const { clip, coverage } = retargetClip(CLIPS.get('celebrate'), map, { targetRest });
+ expect(coverage).toBeLessThan(MIN_COVERAGE);
+ expect(clip).toBeNull();
+ });
+
+ it('the corpus scan treats a null clip as skip (returns null, no tilt)', () => {
+ const root = buildSyntheticRig({
+ armatureRot: rotX(90),
+ hipsRot: rotX(-90),
+ nameFor: identityName,
+ limbs: FEW,
+ });
+ expect(() => scanClip(root, 'celebrate')).not.toThrow();
+ expect(scanClip(root, 'celebrate')).toBeNull();
+ });
+ });
+});
+
+// ── No-regression: cz.glb round-trips byte-for-byte ─────────────────────────
+
+describe('no-regression — cz.glb retarget is byte-for-byte the verbatim path', () => {
+ // cz IS the authoring convention (its Hips rest is identity), so the bind
+ // correction must be a no-op: every track's values must equal the verbatim
+ // path's. This is the shipped `cz: 1.7° → 1.7°` invariant in test form.
+ for (const clip of FEATURED) {
+ it(`${clip}: bind-correction output equals no-correction output, track for track`, () => {
+ const { root: r1 } = loadBoneGraph(avatar('cz.glb'));
+ const map = canonicalNodeMapFromObject(r1);
+ const targetRest = canonicalRestMapFromObject(r1);
+
+ const corrected = retargetClip(CLIPS.get(clip), map, { targetRest }).clip;
+ const verbatim = retargetClip(CLIPS.get(clip), map, { targetRest: new Map() }).clip;
+
+ expect(corrected).not.toBeNull();
+ expect(verbatim).not.toBeNull();
+
+ const names = corrected.tracks.map((t) => t.name);
+ expect(names).toEqual(verbatim.tracks.map((t) => t.name));
+
+ for (let i = 0; i < corrected.tracks.length; i++) {
+ expect(Array.from(corrected.tracks[i].values)).toEqual(
+ Array.from(verbatim.tracks[i].values),
+ );
+ }
+ });
+ }
+});
+
+// ── Runtime guard helper stays silent on healthy rigs ───────────────────────
+
+// Mirror of the runtime guard's pure measurement in src/animation-manager.js:
+// the at-rest (keyframe 0) Hips tilt, which is what the guard samples once per
+// clip. Proves the guard's >45° threshold never fires on a healthy retarget.
+describe('runtime guard is silent on healthy rigs (at-rest Hips tilt < 45°)', () => {
+ for (const [label, file] of [
+ ['cz.glb', 'cz.glb'],
+ ['michelle.glb (post-fix)', 'michelle.glb'],
+ ]) {
+ for (const clip of FEATURED) {
+ it(`${label} + ${clip}: at-rest tilt stays well under the 45° guard threshold`, () => {
+ const { root } = loadBoneGraph(avatar(file));
+ const scan = scanClip(root, clip);
+ expect(scan).not.toBeNull();
+ expect(scan.atKeyframe0).toBeLessThan(45);
+ });
+ }
+ }
+});
diff --git a/tests/api/irl-pins-mine-owner-scope.test.js b/tests/api/irl-pins-mine-owner-scope.test.js
new file mode 100644
index 000000000..62d9be451
--- /dev/null
+++ b/tests/api/irl-pins-mine-owner-scope.test.js
@@ -0,0 +1,143 @@
+// GET /api/irl/pins/mine — owner/device scoping (location-leak regression).
+//
+// The `/mine` feed returns COORDINATES (it's the placer's own pins, surfaced so
+// they can manage them without logging in). That makes its WHERE clause a
+// location-leak boundary: it must return a pin's lat/lng ONLY to the session that
+// owns it or the device token that placed it — never widen to another owner's
+// pins because an identifier was missing or empty.
+//
+// The bug this locks out: a `device_token = ${deviceToken ?? ''}` clause with no
+// null-guard. An authenticated caller with no deviceToken (or an empty one) would
+// run `device_token = ''`, matching every legacy NULL/empty-token anonymous pin —
+// leaking those placers' coordinates to anyone. The fixed query null-guards both
+// arms (`${id}::uuid IS NOT NULL AND user_id = …` / `${dev}::text IS NOT NULL AND
+// device_token = …`) so a missing identifier contributes an UNSATISFIABLE arm.
+//
+// DB / auth / limiter are mocked so the suite stays offline. We inspect the exact
+// parameters the `/mine` SELECT was interpolated with — proving the guard holds at
+// the query layer rather than trusting a mock's row shape.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Pins that would leak if the WHERE clause ever matched an empty/NULL identifier.
+const FOREIGN_PIN = {
+ id: 'pin-foreign', lat: 51.5, lng: -0.12, avatar_name: 'NotYours', caption: null,
+ placed_at: '2026-01-01T00:00:00Z', expires_at: null, view_count: 0,
+};
+const OWN_PIN = {
+ id: 'pin-own', lat: 40.0, lng: -73.0, avatar_name: 'Mine', caption: null,
+ placed_at: '2026-01-02T00:00:00Z', expires_at: null, view_count: 0,
+};
+
+// The `/mine` device/auth SELECT is the only query carrying both `FROM irl_pins`
+// and an `OR (... device_token = ...)` owner clause. Capture its interpolated
+// parameters so a test can prove what it would match in Postgres.
+let mineCall = null;
+let mineRows = [];
+const sqlMock = vi.fn((strings, ...values) => {
+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
+ if (/FROM\s+irl_pins/i.test(q) && /device_token\s*=/i.test(q) && /user_id\s*=/i.test(q) && /LIMIT 20/i.test(q)) {
+ mineCall = { q, values };
+ return Promise.resolve(mineRows);
+ }
+ return Promise.resolve([]);
+});
+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+let sessionUser = null;
+vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => sessionUser) }));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 60_000 })) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../../api/irl/pins.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ headersSent: false,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this.writableEnded = true; this._body = body; },
+ };
+}
+async function getMine({ query = {} } = {}) {
+ const res = makeRes();
+ await handler({ url: '/api/irl/pins/mine', method: 'GET', headers: { host: 'x' }, query }, res);
+ let body = null;
+ try { body = JSON.parse(res._body); } catch { /* non-JSON */ }
+ return { res, body };
+}
+
+beforeEach(() => {
+ sqlMock.mockClear();
+ mineCall = null;
+ mineRows = [];
+ sessionUser = null;
+});
+
+describe('GET /api/irl/pins/mine — requires an identifier', () => {
+ it('400s a caller with neither a session nor a device token, and never queries pins', async () => {
+ const { res } = await getMine({ query: {} });
+ expect(res.statusCode).toBe(400);
+ expect(mineCall).toBeNull();
+ });
+
+ it('400s when the device token is an empty string (no usable identifier)', async () => {
+ const { res } = await getMine({ query: { deviceToken: '' } });
+ expect(res.statusCode).toBe(400);
+ expect(mineCall).toBeNull();
+ });
+});
+
+describe('GET /api/irl/pins/mine — null-guarded owner scoping (no cross-user leak)', () => {
+ it('passes a NULL owner id (not an empty/guessable value) when the caller is anonymous', async () => {
+ // Anonymous device caller: the user_id arm must be NULL so it can never match a
+ // row whose user_id is NULL — only the device_token arm should be live.
+ const { res } = await getMine({ query: { deviceToken: 'dev-xyz' } });
+ expect(res.statusCode).toBe(200);
+ expect(mineCall).not.toBeNull();
+ // Params, in order: ownerId(null), ownerId(null), ownerDev, ownerDev — the
+ // guard interpolates each identifier twice (the `IS NOT NULL` check + the `=`).
+ expect(mineCall.values).toContain('dev-xyz');
+ // No empty-string identifier ever reaches the query — that was the leak.
+ expect(mineCall.values).not.toContain('');
+ // The owner-id arm is explicitly NULL for an anonymous caller.
+ expect(mineCall.values.filter((v) => v === null).length).toBeGreaterThanOrEqual(1);
+ });
+
+ it('passes a NULL device token (not "") when an authenticated caller omits deviceToken', async () => {
+ // The exact bug vector: signed-in user, no deviceToken param. The device arm
+ // must be NULL so `device_token = ''` can never surface other anonymous pins.
+ sessionUser = { id: 'owner-uuid-1' };
+ const { res } = await getMine({ query: {} });
+ expect(res.statusCode).toBe(200);
+ expect(mineCall).not.toBeNull();
+ expect(mineCall.values).toContain('owner-uuid-1');
+ // Crucially: NOT an empty string in the device-token slot.
+ expect(mineCall.values).not.toContain('');
+ });
+
+ it('scopes by session id and device token together for an authenticated placer', async () => {
+ sessionUser = { id: 'owner-uuid-2' };
+ mineRows = [OWN_PIN];
+ const { res, body } = await getMine({ query: { deviceToken: 'dev-abc' } });
+ expect(res.statusCode).toBe(200);
+ expect(mineCall.values).toContain('owner-uuid-2');
+ expect(mineCall.values).toContain('dev-abc');
+ expect(mineCall.values).not.toContain('');
+ expect(body.pins[0].id).toBe('pin-own');
+ });
+
+ it('filters out hidden and expired pins (the row leaves only for live, own pins)', async () => {
+ // The query the handler runs always carries the hidden/expired guards; assert
+ // they are present so a future edit can't quietly drop them.
+ await getMine({ query: { deviceToken: 'dev-abc' } });
+ expect(mineCall.q).toMatch(/hidden_at\s+IS\s+NULL/i);
+ expect(mineCall.q).toMatch(/expires_at\s+IS\s+NULL\s+OR\s+expires_at\s*>\s*NOW\(\)/i);
+ });
+});
diff --git a/tests/ar-anchor-lifecycle.test.js b/tests/ar-anchor-lifecycle.test.js
new file mode 100644
index 000000000..e93809b52
--- /dev/null
+++ b/tests/ar-anchor-lifecycle.test.js
@@ -0,0 +1,207 @@
+// WebXR floor-anchor lifecycle policy (src/ar/anchor-lifecycle.js).
+//
+// AR's production readiness is entirely about the unhappy paths — the device
+// loses tracking, the app gets backgrounded, an anchor can't be created, the
+// user taps before the first GPS fix. These tests pin every one of those rules
+// against plain values, with no XRSession, no Three.js, no real clock, so the
+// recovery behaviour is proven here rather than on a phone:
+// (1) tracking loss is transition-only and survives a one-frame blip;
+// (2) visibility classification matches the WebXR enum;
+// (3) placement copy is honest about a degraded (driftable) anchor;
+// (4) a placement's durable pin saves EXACTLY once — never zero, never twice —
+// whether the fix is live, lands later, or never comes (the headline
+// tap-during-GPS-warm-up scenario from task 05).
+
+import { describe, it, expect, vi } from 'vitest';
+
+import {
+ TRACKING_LOSS_FRAMES,
+ nextTrackingState,
+ XR_PAUSED_STATES,
+ isXrVisible,
+ placementHint,
+ createPersistGate,
+} from '../src/ar/anchor-lifecycle.js';
+
+describe('nextTrackingState — transition-only tracking loss', () => {
+ it('a single missed frame does not declare loss (blip tolerance)', () => {
+ const r = nextTrackingState({ misses: 0, lost: false }, false, 3);
+ expect(r.lost).toBe(false);
+ expect(r.changed).toBe(false);
+ expect(r.state).toEqual({ misses: 1, lost: false });
+ });
+
+ it('declares loss exactly when the miss streak reaches the threshold', () => {
+ let s = { misses: 0, lost: false };
+ let last;
+ for (let i = 0; i < 3; i++) {
+ last = nextTrackingState(s, false, 3);
+ s = last.state;
+ }
+ expect(last.lost).toBe(true);
+ expect(last.changed).toBe(true); // fires once, on the crossing frame
+ expect(s).toEqual({ misses: 3, lost: true });
+ });
+
+ it('stays lost without re-firing changed on subsequent pose-less frames', () => {
+ let s = { misses: 3, lost: true };
+ const r = nextTrackingState(s, false, 3);
+ expect(r.lost).toBe(true);
+ expect(r.changed).toBe(false); // already lost — no repeat callback
+ expect(r.state.misses).toBe(4);
+ });
+
+ it('recovers the instant a pose returns and fires changed once', () => {
+ const r = nextTrackingState({ misses: 5, lost: true }, true, 3);
+ expect(r.lost).toBe(false);
+ expect(r.changed).toBe(true); // lost → recovered transition
+ expect(r.state).toEqual({ misses: 0, lost: false });
+ });
+
+ it('a pose while already healthy is a no-op transition', () => {
+ const r = nextTrackingState({ misses: 0, lost: false }, true, 3);
+ expect(r.changed).toBe(false);
+ expect(r.state).toEqual({ misses: 0, lost: false });
+ });
+
+ it('a pose resets a partial miss streak below the threshold', () => {
+ const r = nextTrackingState({ misses: 2, lost: false }, true, 3);
+ expect(r.changed).toBe(false); // never crossed into lost
+ expect(r.state).toEqual({ misses: 0, lost: false });
+ });
+
+ it('tolerates a null prior state (fresh session)', () => {
+ const r = nextTrackingState(null, false, 3);
+ expect(r.state).toEqual({ misses: 1, lost: false });
+ expect(r.lost).toBe(false);
+ });
+
+ it('uses a sane default threshold (~0.5s at 60fps)', () => {
+ expect(TRACKING_LOSS_FRAMES).toBe(30);
+ let s = null;
+ for (let i = 0; i < TRACKING_LOSS_FRAMES - 1; i++) s = nextTrackingState(s, false).state;
+ expect(s.lost).toBe(false);
+ expect(nextTrackingState(s, false).lost).toBe(true);
+ });
+});
+
+describe('isXrVisible — interruption classification', () => {
+ it('only "visible" is foreground', () => {
+ expect(isXrVisible('visible')).toBe(true);
+ });
+
+ it('hidden and visible-blurred are paused', () => {
+ expect(isXrVisible('hidden')).toBe(false);
+ expect(isXrVisible('visible-blurred')).toBe(false);
+ expect([...XR_PAUSED_STATES].sort()).toEqual(['hidden', 'visible-blurred']);
+ });
+
+ it('an unknown/undefined state is treated as visible (fail-open, never stuck paused)', () => {
+ expect(isXrVisible(undefined)).toBe(true);
+ expect(isXrVisible('')).toBe(true);
+ });
+});
+
+describe('placementHint — degraded-anchor honesty', () => {
+ it('a solid anchor reads as rock-solid', () => {
+ const hint = placementHint(false);
+ expect(hint).toContain('stays put');
+ expect(hint).not.toMatch(/drift/i);
+ });
+
+ it('a degraded anchor discloses possible drift', () => {
+ expect(placementHint(true)).toMatch(/drift/i);
+ });
+});
+
+describe('createPersistGate — the durable pin saves EXACTLY once', () => {
+ it('a tap with a live fix persists immediately, holds nothing', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+ const pose = { id: 'p1' };
+
+ expect(gate.place(pose, true)).toBe('persisted');
+ expect(persist).toHaveBeenCalledTimes(1);
+ expect(persist).toHaveBeenCalledWith(pose);
+ expect(gate.hasPending()).toBe(false);
+
+ // A later fix has nothing to drain — no double-save.
+ expect(gate.onFix(true)).toBe(false);
+ expect(persist).toHaveBeenCalledTimes(1);
+ });
+
+ it('the headline path: tap during GPS warm-up → held → first fix → saved once', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+ const pose = { id: 'warmup' };
+
+ // Tap before the fix — held, NOT saved (zero so far).
+ expect(gate.place(pose, false)).toBe('held');
+ expect(persist).not.toHaveBeenCalled();
+ expect(gate.hasPending()).toBe(true);
+
+ // First GPS fix lands — drains exactly once.
+ expect(gate.onFix(true)).toBe(true);
+ expect(persist).toHaveBeenCalledTimes(1);
+ expect(persist).toHaveBeenCalledWith(pose);
+ expect(gate.hasPending()).toBe(false);
+
+ // A second fix (every subsequent GPS update calls onFix) must NOT re-save.
+ expect(gate.onFix(true)).toBe(false);
+ expect(persist).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaving before the fix drops the held pose — never a surprise late pin', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+
+ gate.place({ id: 'abandoned' }, false);
+ expect(gate.hasPending()).toBe(true);
+
+ gate.drop(); // user exits the session
+ expect(gate.hasPending()).toBe(false);
+
+ expect(gate.onFix(true)).toBe(false); // a fix arrives after they walked away
+ expect(persist).not.toHaveBeenCalled(); // zero saves — correct
+ });
+
+ it('onFix is inert until a fix is actually ready', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+ gate.place({ id: 'held' }, false);
+
+ expect(gate.onFix(false)).toBe(false); // not ready yet
+ expect(persist).not.toHaveBeenCalled();
+ expect(gate.hasPending()).toBe(true); // still held for the real fix
+
+ expect(gate.onFix(true)).toBe(true);
+ expect(persist).toHaveBeenCalledTimes(1);
+ });
+
+ it('onFix with nothing pending is a harmless no-op (every GPS tick calls it)', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+ for (let i = 0; i < 5; i++) expect(gate.onFix(true)).toBe(false);
+ expect(persist).not.toHaveBeenCalled();
+ });
+
+ it('drop is idempotent and safe when nothing is held', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+ gate.drop();
+ gate.drop();
+ expect(gate.hasPending()).toBe(false);
+ expect(persist).not.toHaveBeenCalled();
+ });
+
+ it('passes the full payload through so degraded honesty survives the warm-up wait', () => {
+ const persist = vi.fn();
+ const gate = createPersistGate(persist);
+ const payload = { pose: { position: { y: -1.4 } }, degraded: true };
+
+ gate.place(payload, false);
+ gate.onFix(true);
+ expect(persist).toHaveBeenCalledWith(payload);
+ expect(persist.mock.calls[0][0].degraded).toBe(true);
+ });
+});
diff --git a/workers/agent-sniper/alerts.js b/workers/agent-sniper/alerts.js
new file mode 100644
index 000000000..04dccd1ad
--- /dev/null
+++ b/workers/agent-sniper/alerts.js
@@ -0,0 +1,83 @@
+// agent-sniper — ops alerting.
+//
+// Thin wrapper over the platform's shared ops-alert pipeline
+// (api/_lib/alerts.js → Telegram TELEGRAM_ALERTS_CHAT_ID). That module already
+// owns the dedup-per-signature-per-hour and global-ceiling throttle, the 2.5s
+// fire-and-forget timeout, and the [env] prefix — so a sustained feed outage
+// pages once an hour, not every reconnect, and an alert storm can never wedge
+// the trade loop.
+//
+// The trade-success / position-exit notifications are a SEPARATE channel
+// (api/_lib/sniper/notify.js — TELEGRAM_SNIPER_CHAT_ID): those are product
+// signal for the strategy owner. THIS module is for OPERATORS — "the worker is
+// in trouble" (silent feed, repeated RPC failures, executor crashes, boot,
+// shutdown). Distinct so a busy snipe day never drowns out a dead feed.
+//
+// Signatures are stable strings so the same failure dedups; transient detail
+// (counts, ages) goes in the body, never the signature.
+
+import { sendOpsAlert } from '../../api/_lib/alerts.js';
+import { log } from './log.js';
+
+const PREFIX = '🎯 agent-sniper';
+
+function alert(title, detail, signature) {
+ // sendOpsAlert is best-effort and swallows its own errors, but guard anyway:
+ // alerting must never throw into the worker's control loop.
+ Promise.resolve(sendOpsAlert(`${PREFIX} — ${title}`, detail, { signature })).catch(() => {});
+}
+
+/** The feed went silent past the watchdog threshold and we re-subscribed. */
+export function alertFeedSilent({ silentMs, network, mode }) {
+ alert(
+ 'feed silent — re-subscribing',
+ `No PumpPortal events for ${Math.round(silentMs / 1000)}s on ${network} (${mode}). Re-subscribed; if this repeats the upstream feed or egress is degraded.`,
+ 'sniper:feed-silent',
+ );
+}
+
+/** The feed dropped and exhausted its internal reconnect budget. */
+export function alertFeedDown({ network, mode }) {
+ alert(
+ 'feed connection down',
+ `PumpPortal subscription closed and the worker re-subscribed from scratch on ${network} (${mode}). Nothing is scored while the feed is down.`,
+ 'sniper:feed-down',
+ );
+}
+
+/** Executor / RPC errors crossed the run-window threshold. */
+export function alertErrorSpike({ count, windowMs, lastError, network, mode }) {
+ alert(
+ 'executor error spike',
+ `${count} executor/RPC errors in the last ${Math.round(windowMs / 60000)}m on ${network} (${mode}). Last: ${lastError || 'unknown'}. Check the RPC endpoint and agent-wallet funding.`,
+ 'sniper:error-spike',
+ );
+}
+
+/** A heartbeat write to Postgres failed repeatedly — the worker is flying blind. */
+export function alertHeartbeatStale({ network, mode }) {
+ alert(
+ 'heartbeat write failing',
+ `The sniper cannot write its liveness heartbeat to Postgres on ${network} (${mode}). /status will show it as stale even if trading is fine — fix the DB connection.`,
+ 'sniper:heartbeat-stale',
+ );
+}
+
+/** The worker booted. Confirms a deploy/restart actually came back up. */
+export function alertBoot({ network, mode, globalKill }) {
+ alert(
+ 'worker started',
+ `Sniper online — network=${network} mode=${mode}${globalKill ? ' [GLOBAL KILL]' : ''}.`,
+ `sniper:boot:${Date.now()}`, // unique: every boot should announce
+ );
+ log.info('boot alert sent', { network, mode });
+}
+
+/** The worker is shutting down (deploy, scale-in, SIGTERM). */
+export function alertShutdown({ signal, inFlight }) {
+ alert(
+ 'worker stopping',
+ `Sniper received ${signal}; draining ${inFlight} in-flight buy(s). Cloud Run will start a fresh revision.`,
+ `sniper:shutdown:${Date.now()}`,
+ );
+}
diff --git a/workers/agent-sniper/heartbeat.js b/workers/agent-sniper/heartbeat.js
new file mode 100644
index 000000000..403e5edbe
--- /dev/null
+++ b/workers/agent-sniper/heartbeat.js
@@ -0,0 +1,81 @@
+// agent-sniper — liveness heartbeat.
+//
+// A long-lived worker that holds a websocket feed open has one catastrophic
+// failure mode: it stays UP but goes silent — the process is alive, the feed is
+// dead, and nothing snipes. A crash is loud (Cloud Run restarts it); a silent
+// dead feed is invisible. The heartbeat makes "is the sniper actually working?"
+// answerable from the outside without SSHing into the instance.
+//
+// We reuse the existing `bot_heartbeat` table (migration 2026-06-01-pump-alerts)
+// — the same row shape the pumpfun-monitor cron uses and /api/healthz already
+// reads — keyed `worker='agent-sniper'`. `last_beat_at` is the liveness clock;
+// `meta` carries the operational truth the status endpoint surfaces:
+//
+// mode simulate | live
+// network mainnet | devnet
+// feedConnected is the PumpPortal subscription currently up
+// lastEventAgeMs how long since the last feed event (silence detector)
+// strategies active armed strategies the worker is watching
+// globalKill is the new-buy kill switch engaged
+// reconnects cumulative feed re-subscribes since boot
+// errors cumulative executor/RPC errors since boot
+// bootAt process start (for uptime)
+//
+// Best-effort: a DB blip must never crash the trade loop, so every write is
+// guarded. Secrets are never written here.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+
+const WORKER = 'agent-sniper';
+
+/**
+ * Upsert the sniper's heartbeat row. Fire-and-forget safe — swallows DB errors
+ * (a transient Neon blip must not take down the worker), but logs them so a
+ * sustained DB outage is visible in the worker's own logs.
+ *
+ * @param {string} mode simulate | live
+ * @param {() => object} snapshot returns the current operational meta
+ */
+export async function writeHeartbeat(mode, meta) {
+ try {
+ await sql`
+ INSERT INTO bot_heartbeat (worker, mode, last_beat_at, meta)
+ VALUES (${WORKER}, ${mode}, now(), ${JSON.stringify(meta || {})}::jsonb)
+ ON CONFLICT (worker) DO UPDATE
+ SET mode = excluded.mode,
+ last_beat_at = excluded.last_beat_at,
+ meta = excluded.meta
+ `;
+ } catch (err) {
+ log.warn('heartbeat write failed', { err: err?.message });
+ }
+}
+
+/**
+ * Start a heartbeat loop. Writes immediately, then every `intervalMs`. Returns a
+ * stop function. `getMeta` is called on every beat so the row always reflects
+ * the live operational state (feed up?, silence age, active strategies, error
+ * counts) rather than a stale boot snapshot.
+ *
+ * @param {object} opts
+ * @param {string} opts.mode
+ * @param {number} opts.intervalMs
+ * @param {() => object} opts.getMeta
+ * @returns {() => void} stop
+ */
+export function startHeartbeat({ mode, intervalMs, getMeta }) {
+ const beat = () => writeHeartbeat(mode, safeMeta(getMeta));
+ beat();
+ const timer = setInterval(beat, intervalMs);
+ if (typeof timer.unref === 'function') timer.unref();
+ return () => clearInterval(timer);
+}
+
+function safeMeta(getMeta) {
+ try {
+ return getMeta() || {};
+ } catch {
+ return {};
+ }
+}