Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add IRL proximity arrival cue, presence privacy; sniper positions, wallet
nirholasb4d5c5d76818
diff --git a/api/cron/irl-reap.js b/api/cron/irl-reap.jsindex 724c0d8d1..7dece560c 100644--- a/api/cron/irl-reap.js+++ b/api/cron/irl-reap.js@@ -10,6 +10,24 @@// IS NULL) are NEVER reaped.// 2. Reports tied to pins that no longer exist — once the pin is gone the report// trail is moot, so it's purged to keep irl_pin_reports bounded.+// 3. Interactions (taps/views/messages/pays) whose pin is gone, and interactions+// older than the retention window regardless of pin state. An interaction row+// is a record that "device X was at coordinate Y at time T" (it snapshots the+// pin's lat/lng + a viewer_device), so it is exactly the location trail data+// minimization should not let accumulate. We cascade-delete it the moment its+// pin dies, and age it out at INTERACTION_RETENTION_DAYS so even a permanent+// (signed-in) pin's encounter trail can't grow unbounded.+//+// Retention window — interactions: 180 days. Rationale: long enough that an owner's+// dashboard inbox + the earnings history a `pay` row backs stay useful across a+// reasonable review horizon, short enough that the location trail has a hard, known+// ceiling. The geo-bearing columns (lat/lng) duplicate the pin's own location and+// are kept only for the lifetime of the row precisely because the row is bounded by+// this window + the orphan cascade; we age out the raw row rather than null its+// coordinates so nothing about a months-old encounter survives. `pay` rows age out+// on the same clock — the durable earnings signal an owner cares about is recent,+// and a 180-day-old settlement is already on-chain (the source of truth), so we do+// not keep a stale geo-tagged copy of it indefinitely.//// Hidden pins are NOT deleted here: a moderation-hidden pin is queued for review +// owner appeal, not garbage. It's reaped only when its own expiry passes (anon) or@@ -47,10 +65,11 @@ export default wrap(async (req, res) => {// they may not exist yet. A reaper that hard-depended on them would throw// `relation does not exist` and 500 the hourly cron. Probe with to_regclass// and treat a missing table as "nothing to reap" rather than an error.- const [{ pins, reports }] = await sql`+ const [{ pins, reports, interactions }] = await sql`SELECT- to_regclass('public.irl_pins') AS pins,- to_regclass('public.irl_pin_reports') AS reports+ to_regclass('public.irl_pins') AS pins,+ to_regclass('public.irl_pin_reports') AS reports,+ to_regclass('public.irl_interactions') AS interactions`;// Expired anon pins, ≥ 1 day past expiry. expires_at IS NULL ⇒ permanent ⇒ kept.@@ -76,10 +95,37 @@ export default wrap(async (req, res) => {: await sql`DELETE FROM irl_pin_reports RETURNING id`;}+ // Interactions — the location trail. Two sweeps, both existence-guarded so a+ // fresh DB never 500s:+ // a. orphaned — the pin is gone, so the encounter record is moot (mirrors the+ // report orphan sweep). With no pins table at all, every interaction is an+ // orphan, so purge them all.+ // b. aged-out — older than the retention window regardless of pin state, so a+ // permanent pin's trail can't accumulate forever.+ // A single re-run after a clean sweep deletes nothing new (idempotent): both+ // predicates are empty once the table holds only live, in-window rows.+ let reapedInteractions = [];+ if (interactions) {+ const orphaned = pins+ ? await sql`+ DELETE FROM irl_interactions ix+ WHERE NOT EXISTS (SELECT 1 FROM irl_pins p WHERE p.id = ix.pin_id)+ RETURNING ix.id+ `+ : await sql`DELETE FROM irl_interactions RETURNING id`;+ const aged = await sql`+ DELETE FROM irl_interactions+ WHERE created_at < NOW() - INTERVAL '180 days'+ RETURNING id+ `;+ reapedInteractions = [...orphaned, ...aged];+ }+return json(res, 200, {ok: true,reapedPins: reapedPins.length,reapedReports: reapedReports.length,+ reapedInteractions: reapedInteractions.length,ts: Date.now(),});});diff --git a/api/irl/interactions.js b/api/irl/interactions.jsindex c4d63d2d4..12aaf0fc4 100644--- a/api/irl/interactions.js+++ b/api/irl/interactions.js@@ -24,6 +24,17 @@* Returns newest-first, joined with the pin's avatar name + caption.** GET /api/irl/interactions?pinId=<id> — public count for one pin+ *+ * ── Retention / data-minimization (H6) ───────────────────────────────────────+ * Each row snapshots the pin's lat/lng + a viewer_device, so it's a location trail+ * ("device X was at coordinate Y at time T") that must not accumulate. The hourly+ * reaper (api/cron/irl-reap.js) cascade-deletes a row the moment its pin is gone and+ * ages out any row older than 180 days regardless of pin state, so even a permanent+ * pin's encounter trail is bounded. The created_at index below keeps that age-out+ * sweep index-backed. The lat/lng columns duplicate the pin's own location, but they+ * earn their keep: the owner inbox + the SSE stream render the row WITHOUT joining+ * back to a possibly-deleted pin, and the row is bounded by the reaper above — so we+ * keep the geo snapshot on the (short-lived) row rather than re-deriving it on read.*/import { cors, json, wrap, rateLimited } from '../_lib/http.js';@@ -109,6 +120,8 @@ async function ensureTable() {`;await sql`CREATE INDEX IF NOT EXISTS irl_interactions_pin ON irl_interactions (pin_id, created_at DESC)`;await sql`CREATE INDEX IF NOT EXISTS irl_interactions_viewer ON irl_interactions (viewer_device, pin_id, type)`;+ // Index-backs the reaper's age-out sweep (DELETE … WHERE created_at < NOW() - 180d).+ await sql`CREATE INDEX IF NOT EXISTS irl_interactions_created ON irl_interactions (created_at)`;// Earnings columns (C4) — populated for type='pay'. amount is in the asset's// atomic units; currency_mint is $THREE or USDC; payload carries the on-chain// signature, network, and any structured context (geo, settlement detail).diff --git a/multiplayer/src/irl-schemas.js b/multiplayer/src/irl-schemas.jsindex 6d9a2ed38..40ae9c5cb 100644--- a/multiplayer/src/irl-schemas.js+++ b/multiplayer/src/irl-schemas.js@@ -3,10 +3,18 @@// it bundles walk's schemas.js).//// @colyseus/schema uses delta encoding: only fields that changed since the last-// patch ride the wire, and a late joiner receives the full current set on join-// for free. That delta sync is exactly what makes the pin set LIVE — a placed /-// moved / removed pin is a one-entry patch the room broadcasts to everyone in the-// geocell, and a fresh viewer is handed the whole MapSchema on connect.+// patch ride the wire, and a late joiner receives the full current set on join.+// This room delta-syncs PRESENCE (the `viewers` map) and broadcasts ambient+// REACTIONS — it does NOT sync pins. Placed agents are private by location and are+// discovered ONLY through the per-viewer /api/irl/pins proximity read (REST), never+// broadcast here as a roster (see IrlRoom.js, which never writes IrlState.pins).+//+// The IrlPin schema + IrlState.pins map below are therefore DORMANT: declared but+// never populated by the server and never read by the client (src/irl-net.js+// consumes viewers + reactions only). They are retained — not deleted — because+// @colyseus/schema's binary protocol is POSITIONAL: removing IrlPin or the `pins`+// field would shift every later field's index and break any client still connected+// to an older deployed server mid-deploy. They cost nothing on the wire while empty.//// IMPORTANT: append-only. Field indices are positional in @colyseus/schema's// binary protocol — inserting in the middle shifts every later index and breaks@@ -14,11 +22,10 @@import { Schema, MapSchema, defineTypes } from '@colyseus/schema';-// One placed 3D agent anchored at a real-world GPS coordinate. Keyed in the pins-// MapSchema by its pin id (the Neon row UUID), so a place/move/remove is a single-// MapSchema patch. lat/lng are float64 — float32 quantizes a degree to ~1 m of-// error, which is fine for distance but loses the precision a placement actually-// stored, so we pay the extra bytes for an honest coordinate.+// DORMANT (see header): a placed 3D agent's wire shape. Never populated by the+// server — pins ride the REST proximity read, not this socket — and never read by+// the client. Kept only to preserve the positional binary layout across deploys.+// lat/lng are float64 to carry an honest coordinate had this ever synced.export class IrlPin extends Schema {constructor() {super();@@ -105,9 +112,9 @@ defineTypes(IrlViewer, {export class IrlState extends Schema {constructor() {super();- // The set of pins in this room's 3×3 geocell window (centre cell + up to 8- // neighbours), keyed by pin id. This is the live, delta-synced collection- // the client reconciles into its scene.+ // DORMANT (see header): retained for binary-layout stability only. The server+ // never writes to this map and the client never reads it — pins are private by+ // location and ride the per-viewer /api/irl/pins proximity read, not this socket.this.pins = new MapSchema();// The centre geocell this room instance serves (filterBy key). Seeded by the// first client to land here; identical for every viewer in the instance.diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex 3ced266d6..172e53496 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -35,11 +35,6 @@<link rel="stylesheet" href="/fonts/fonts.css" /><link rel="stylesheet" href="/src/agent-detail.css" /><link rel="stylesheet" href="/src/pump/launch-token-modal.css" />- <script- src="https://cdnjs.cloudflare.com/ajax/libs/qrious/4.0.2/qrious.min.js"- integrity="sha384-Dr98ddmUw2QkdCarNQ+OL7xLty7cSxgR0T7v1tq4UErS/qLV0132sBYTolRAFuOV"- crossorigin="anonymous"- ></script><style>.ad-main.loading .ad-hero-avatar,.ad-main.loading .ad-hero-body > *,@@ -429,17 +424,7 @@</button></div><div class="ad-balance"><span id="ad-holdings-sol">0</span> SOL</div>- <div class="flex space-x-2 mt-4 justify-start" id="ad-holdings-actions">- <button id="receive-btn" class="ad-btn">Receive</button>- <button id="withdraw-btn" class="ad-btn">Withdraw</button>- <button id="swap-btn" class="ad-btn">Swap</button>- </div>- <div- id="qr-code-container"- class="hidden mt-4 p-4 bg-white rounded-lg shadow-md inline-block"- >- <canvas id="qr-code"></canvas>- </div>+ <div class="flex space-x-2 mt-4 justify-start" id="ad-holdings-actions"></div></section><section class="ad-card">diff --git a/public/features.json b/public/features.jsonindex f101d97e3..f14f8a9fe 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T12:30:50.044Z",+ "generated_at": "2026-06-17T12:37:32.782Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/sniper-backfill-graduated.mjs b/scripts/sniper-backfill-graduated.mjsnew file mode 100644index 000000000..4e01f0cb8--- /dev/null+++ b/scripts/sniper-backfill-graduated.mjs@@ -0,0 +1,100 @@+#!/usr/bin/env node+/**+ * sniper-backfill-graduated.mjs — exit any sniper position parked on a graduated+ * coin through the pump AMM pool.+ *+ * Before the AMM-exit path existed, a position whose coin graduated off the+ * bonding curve was flagged `error='graduated:awaiting_amm_exit'` and left open+ * indefinitely — the bonding-curve sell could no longer price it. The live+ * worker now re-quotes such positions off the AMM and exits them when an exit+ * rule fires, so they no longer park. This one-shot drives that same machinery+ * on demand (e.g. right after deploy) instead of waiting for the worker's poll+ * cadence, and clears any pre-existing backlog.+ *+ * It runs the REAL production sweep (workers/agent-sniper/positions.js →+ * runPositionSweep), which:+ * • includes graduated positions in its work set (strategy-store.getOpenPositions),+ * • re-quotes each off the canonical AMM pool (amm-exit.quoteAmmSell),+ * • fires stop-loss / trailing / take-profit / timeout against the real+ * post-graduation price, and exits via the AMM (executor.buildGraduatedSell).+ *+ * Idempotent: executeSell flips status to closing→closed, so re-running never+ * double-sells. Honors SNIPER_MODE (simulate = paper exit, the default).+ *+ * Usage:+ * SNIPER_MODE=simulate node scripts/sniper-backfill-graduated.mjs+ * SNIPER_MODE=live SOLANA_RPC_URL=... node scripts/sniper-backfill-graduated.mjs+ * node scripts/sniper-backfill-graduated.mjs --max-sweeps 8+ *+ * Env: DATABASE_URL + JWT_SECRET (required); SNIPER_NETWORK (default mainnet);+ * SNIPER_MODE (default simulate); SOLANA_RPC_URL / HELIUS_API_KEY (live).+ */++import { loadConfig } from '../workers/agent-sniper/config.js';+import { runPositionSweep } from '../workers/agent-sniper/positions.js';+import { sql } from '../api/_lib/db.js';++function arg(flag, def) {+ const i = process.argv.indexOf(flag);+ if (i === -1 || i === process.argv.length - 1) return def;+ return process.argv[i + 1];+}++async function countParked(network) {+ const [r] = await sql`+ SELECT count(*)::int AS n FROM agent_sniper_positions+ WHERE network = ${network} AND status = 'open' AND error LIKE 'graduated%'+ `;+ return r?.n ?? 0;+}++async function main() {+ const cfg = loadConfig();+ const maxSweeps = Math.max(1, Number(arg('--max-sweeps', '6')) || 6);++ const before = await countParked(cfg.network);+ console.log(+ `[backfill] network=${cfg.network} mode=${cfg.mode} parked(graduated)=${before}`,+ );+ if (before === 0) {+ console.log('[backfill] nothing parked — done.');+ return;+ }++ // Run sweeps until the parked set stops shrinking or the cap is hit. A single+ // sweep re-quotes every open position (including graduated ones) and exits the+ // ones whose triggers fire; a long-parked position satisfies its timeout+ // immediately, so most clear on the first pass. Extra passes catch transient+ // RPC failures on the previous one.+ let remaining = before;+ for (let i = 1; i <= maxSweeps; i++) {+ await runPositionSweep(cfg);+ const now = await countParked(cfg.network);+ console.log(`[backfill] sweep ${i}: parked ${remaining} → ${now}`);+ if (now === 0) {+ console.log('[backfill] all graduated positions exited.');+ return;+ }+ if (now >= remaining) {+ // No progress this pass — the rest are held by exit rules that haven't+ // fired yet (e.g. a graduated coin still inside its hold window with no+ // stop hit). The live worker will exit them when a trigger fires; this is+ // not a stuck state. Report and stop.+ console.log(+ `[backfill] ${now} graduated position(s) still open but holding (no exit trigger met). ` ++ 'The worker will exit them when stop-loss/trailing/take-profit/timeout fires.',+ );+ return;+ }+ remaining = now;+ }+ const left = await countParked(cfg.network);+ console.log(`[backfill] stopped after ${maxSweeps} sweeps; ${left} still open (holding).`);+}++main()+ .then(() => process.exit(0))+ .catch((err) => {+ console.error('[backfill] fatal:', err?.message || err);+ process.exit(1);+ });diff --git a/src/account.js b/src/account.jsindex bef2fd468..4a15b226e 100644--- a/src/account.js+++ b/src/account.js@@ -153,7 +153,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {const { canonicalizeGLBBones } = await import('./glb-canonicalize.js');const buf = await blob.arrayBuffer();const result = canonicalizeGLBBones(buf);- if (result.renamed > 0) {+ if (result.renamed > 0 || result.orientationCorrected) {blob = new Blob([result.buffer], { type: 'model/gltf-binary' });retargetedBoneCount = result.renamed;}diff --git a/src/agent-detail.js b/src/agent-detail.jsindex e38650c5f..cf3a67f41 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -24,14 +24,12 @@ const solanaWeb3 = {LAMPORTS_PER_SOL,clusterApiUrl,};-import { openSwapModal } from './swap-jupiter.js';import { onchainBadgeEl } from './shared/onchain-badge.js';import { mountValidationBadge } from './shared/validation-badge.js';import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';import { renderError as renderAsyncError } from './shared/async-state.js';import { skeletonHTML } from './shared/state-kit.js';import { openCoinLaunch } from './shared/agent-coin.js';-import { Modal } from './shared/modal.js';import { showSharePanel } from './shared/share.js';import { enrichAgentDetail, renderEmbed as renderAgentEmbed } from './agent-detail-market.js';import { log } from './shared/log.js';@@ -741,7 +739,7 @@ function render(agent) {}document.querySelector('.ad-main').classList.remove('loading');- bindWalletActions(agent.isOwner);+ bindWalletActions(agent);mountOwnerBar(agent);wireShareButton(agent);@@ -1454,115 +1452,6 @@ function renderEmbedPolicy(p) {card.style.display = '';}-const SOL_NAME_RE = /^[a-z0-9-]{1,63}(?:\.[a-z0-9-]{1,63})*(?:\.sol)?$/i;-const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;--// In-flight resolution token — used by both the typeahead and the confirm-// handler so the latter doesn't fire while a lookup is still pending and so a-// stale typeahead response can't overwrite a newer one.-function makeSnsResolver(inputEl, statusEl) {- let seq = 0;- let lastInput = '';- let lastResolved = null; // { name: 'foo.sol', address: 'BASE58' } | { name: null, address: 'raw' } | null- let pending = null;-- function setStatus(kind, text) {- statusEl.hidden = !text;- statusEl.textContent = text || '';- statusEl.className = `ad-resolved${kind ? ` ${kind}` : ''}`;- }-- async function lookup(name) {- const myId = ++seq;- pending = (async () => {- try {- const r = await fetch(`/api/sns?name=${encodeURIComponent(name)}`, {- credentials: 'include',- });- if (myId !== seq) return null; // superseded- if (!r.ok) {- const j = await r.json().catch(() => ({}));- setStatus('warn', j?.error_description || `lookup failed (${r.status})`);- lastResolved = null;- return null;- }- const { data } = await r.json();- if (myId !== seq) return null;- // A miss is now a 200 with `resolved: false` / `address: null`, not a 404.- if (!data?.address) {- setStatus('warn', `${name} does not resolve`);- lastResolved = null;- return null;- }- setStatus('ok', `→ ${data.address}`);- lastResolved = { name: data.name, address: data.address };- return lastResolved;- } catch (err) {- if (myId === seq) setStatus('warn', err.message || 'lookup failed');- return null;- } finally {- if (myId === seq) pending = null;- }- })();- return pending;- }-- function onInput() {- const raw = inputEl.value.trim();- if (raw === lastInput) return;- lastInput = raw;- seq++; // invalidate any in-flight lookup- pending = null;- lastResolved = null;-- if (!raw) {- setStatus('', '');- return;- }- if (SOL_ADDR_RE.test(raw)) {- lastResolved = { name: null, address: raw };- setStatus('', '');- return;- }- if (/\.sol$/i.test(raw) || (SOL_NAME_RE.test(raw) && !SOL_ADDR_RE.test(raw))) {- setStatus('loading', 'Resolving .sol…');- // debounce briefly so we don't fire for every keystroke- const myId = seq;- setTimeout(() => {- if (myId !== seq) return;- lookup(raw);- }, 300);- return;- }- setStatus('warn', 'Not a valid Solana address or .sol name');- }-- async function resolveForSubmit() {- // If a lookup is in flight, wait for it.- if (pending) await pending;- const raw = inputEl.value.trim();- if (!raw) return null;- if (lastResolved?.address) return lastResolved.address;- if (SOL_ADDR_RE.test(raw)) return raw;- if (/\.sol$/i.test(raw) || SOL_NAME_RE.test(raw)) {- const r = await lookup(raw);- return r?.address || null;- }- return null;- }-- function reset() {- seq++;- pending = null;- lastInput = '';- lastResolved = null;- setStatus('', '');- }-- inputEl.addEventListener('input', onInput);- return { resolveForSubmit, reset };-}-function wireShareButton(agent) {const origin = location.origin;const shareUrl = `${origin}/agent/${agent.id}/share`;@@ -1760,149 +1649,40 @@ async function openDeployModalFromDetail(agent) {}}-function bindWalletActions(isOwner) {- // Receive / Withdraw / Swap act on funds the viewer controls, not the agent's- // on-chain wallet — there is no client-side key for the agent address. Showing- // them under AGENT HOLDINGS on agents the viewer doesn't own misrepresents what- // they do (it reads as "move the agent's SOL"). Server-side ownership is the- // authoritative signal: /api/agents/:id only returns user_id to the owner, which- // is what `isOwner` reflects. Hide the actions for everyone else; the balance and- // address above stay visible as read-only info.+function bindWalletActions(agent) {+ // AGENT HOLDINGS shows the agent's custodial Solana address + balance as+ // read-only info for everyone. Funding, trading, paying, and withdrawing the+ // agent's OWN custodial wallet all live in one place — the Agent Wallet hub+ // (/agent/:id/wallet) — so this card just links there for the owner. The hub+ // owns every wallet action; the detail page no longer re-implements them.const actions = document.getElementById('ad-holdings-actions');- if (!isOwner) {- if (actions) actions.style.display = 'none';- return;- }+ if (!actions) return;- const receiveBtn = document.getElementById('receive-btn');- const withdrawBtn = document.getElementById('withdraw-btn');- const swapBtn = document.getElementById('swap-btn');+ const isOwner = !!(agent?.isOwner ?? agent?.is_owner);+ // The legacy Receive QR popover lives in the same card; the hub's Deposit tab+ // supersedes it, so keep it hidden whether or not the user owns the agent.const qrCodeContainer = document.getElementById('qr-code-container');- const qrCodeCanvas = document.getElementById('qr-code');- const walletAddressSpan = document.getElementById('ad-holdings-addr');-- receiveBtn.addEventListener('click', () => {- const walletAddress = walletAddressSpan.dataset.full;- if (walletAddress) {- qrCodeContainer.classList.toggle('hidden');- if (!qrCodeContainer.classList.contains('hidden')) {- new QRious({- element: qrCodeCanvas,- value: walletAddress,- size: 160,- });- }- }- });+ if (qrCodeContainer) qrCodeContainer.classList.add('hidden');- // Build the withdraw modal using the shared Modal primitive- const bodyEl = document.createElement('div');- bodyEl.innerHTML = `- <div class="ad-form-group">- <label for="withdraw-amount">Amount (SOL)</label>- <input type="number" id="withdraw-amount" class="ad-input" placeholder="0.0">- </div>- <div class="ad-form-group">- <label for="recipient-address">Recipient address or .sol name</label>- <input type="text" id="recipient-address" class="ad-input"- placeholder="Wallet address or yourname.sol" autocomplete="off" spellcheck="false">- <div id="recipient-resolved" class="ad-resolved" hidden></div>- </div>- `;-- const actionsEl = document.createElement('div');- actionsEl.innerHTML = `- <button id="cancel-withdraw-btn" class="ad-btn" type="button">Cancel</button>- <button id="confirm-withdraw-btn" class="ad-btn ad-btn-primary" type="button">Confirm Withdraw</button>- `;-- const withdrawModal = new Modal({- title: 'Withdraw SOL',- body: bodyEl,- actions: actionsEl,- });-- const withdrawAmountInput = withdrawModal.bodyEl.querySelector('#withdraw-amount');- const recipientAddressInput = withdrawModal.bodyEl.querySelector('#recipient-address');- const recipientResolvedEl = withdrawModal.bodyEl.querySelector('#recipient-resolved');- const cancelWithdrawBtn = withdrawModal.actionsEl.querySelector('#cancel-withdraw-btn');- const confirmWithdrawBtn = withdrawModal.actionsEl.querySelector('#confirm-withdraw-btn');- const snsResolver = makeSnsResolver(recipientAddressInput, recipientResolvedEl);-- withdrawBtn.addEventListener('click', () => {- withdrawModal.open(withdrawBtn);- });-- cancelWithdrawBtn.addEventListener('click', () => {- withdrawModal.close();- });-- confirmWithdrawBtn.addEventListener('click', async () => {- if (!wallet) {- alert('Please connect your wallet first.');- return;- }-- const amount = parseFloat(withdrawAmountInput.value);- const typedRecipient = recipientAddressInput.value.trim();-- if (isNaN(amount) || amount <= 0) {- alert('Please enter a valid amount.');- return;- }-- if (!typedRecipient) {- alert('Please enter a recipient address.');- return;- }-- confirmWithdrawBtn.disabled = true;- try {- const recipientAddress = await snsResolver.resolveForSubmit();- if (!recipientAddress) {- alert(`Could not resolve "${typedRecipient}" to a Solana address.`);- return;- }-- const recipientPubKey = new solanaWeb3.PublicKey(recipientAddress);- const transaction = new solanaWeb3.Transaction().add(- solanaWeb3.SystemProgram.transfer({- fromPubkey: wallet,- toPubkey: recipientPubKey,- lamports: amount * solanaWeb3.LAMPORTS_PER_SOL,- }),- );-- transaction.feePayer = wallet;- const { blockhash } = await connection.getRecentBlockhash();- transaction.recentBlockhash = blockhash;-- const provider = getProvider();- const signedTransaction = await provider.signTransaction(transaction);- const signature = await connection.sendRawTransaction(signedTransaction.serialize());- await connection.confirmTransaction(signature);-- const displayTarget =- typedRecipient === recipientAddress- ? recipientAddress- : `${typedRecipient} (${recipientAddress})`;- alert(`Withdrawal of ${amount} SOL to ${displayTarget} successful!`);-- withdrawModal.close();- withdrawAmountInput.value = '';- recipientAddressInput.value = '';- snsResolver.reset();- } catch (error) {- log.error('Withdrawal failed:', error);- alert(`Withdrawal failed: ${error.message}`);- } finally {- confirmWithdrawBtn.disabled = false;- }- });+ const agentId = agent?.id;+ if (!isOwner || !agentId) {+ actions.style.display = 'none';+ return;+ }- swapBtn.addEventListener('click', () => {- openSwapModal({ wallet, getProvider });- });+ // Replace the legacy Receive/Withdraw/Swap buttons with a single entry point+ // into the wallet hub. One wallet surface, reachable from the profile.+ actions.innerHTML = '';+ const manage = document.createElement('a');+ manage.className = 'ad-btn ad-btn-primary';+ manage.href = `/agent/${encodeURIComponent(agentId)}/wallet`;+ manage.textContent = 'Manage wallet';+ manage.setAttribute('aria-label', 'Open this agent’s wallet hub');+ const deposit = document.createElement('a');+ deposit.className = 'ad-btn';+ deposit.href = `/agent/${encodeURIComponent(agentId)}/wallet#deposit`;+ deposit.textContent = 'Deposit';+ actions.append(manage, deposit);}function renderNotFound(id, reason) {diff --git a/src/agent-wallet-hub/tabs/withdraw.js b/src/agent-wallet-hub/tabs/withdraw.jsindex 2f51e62d6..5496dfa5d 100644--- a/src/agent-wallet-hub/tabs/withdraw.js+++ b/src/agent-wallet-hub/tabs/withdraw.js@@ -1,19 +1,630 @@/**- * Agent Wallet hub — Withdraw tab (placeholder; replaced by epic task 09).+ * Agent Wallet hub — Withdraw tab (epic task 09: custody safety).*- * Owner-only: only the owner may move funds out of the custodial wallet.- * Task 09 ships the withdraw/sweep path (SOL + SPL), spend limits, and the- * custody audit trail.+ * Owner-only. Three sub-sections, all states designed:+ *+ * Withdraw Sweep SOL or any held SPL token out to an address or .sol+ * name. The agent key is server-side, so this calls the+ * server-signed, idempotent POST /api/agents/:id/solana/withdraw+ * — there is no client key for the agent's address. Rent + fees+ * are reserved on a SOL "Max" so a sweep can't brick the wallet.+ * Limits & Safety Read/edit the per-agent spend policy (daily + per-tx USD+ * ceilings, withdraw allowlist) that governs trade/snipe/x402/+ * withdraw from one place.+ * Activity The custody audit trail: key recovery, withdrawals, automated+ * spends, and limit changes.+ *+ * Everything is real: live holdings from /solana/holdings, real on-chain+ * withdrawals, the real shared spend policy. No mocks, no client signing.*/-import { registerPlaceholderTab } from './_placeholder.js';+import { registerWalletTab } from '../registry.js';+import { formatUsd, explorerTxUrl, explorerAddressUrl } from '../util.js';++const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const WD_STYLE_ID = 'awh-withdraw-style';+const WD_STYLE = `+.awh-sub { display: flex; gap: 4px; margin-bottom: var(--space-4,16px); }+.awh-sub button { appearance:none; font:inherit; font-size: var(--text-sm,.764rem); font-weight:500; color: var(--ink-dim,#888); background:transparent; border:1px solid transparent; border-radius: var(--radius-pill,999px); padding:5px 13px; cursor:pointer; transition: background var(--duration-fast,140ms), color var(--duration-fast,140ms); }+.awh-sub button:hover { color: var(--ink,#e8e8e8); }+.awh-sub button[aria-pressed="true"] { color: var(--ink-bright,#fff); background: var(--surface-2, rgba(255,255,255,.07)); border-color: var(--stroke,rgba(255,255,255,.1)); }+.awh-sub button:focus-visible { outline: var(--focus-ring-width,2px) solid var(--focus-ring-color,#fff); outline-offset:2px; }++.awh-fld { margin-bottom: var(--space-4,16px); }+.awh-fld label { display:block; font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-bottom:6px; }+.awh-in, .awh-sel { width:100%; box-sizing:border-box; font:inherit; font-size: var(--text-md,.8125rem); color: var(--ink,#e8e8e8); background: var(--surface-1, rgba(255,255,255,.03)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:9px 12px; transition: border-color var(--duration-fast,140ms); }+.awh-in:focus, .awh-sel:focus { outline:none; border-color: var(--stroke-strong, rgba(255,255,255,.2)); }+.awh-row { display:flex; gap:8px; }+.awh-row .awh-in { flex:1; }+.awh-resolved { font-size: var(--text-sm,.764rem); margin-top:6px; font-family: var(--font-mono,ui-monospace,monospace); word-break:break-all; }+.awh-resolved.ok { color: var(--success,#4ade80); }+.awh-resolved.warn { color: var(--warn,#fbbf24); }+.awh-note { font-size: var(--text-sm,.764rem); color: var(--ink-dim,#888); margin-top:6px; }+.awh-err { background: color-mix(in srgb, var(--danger,#f87171) 12%, transparent); border:1px solid color-mix(in srgb, var(--danger,#f87171) 32%, transparent); color: var(--danger,#f87171); border-radius: var(--radius-md,10px); padding:10px 12px; font-size: var(--text-sm,.764rem); margin-bottom: var(--space-3,12px); }+.awh-err .why { color: var(--ink-dim,#aaa); font-size: var(--text-2xs,.6875rem); margin-top:4px; text-transform:capitalize; }+.awh-sum { background: var(--surface-2, rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-md,10px); padding:12px 14px; margin-bottom: var(--space-3,12px); }+.awh-sum .r { display:flex; justify-content:space-between; gap:12px; padding:4px 0; font-size: var(--text-sm,.764rem); }+.awh-sum .r > span:first-child { color: var(--ink-dim,#888); flex:none; }+.awh-sum .r .v { font-family: var(--font-mono,ui-monospace,monospace); text-align:right; word-break:break-all; color: var(--ink,#e8e8e8); }+.awh-actions { display:flex; gap:8px; margin-top: var(--space-3,12px); }+.awh-ok { text-align:center; padding: var(--space-4,16px) var(--space-2,8px); }+.awh-ok .ic { font-size:32px; line-height:1; margin-bottom:8px; }+.awh-skel-line { height:14px; border-radius:6px; background: var(--surface-2, rgba(255,255,255,.05)); animation: awh-skel 1.4s ease-in-out infinite; margin:9px 0; }+.awh-spin { display:inline-block; width:13px; height:13px; border:2px solid rgba(255,255,255,.3); border-top-color: currentColor; border-radius:50%; animation: awh-rot .7s linear infinite; vertical-align:-2px; margin-right:6px; }+@keyframes awh-rot { to { transform: rotate(360deg); } }++.awh-chips { display:flex; gap:6px; flex-wrap:wrap; margin-bottom: var(--space-3,12px); }+.awh-chip { font-size: var(--text-2xs,.6875rem); color: var(--ink,#e8e8e8); background: var(--surface-2,rgba(255,255,255,.06)); border:1px solid var(--stroke,rgba(255,255,255,.1)); border-radius: var(--radius-pill,999px); padding:3px 10px; }+.awh-chip.alert { color: var(--warn,#fbbf24); border-color: color-mix(in srgb, var(--warn,#fbbf24) 30%, transparent); }+.awh-allow { list-style:none; margin:0 0 10px; padding:0; }+.awh-allow li { display:flex; align-items:center; justify-content:space-between; gap:8px; padding:7px 0; border-bottom:1px solid var(--stroke,rgba(255,255,255,.06)); font-family: var(--font-mono,ui-monospace,monospace); font-size: var(--text-sm,.764rem); }+.awh-allow .rm { appearance:none; background:transparent; border:0; color: var(--danger,#f87171); cursor:pointer; font-size:14px; line-height:1; padding:2px 6px; border-radius:6px; }+.awh-allow .rm:hover { background: color-mix(in srgb, var(--danger,#f87171) 14%, transparent); }++.awh-evs { list-style:none; margin:0; padding:0; }+.awh-ev { display:flex; gap:11px; padding:10px 0; border-bottom:1px solid var(--stroke,rgba(255,255,255,.06)); font-size: var(--text-sm,.764rem); }+.awh-ev:last-child { border-bottom:none; }+.awh-ev .ic { font-size:15px; width:20px; text-align:center; flex:none; }+.awh-ev .m { flex:1; min-width:0; }+.awh-ev .ttl { color: var(--ink,#e8e8e8); }+.awh-ev .sb { color: var(--ink-dim,#888); font-size: var(--text-2xs,.6875rem); font-family: var(--font-mono,ui-monospace,monospace); margin-top:2px; word-break:break-all; }+.awh-ev .sb a { color: inherit; border-bottom:1px dotted currentColor; }+.awh-ev .amt { text-align:right; font-family: var(--font-mono,ui-monospace,monospace); flex:none; color: var(--ink,#e8e8e8); }++.awh-scan { position:fixed; inset:0; background:rgba(0,0,0,.85); z-index:99999; display:flex; align-items:center; justify-content:center; }+.awh-scan-box { display:flex; flex-direction:column; gap:12px; align-items:center; }+.awh-scan video { width:min(320px,80vw); height:min(320px,80vw); object-fit:cover; border-radius:14px; border:2px solid var(--accent,#fff); }+@media (prefers-reduced-motion: reduce) { .awh-skel-line, .awh-spin { animation:none; } }+`;++function injectStyle() {+ if (typeof document === 'undefined' || document.getElementById(WD_STYLE_ID)) return;+ const tag = document.createElement('style');+ tag.id = WD_STYLE_ID;+ tag.textContent = WD_STYLE;+ document.head.appendChild(tag);+}++// ── fetch helper: never throws, always a designed result ──────────────────────+async function call(url, { method = 'GET', body = null } = {}) {+ try {+ const opts = { method, credentials: 'include', headers: {} };+ if (body != null) {+ opts.headers['content-type'] = 'application/json';+ opts.body = JSON.stringify(body);+ }+ const r = await fetch(url, opts);+ let j = null;+ try { j = await r.json(); } catch { /* empty body */ }+ if (!r.ok) {+ return { ok: false, status: r.status, code: j?.error || 'error', message: j?.error_description || `request failed (${r.status})`, detail: j?.detail || null, extra: j || null };+ }+ return { ok: true, status: r.status, data: j?.data ?? j };+ } catch (err) {+ return { ok: false, status: 0, code: 'network_error', message: err?.message || 'network error' };+ }+}++function fmtAmount(n, max = 6) {+ if (n == null) return '0';+ const num = Number(n);+ if (!Number.isFinite(num)) return String(n);+ return num.toLocaleString(undefined, { maximumFractionDigits: max });+}++async function resolveRecipient(raw) {+ const v = (raw || '').trim();+ if (!v) return { error: 'Enter a recipient address.' };+ if (SOL_ADDR_RE.test(v)) return { address: v };+ if (/\.sol$/i.test(v)) {+ const res = await call(`/api/sns?name=${encodeURIComponent(v)}`);+ if (res.ok && res.data?.address) return { address: res.data.address, name: v };+ return { error: `Could not resolve “${v}”.` };+ }+ return { error: 'Not a valid Solana address or .sol name.' };+}++function qrSupported() {+ return typeof window !== 'undefined' && 'BarcodeDetector' in window && !!navigator.mediaDevices?.getUserMedia;+}-registerPlaceholderTab({+async function scanQr() {+ if (!qrSupported()) return null;+ let stream = null;+ const overlay = document.createElement('div');+ overlay.className = 'awh-scan';+ overlay.innerHTML = `<div class="awh-scan-box"><video autoplay muted playsinline></video><button type="button" class="awh-btn">Cancel</button></div>`;+ document.body.appendChild(overlay);+ const video = overlay.querySelector('video');+ let stopped = false;+ const cleanup = () => { stopped = true; if (stream) stream.getTracks().forEach((t) => t.stop()); overlay.remove(); };+ overlay.querySelector('button').addEventListener('click', cleanup);+ try {+ // eslint-disable-next-line no-undef+ const detector = new BarcodeDetector({ formats: ['qr_code'] });+ stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });+ video.srcObject = stream;+ return await new Promise((resolve) => {+ const tick = async () => {+ if (stopped || !overlay.isConnected) return resolve(null);+ try {+ const codes = await detector.detect(video);+ if (codes && codes.length) {+ let raw = codes[0].rawValue || '';+ const m = raw.match(/^solana:([1-9A-HJ-NP-Za-km-z]{32,44})/);+ if (m) raw = m[1];+ cleanup();+ return resolve(raw);+ }+ } catch { /* keep scanning */ }+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ });+ } catch {+ cleanup();+ return null;+ }+}++registerWalletTab({id: 'withdraw',label: 'Withdraw',order: 60,ownerOnly: true,- icon: '↑',- title: 'Withdraw funds',- body: 'Move all SOL and SPL tokens out of the agent wallet to any address or .sol name at any time — you always control the funds. Spend limits and a full custody audit trail live here too. This panel is being wired up now.',+ mount({ panel, ctx }) {+ injectStyle();+ const { escapeHtml, shortAddress, toast } = ctx;+ const esc = escapeHtml;+ const base = (sub) => `/api/agents/${encodeURIComponent(ctx.agentId)}/solana/${sub}`;++ let destroyed = false;+ let detachNet = null;+ const state = {+ view: 'withdraw', // 'withdraw' | 'limits' | 'activity'+ holdings: null, // { sol, tokens } | null+ holdingsErr: null,+ limits: null, // { limits, spent_today_usd } | { error }+ // withdraw form+ selectedAsset: 0,+ dest: '',+ resolvedDest: null,+ amount: '',+ phase: 'form', // 'form' | 'confirm' | 'sending' | 'success'+ intent: null,+ result: null,+ submitErr: null,+ };++ function subStrip() {+ const item = (id, label) => `<button type="button" data-sub="${id}" aria-pressed="${state.view === id}">${esc(label)}</button>`;+ return `<div class="awh-sub" role="tablist">${item('withdraw', 'Withdraw')}${item('limits', 'Limits & Safety')}${item('activity', 'Activity')}</div>`;+ }++ function render() {+ if (destroyed) return;+ let inner = '';+ if (state.view === 'withdraw') inner = renderWithdraw();+ else if (state.view === 'limits') inner = renderLimits();+ else inner = '<div class="awh-card" data-host="activity"></div>';+ panel.innerHTML = `${subStrip()}${inner}`;+ panel.querySelectorAll('[data-sub]').forEach((b) => b.addEventListener('click', () => switchView(b.dataset.sub)));+ if (state.view === 'withdraw') wireWithdraw();+ else if (state.view === 'limits') wireLimits();+ else mountActivity(panel.querySelector('[data-host="activity"]'));+ }++ function switchView(v) {+ if (state.view === v) return;+ state.view = v;+ if (v === 'withdraw') { state.phase = 'form'; }+ render();+ }++ // ── Withdraw view ─────────────────────────────────────────────────────+ function assetList() {+ const out = [];+ const { sol = 0, tokens = [] } = state.holdings || {};+ if (Number(sol) > 0) out.push({ kind: 'SOL', name: 'SOL', label: `SOL — ${fmtAmount(sol, 6)}`, max: sol, decimals: 9 });+ for (const t of tokens) {+ out.push({+ kind: t.mint,+ name: t.is_usdc ? 'USDC' : shortAddress(t.mint, 4, 4),+ label: `${t.is_usdc ? 'USDC' : shortAddress(t.mint, 4, 4)} — ${fmtAmount(t.ui_amount, t.decimals)}`,+ max: t.ui_amount, decimals: t.decimals, isUsdc: t.is_usdc,+ });+ }+ return out;+ }++ function renderWithdraw() {+ if (state.phase === 'success') return renderSuccess();+ if (state.holdings === null && !state.holdingsErr) {+ return `<div class="awh-card"><div class="awh-skel-line" style="width:40%"></div><div class="awh-skel-line"></div><div class="awh-skel-line"></div><div class="awh-skel-line" style="width:60%"></div></div>`;+ }+ if (state.holdingsErr) {+ return `<div class="awh-card"><div class="awh-err">Couldn’t load balances.<div class="why">${esc(state.holdingsErr)}</div></div><button class="awh-btn" type="button" data-act="reload-holdings">Retry</button></div>`;+ }+ const assets = assetList();+ if (!assets.length) {+ return `<div class="awh-card"><div class="awh-empty" style="text-align:center;padding:24px 8px;">This wallet holds no withdrawable funds on ${esc(ctx.getNetwork())}.<br>Fund it from the Deposit tab, then sweep funds out here.</div></div>`;+ }+ if (state.phase === 'confirm' && state.intent) return renderConfirm();++ const a = assets[Math.min(state.selectedAsset, assets.length - 1)];+ return `+ <div class="awh-card">+ <div class="awh-fld">+ <label for="awh-asset">Asset</label>+ <select class="awh-sel" id="awh-asset">+ ${assets.map((x, i) => `<option value="${i}" ${i === state.selectedAsset ? 'selected' : ''}>${esc(x.label)}</option>`).join('')}+ </select>+ </div>+ <div class="awh-fld">+ <label for="awh-dest">Destination address or .sol name</label>+ <div class="awh-row">+ <input class="awh-in" id="awh-dest" autocomplete="off" spellcheck="false" placeholder="Recipient wallet or name.sol" value="${esc(state.dest)}">+ <button class="awh-btn" id="awh-scan" type="button" title="Scan a QR code" ${qrSupported() ? '' : 'style="display:none"'}>⛶</button>+ </div>+ <div class="awh-resolved" id="awh-resolved" hidden></div>+ </div>+ <div class="awh-fld">+ <label for="awh-amount">Amount</label>+ <div class="awh-row">+ <input class="awh-in" id="awh-amount" type="text" inputmode="decimal" placeholder="0.0" value="${esc(state.amount)}">+ <button class="awh-btn" id="awh-max" type="button">Max</button>+ </div>+ <div class="awh-note" id="awh-avail">Available: ${esc(fmtAmount(a.max, a.decimals))} ${esc(a.name)}</div>+ </div>+ <div class="awh-err" id="awh-wd-err" hidden></div>+ <button class="awh-btn awh-btn--primary" id="awh-review" type="button" style="width:100%;">Review withdrawal</button>+ </div>`;+ }++ function renderConfirm() {+ const it = state.intent;+ return `+ <div class="awh-card">+ <div class="awh-sum">+ <div class="r"><span>Asset</span><span class="v">${esc(it.assetName)}</span></div>+ <div class="r"><span>Amount</span><span class="v">${it.isMax ? 'Max — ' : ''}${esc(fmtAmount(it.amount, it.decimals))} ${esc(it.assetName)}</span></div>+ <div class="r"><span>To</span><span class="v">${esc(it.destination)}</span></div>+ <div class="r"><span>Network</span><span class="v">${esc(ctx.getNetwork())}</span></div>+ </div>+ ${it.kind === 'SOL' && it.isMax ? '<div class="awh-note">A little SOL is kept back to cover rent + network fees.</div>' : ''}+ <div class="awh-err" id="awh-cf-err" hidden></div>+ <div class="awh-actions">+ <button class="awh-btn" id="awh-back" type="button" style="flex:1;" ${state.phase === 'sending' ? 'disabled' : ''}>Back</button>+ <button class="awh-btn awh-btn--primary" id="awh-confirm" type="button" style="flex:2;" ${state.phase === 'sending' ? 'disabled' : ''}>+ ${state.phase === 'sending' ? '<span class="awh-spin"></span>Submitting…' : 'Confirm withdrawal'}+ </button>+ </div>+ </div>`;+ }++ function renderSuccess() {+ const r = state.result || {};+ const net = ctx.getNetwork();+ const sig = r.signature || null;+ const explorer = r.explorer || (sig ? explorerTxUrl(sig, net) : null);+ const it = state.intent || {};+ return `+ <div class="awh-card awh-ok">+ <div class="ic">${state.unconfirmed ? '⏳' : '✓'}</div>+ <div style="font-size:var(--text-md,.8125rem);font-weight:600;color:var(--ink-bright,#fff);margin-bottom:4px;">+ ${state.unconfirmed ? 'Withdrawal submitted' : 'Withdrawal confirmed'}+ </div>+ <div class="awh-empty" style="padding:0 0 12px;">+ ${state.unconfirmed+ ? 'Submitted to the network — confirm it on the explorer before retrying.'+ : `${esc(fmtAmount(it.amount, it.decimals))} ${esc(it.assetName)} sent to ${esc(shortAddress(it.destination, 6, 6))}.`}+ </div>+ ${explorer ? `<a class="awh-btn awh-btn--primary" href="${esc(explorer)}" target="_blank" rel="noopener" style="text-decoration:none;display:inline-block;">View on explorer ↗</a>` : ''}+ <div style="margin-top:14px;"><button class="awh-btn" id="awh-again" type="button">Withdraw more</button></div>+ </div>`;+ }++ function wireWithdraw() {+ panel.querySelector('[data-act="reload-holdings"]')?.addEventListener('click', () => { state.holdings = null; state.holdingsErr = null; render(); loadHoldings(); });++ if (state.phase === 'success') {+ panel.querySelector('#awh-again')?.addEventListener('click', () => { resetForm(); state.holdings = null; render(); loadHoldings(); });+ return;+ }+ if (state.phase === 'confirm') {+ panel.querySelector('#awh-back')?.addEventListener('click', () => { state.phase = 'form'; render(); });+ panel.querySelector('#awh-confirm')?.addEventListener('click', submitWithdraw);+ return;+ }++ const assets = assetList();+ const assetSel = panel.querySelector('#awh-asset');+ const destInput = panel.querySelector('#awh-dest');+ const resolvedEl = panel.querySelector('#awh-resolved');+ const amountInput = panel.querySelector('#awh-amount');+ const availEl = panel.querySelector('#awh-avail');+ const errEl = panel.querySelector('#awh-wd-err');+ if (!assetSel) return;++ const currentAsset = () => assets[Math.min(Number(assetSel.value), assets.length - 1)];++ assetSel.addEventListener('change', () => {+ state.selectedAsset = Number(assetSel.value);+ const a = currentAsset();+ availEl.textContent = `Available: ${fmtAmount(a.max, a.decimals)} ${a.name}`;+ });+ amountInput.addEventListener('input', () => { state.amount = amountInput.value; });+ panel.querySelector('#awh-max')?.addEventListener('click', () => { amountInput.value = 'max'; state.amount = 'max'; });++ let seq = 0;+ async function doResolve() {+ const myId = ++seq;+ const raw = destInput.value.trim();+ state.dest = raw;+ state.resolvedDest = null;+ if (!raw) { resolvedEl.hidden = true; return; }+ if (SOL_ADDR_RE.test(raw)) {+ state.resolvedDest = raw;+ resolvedEl.hidden = false; resolvedEl.className = 'awh-resolved ok'; resolvedEl.textContent = `✓ ${shortAddress(raw, 6, 6)}`;+ return;+ }+ const res = await resolveRecipient(raw);+ if (myId !== seq) return;+ if (res.address) {+ state.resolvedDest = res.address;+ resolvedEl.hidden = false; resolvedEl.className = 'awh-resolved ok'; resolvedEl.textContent = `→ ${res.address}`;+ } else {+ resolvedEl.hidden = false; resolvedEl.className = 'awh-resolved warn'; resolvedEl.textContent = res.error || 'unresolved';+ }+ }+ destInput.addEventListener('input', () => { clearTimeout(destInput._t); destInput._t = setTimeout(doResolve, 250); });+ if (state.dest) doResolve();++ panel.querySelector('#awh-scan')?.addEventListener('click', async () => {+ const got = await scanQr();+ if (got) { destInput.value = got; doResolve(); }+ });++ panel.querySelector('#awh-review')?.addEventListener('click', async () => {+ errEl.hidden = true;+ const a = currentAsset();+ if (!state.resolvedDest) {+ await doResolve();+ if (!state.resolvedDest) { errEl.hidden = false; errEl.textContent = 'Enter a valid destination address or .sol name.'; return; }+ }+ const amtRaw = (amountInput.value || '').trim().toLowerCase();+ const isMax = amtRaw === 'max';+ const amt = isMax ? Number(a.max) : Number(amtRaw);+ if (!isMax && (!Number.isFinite(amt) || amt <= 0)) { errEl.hidden = false; errEl.textContent = 'Enter an amount, or tap Max.'; return; }+ if (!isMax && amt > Number(a.max) + 1e-12) { errEl.hidden = false; errEl.textContent = 'Amount exceeds the available balance.'; return; }+ state.intent = {+ kind: a.kind, assetName: a.name, decimals: a.decimals,+ isMax, amount: isMax ? Number(a.max) : amt, destination: state.resolvedDest,+ idem: (crypto?.randomUUID?.() || `wd-${Date.now()}-${Math.round(Math.random() * 1e9)}`),+ };+ state.phase = 'confirm';+ render();+ });+ }++ async function submitWithdraw() {+ const it = state.intent;+ if (!it || state.phase === 'sending') return;+ state.phase = 'sending';+ render();+ const res = await call(base('withdraw'), {+ method: 'POST',+ body: { asset: it.kind, amount: it.isMax ? 'max' : it.amount, destination: it.destination, network: ctx.getNetwork(), idempotency_key: it.idem },+ });+ if (res.ok || res.status === 202) {+ state.result = res.ok ? res.data : (res.extra || {});+ state.unconfirmed = res.status === 202;+ state.phase = 'success';+ toast(state.unconfirmed ? 'Withdrawal submitted' : 'Withdrawal confirmed');+ render();+ // Refresh limits/activity next time they're opened.+ state.limits = null;+ return;+ }+ state.phase = 'confirm';+ render();+ const errEl = panel.querySelector('#awh-cf-err');+ if (errEl) {+ errEl.hidden = false;+ errEl.innerHTML = `${esc(res.message)}${res.code ? `<div class="why">${esc(res.code.replace(/_/g, ' '))}</div>` : ''}`;+ }+ }++ function resetForm() {+ state.phase = 'form'; state.intent = null; state.result = null;+ state.dest = ''; state.resolvedDest = null; state.amount = ''; state.selectedAsset = 0; state.unconfirmed = false;+ }++ async function loadHoldings() {+ const res = await call(`${base('holdings')}?network=${ctx.getNetwork()}`);+ if (destroyed) return;+ if (!res.ok) { state.holdingsErr = res.message; state.holdings = null; }+ else { state.holdingsErr = null; state.holdings = res.data; }+ if (state.view === 'withdraw') render();+ }++ // ── Limits & Safety view ───────────────────────────────────────────────+ function renderLimits() {+ if (state.limits === null) {+ return `<div class="awh-card"><div class="awh-skel-line" style="width:50%"></div><div class="awh-skel-line"></div><div class="awh-skel-line"></div></div>`;+ }+ if (state.limits.error) {+ return `<div class="awh-card"><div class="awh-err">Couldn’t load limits.<div class="why">${esc(state.limits.error)}</div></div><button class="awh-btn" type="button" data-act="reload-limits">Retry</button></div>`;+ }+ const lim = state.limits.limits || {};+ const spent = state.limits.spent_today_usd ?? 0;+ const allow = Array.isArray(lim.withdraw_allowlist) ? lim.withdraw_allowlist : [];+ const overDaily = lim.daily_usd != null && spent >= lim.daily_usd;+ return `+ <div class="awh-card">+ <div class="awh-chips">+ <span class="awh-chip${overDaily ? ' alert' : ''}">Spent today: ${esc(formatUsd(spent) || '$0.00')}</span>+ <span class="awh-chip">Daily cap: ${lim.daily_usd != null ? esc(formatUsd(lim.daily_usd)) : 'none'}</span>+ <span class="awh-chip">Per-tx cap: ${lim.per_tx_usd != null ? esc(formatUsd(lim.per_tx_usd)) : 'none'}</span>+ </div>+ <p class="awh-empty" style="margin-top:0;">These ceilings apply to every outbound path — trades, snipes, x402 payments and withdrawals. Leave a field blank for no limit.</p>+ <div class="awh-fld">+ <label for="awh-daily">Daily spend cap (USD)</label>+ <input class="awh-in" id="awh-daily" type="text" inputmode="decimal" placeholder="No limit" value="${lim.daily_usd != null ? esc(lim.daily_usd) : ''}">+ </div>+ <div class="awh-fld">+ <label for="awh-pertx">Per-transaction cap (USD)</label>+ <input class="awh-in" id="awh-pertx" type="text" inputmode="decimal" placeholder="No limit" value="${lim.per_tx_usd != null ? esc(lim.per_tx_usd) : ''}">+ </div>+ <div class="awh-fld">+ <label>Withdraw allowlist <span style="opacity:.6">(optional — restrict where funds can be swept)</span></label>+ <ul class="awh-allow" id="awh-allow">+ ${allow.length ? allow.map((x) => `<li><span>${esc(x)}</span><button class="rm" type="button" data-a="${esc(x)}" aria-label="Remove ${esc(x)}">✕</button></li>`).join('') : '<li style="opacity:.6;border:0;">Any valid address allowed.</li>'}+ </ul>+ <div class="awh-row">+ <input class="awh-in" id="awh-allow-add" autocomplete="off" spellcheck="false" placeholder="Add an address or name.sol">+ <button class="awh-btn" id="awh-allow-btn" type="button">Add</button>+ </div>+ </div>+ <div class="awh-err" id="awh-lim-err" hidden></div>+ <button class="awh-btn awh-btn--primary" id="awh-lim-save" type="button" style="width:100%;">Save limits</button>+ </div>`;+ }++ function wireLimits() {+ panel.querySelector('[data-act="reload-limits"]')?.addEventListener('click', () => { state.limits = null; render(); loadLimits(); });+ if (state.limits === null) { loadLimits(); return; }+ if (state.limits.error) return;++ const lim = state.limits.limits || {};+ const allowState = (Array.isArray(lim.withdraw_allowlist) ? lim.withdraw_allowlist : []).slice();+ const errEl = panel.querySelector('#awh-lim-err');++ function repaint() {+ const ul = panel.querySelector('#awh-allow');+ if (!ul) return;+ ul.innerHTML = allowState.length+ ? allowState.map((x) => `<li><span>${esc(x)}</span><button class="rm" type="button" data-a="${esc(x)}" aria-label="Remove">✕</button></li>`).join('')+ : '<li style="opacity:.6;border:0;">Any valid address allowed.</li>';+ ul.querySelectorAll('.rm').forEach((b) => b.addEventListener('click', () => {+ const i = allowState.indexOf(b.dataset.a);+ if (i >= 0) allowState.splice(i, 1);+ repaint();+ }));+ }+ repaint();++ panel.querySelector('#awh-allow-btn')?.addEventListener('click', async () => {+ const inp = panel.querySelector('#awh-allow-add');+ errEl.hidden = true;+ const res = await resolveRecipient(inp.value.trim());+ if (!res.address) { errEl.hidden = false; errEl.textContent = res.error || 'Invalid address.'; return; }+ if (!allowState.includes(res.address)) allowState.push(res.address);+ inp.value = '';+ repaint();+ });++ panel.querySelector('#awh-lim-save')?.addEventListener('click', async () => {+ const saveBtn = panel.querySelector('#awh-lim-save');+ errEl.hidden = true;+ const parse = (v) => (v.trim() === '' ? null : Number(v));+ const daily = parse(panel.querySelector('#awh-daily').value);+ const perTx = parse(panel.querySelector('#awh-pertx').value);+ if (daily != null && (!Number.isFinite(daily) || daily < 0)) { errEl.hidden = false; errEl.textContent = 'Daily cap must be a non-negative number.'; return; }+ if (perTx != null && (!Number.isFinite(perTx) || perTx < 0)) { errEl.hidden = false; errEl.textContent = 'Per-tx cap must be a non-negative number.'; return; }+ saveBtn.disabled = true;+ saveBtn.innerHTML = '<span class="awh-spin"></span>Saving…';+ const res = await call(`${base('limits')}?network=${ctx.getNetwork()}`, { method: 'PUT', body: { daily_usd: daily, per_tx_usd: perTx, withdraw_allowlist: allowState } });+ if (destroyed) return;+ if (!res.ok) {+ saveBtn.disabled = false; saveBtn.textContent = 'Save limits';+ errEl.hidden = false; errEl.textContent = res.message;+ return;+ }+ state.limits = res.data;+ toast('Limits saved');+ render();+ });+ }++ async function loadLimits() {+ const res = await call(`${base('limits')}?network=${ctx.getNetwork()}`);+ if (destroyed) return;+ state.limits = res.ok ? res.data : { error: res.message };+ if (state.view === 'limits') render();+ }++ // ── Activity view (custody audit trail) ─────────────────────────────────+ function mountActivity(host) {+ if (!host) return;+ const items = [];+ let cursor = null;+ let exhausted = false;+ host.innerHTML = `<div class="awh-skel-line"></div><div class="awh-skel-line"></div><div class="awh-skel-line" style="width:70%"></div>`;++ const META = {+ key_recover: { ic: '🔑', label: 'Key recovered to sign' },+ limit_change: { ic: '⚙', label: 'Limits updated' },+ };+ const CAT = { trade: 'Trade', snipe: 'Snipe', x402: 'x402 payment', withdraw: 'Withdrawal' };+ const title = (e) => (e.event_type === 'spend' ? (CAT[e.category] || 'Spend') : (META[e.event_type]?.label || e.event_type));+ const icon = (e) => (e.event_type === 'spend' ? (e.category === 'withdraw' ? '↑' : '💸') : (META[e.event_type]?.ic || '•'));++ function renderEvent(e) {+ let amt = '';+ if (e.asset === 'SOL' && e.amount_lamports != null) amt = `${fmtAmount(Number(e.amount_lamports) / 1e9, 6)} SOL`;+ else if (e.usd != null) amt = formatUsd(e.usd) || '';+ else if (e.asset && e.asset !== 'SOL') amt = shortAddress(e.asset, 4, 4);+ const when = e.created_at ? new Date(e.created_at).toLocaleString() : '';+ const sub = [+ e.destination ? `→ ${shortAddress(e.destination, 4, 4)}` : '',+ e.event_type === 'key_recover' && e.reason ? esc(e.reason) : '',+ e.status && e.status !== 'ok' && e.status !== 'confirmed' ? `[${esc(e.status)}]` : '',+ esc(when),+ ].filter(Boolean).join(' · ');+ return `<li class="awh-ev"><span class="ic">${icon(e)}</span><span class="m"><span class="ttl">${esc(title(e))}</span><span class="sb">${sub}${e.explorer ? ` · <a href="${esc(e.explorer)}" target="_blank" rel="noopener">tx ↗</a>` : ''}</span></span><span class="amt">${esc(amt)}</span></li>`;+ }++ function paint() {+ if (!items.length) {+ host.innerHTML = `<div class="awh-empty" style="text-align:center;padding:24px 8px;">No custody activity yet on ${esc(ctx.getNetwork())}.<br>Withdrawals, automated spends and limit changes appear here.</div>`;+ return;+ }+ host.innerHTML = `<ul class="awh-evs">${items.map(renderEvent).join('')}</ul>${exhausted ? '' : '<button class="awh-btn" id="awh-more" type="button" style="width:100%;margin-top:10px;">Load older</button>'}`;+ host.querySelector('#awh-more')?.addEventListener('click', (ev) => { ev.target.disabled = true; ev.target.innerHTML = '<span class="awh-spin"></span>Loading…'; loadPage(); });+ }++ async function loadPage() {+ const url = `${base('custody')}?network=${ctx.getNetwork()}&limit=25${cursor ? `&before=${cursor}` : ''}`;+ const res = await call(url);+ if (destroyed) return;+ if (!res.ok) { host.innerHTML = `<div class="awh-err">Couldn’t load activity.<div class="why">${esc(res.message)}</div></div>`; return; }+ items.push(...(res.data?.items || []));+ cursor = res.data?.next_cursor || null;+ exhausted = !cursor;+ paint();+ }+ loadPage();+ }++ // React to a network switch from the hub header.+ detachNet = ctx.onNetworkChange(() => {+ state.holdings = null; state.holdingsErr = null; state.limits = null;+ resetForm();+ render();+ if (state.view === 'withdraw') loadHoldings();+ else if (state.view === 'limits') loadLimits();+ });++ render();++ return {+ onShow() {+ if (state.view === 'withdraw' && state.holdings === null && state.phase !== 'success') loadHoldings();+ else if (state.view === 'limits' && state.limits === null) loadLimits();+ },+ destroy() { destroyed = true; detachNet?.(); },+ };+ },});diff --git a/src/glb-canonicalize.js b/src/glb-canonicalize.jsindex ba9e8e891..a59313aea 100644--- a/src/glb-canonicalize.js+++ b/src/glb-canonicalize.js@@ -20,9 +20,17 @@// rewrites the GLB JSON chunk in-place and repacks the binary container so// the result is a valid GLB that swaps in 1:1 at the same R2 storage key.+import { Matrix4, Quaternion, Vector3 } from 'three';+const GLB_MAGIC = 0x46546c67; // 'glTF' little-endianconst CHUNK_TYPE_JSON = 0x4e4f534a; // 'JSON'+// Quaternion is "axis-aligned enough" / scale is "uniform enough" below this.+const ORIENT_EPS = 1e-5;+// Joint world-matrix elements must match within this before/after the fold, or+// the fold is reverted (it would have altered the mesh).+const ORIENT_WORLD_EPS = 1e-4;+// Canonical humanoid bone set. Mirrors the rig used by scripts/build-animations.mjs// (cz.glb / Avaturn reference rig) — every animation clip in /public/animations/clips// addresses tracks by these exact names.@@ -146,6 +154,147 @@ export function canonicalizeJointNodes(json) {return { renamed, samples };}+// Local TRS → Matrix4 for a glTF node.+function nodeLocalMatrix(node) {+ const t = new Vector3();+ const r = new Quaternion();+ const s = new Vector3(1, 1, 1);+ if (node.translation) t.fromArray(node.translation);+ if (node.rotation) r.fromArray(node.rotation);+ if (node.scale) s.fromArray(node.scale);+ return new Matrix4().compose(t, r, s);+}++// World matrices for a set of node indices, each walked to its scene root.+function worldMatricesFor(json, indices, parentOf) {+ const local = json.nodes.map(nodeLocalMatrix);+ const cache = new Map();+ const world = (idx) => {+ if (cache.has(idx)) return cache.get(idx);+ const p = parentOf.get(idx);+ const m = p == null ? local[idx].clone() : world(p).clone().multiply(local[idx]);+ cache.set(idx, m);+ return m;+ };+ const out = new Map();+ for (const idx of indices) out.set(idx, world(idx));+ return out;+}++/**+ * Fold a Mixamo/FBX up-axis bake out of the rig. Mixamo exports put a +90°X on+ * the armature node and a −90°X on Hips; the net is upright, but a clip authored+ * for an identity-Hips rig overwrites the −90°X and tips the body over (the+ * "lying down" bug). The runtime retargeter (animation-retarget.js) corrects for+ * this on the fly, but normalizing at ingest means stored avatars are already+ * axis-aligned and need no correction.+ *+ * The fold pushes the armature's rotation down into each child (rotating its+ * translation, pre-multiplying its rotation) and zeroes the armature's rotation.+ * Bone *world* matrices are preserved exactly — provided the armature's scale is+ * uniform, so rotation commutes with it — which means the skinned mesh and its+ * inverse-bind matrices (in the untouched BIN chunk) still resolve to the same+ * bind pose. A counter-rotated Hips collapses to identity. Verified by comparing+ * world matrices before/after; reverts on any mismatch. Mutates `json` in place.+ *+ * @param {object} json parsed glTF JSON+ * @returns {{ corrected: boolean, hipsIdentity?: boolean }}+ */+export function canonicalizeArmatureOrientation(json) {+ if (!json || !Array.isArray(json.nodes) || !Array.isArray(json.skins)) {+ return { corrected: false };+ }+ const parentOf = new Map();+ json.nodes.forEach((n, i) => {+ if (Array.isArray(n.children)) for (const c of n.children) parentOf.set(c, i);+ });+ const jointIdx = new Set();+ for (const skin of json.skins) {+ if (Array.isArray(skin.joints)) for (const j of skin.joints) jointIdx.add(j);+ }+ if (jointIdx.size === 0) return { corrected: false };++ let hips = -1;+ for (const idx of jointIdx) {+ const n = json.nodes[idx];+ if (n && typeof n.name === 'string' && canonicalizeBoneName(n.name) === 'Hips') {+ hips = idx;+ break;+ }+ }+ if (hips < 0) return { corrected: false };+ const pIdx = parentOf.get(hips);+ if (pIdx == null) return { corrected: false };+ const parent = json.nodes[pIdx];++ const r = new Quaternion();+ if (parent.rotation) r.fromArray(parent.rotation);+ if (1 - Math.abs(r.w) < ORIENT_EPS) return { corrected: false }; // already axis-aligned++ // Rotation only commutes with the parent's scale when that scale is uniform.+ const s = parent.scale;+ if (s && (Math.abs(s[0] - s[1]) > ORIENT_EPS || Math.abs(s[1] - s[2]) > ORIENT_EPS)) {+ return { corrected: false };+ }++ const children = Array.isArray(parent.children) ? parent.children : [];+ if (children.length === 0) return { corrected: false };++ // Snapshot the children (for revert) and all affected world matrices (to verify+ // the fold didn't move anything the mesh depends on).+ const checkSet = new Set([...jointIdx, ...children]);+ const before = worldMatricesFor(json, checkSet, parentOf);+ const snapshot = children.map((c) => ({+ idx: c,+ translation: json.nodes[c].translation ? json.nodes[c].translation.slice() : null,+ rotation: json.nodes[c].rotation ? json.nodes[c].rotation.slice() : null,+ }));+ const parentRotBefore = parent.rotation ? parent.rotation.slice() : null;++ for (const c of children) {+ const node = json.nodes[c];+ const t = new Vector3();+ if (node.translation) t.fromArray(node.translation);+ t.applyQuaternion(r);+ node.translation = [t.x, t.y, t.z];+ const cr = new Quaternion();+ if (node.rotation) cr.fromArray(node.rotation);+ cr.premultiply(r);+ node.rotation = [cr.x, cr.y, cr.z, cr.w];+ }+ parent.rotation = [0, 0, 0, 1];++ const after = worldMatricesFor(json, checkSet, parentOf);+ let ok = true;+ for (const idx of checkSet) {+ const a = before.get(idx).elements;+ const b = after.get(idx).elements;+ for (let k = 0; k < 16; k++) {+ if (Math.abs(a[k] - b[k]) > ORIENT_WORLD_EPS) {+ ok = false;+ break;+ }+ }+ if (!ok) break;+ }+ if (!ok) {+ for (const snap of snapshot) {+ const node = json.nodes[snap.idx];+ if (snap.translation) node.translation = snap.translation;+ else delete node.translation;+ if (snap.rotation) node.rotation = snap.rotation;+ else delete node.rotation;+ }+ if (parentRotBefore) parent.rotation = parentRotBefore;+ else delete parent.rotation;+ return { corrected: false };+ }++ const hipsQ = new Quaternion();+ if (json.nodes[hips].rotation) hipsQ.fromArray(json.nodes[hips].rotation);+ return { corrected: true, hipsIdentity: 1 - Math.abs(hipsQ.w) < ORIENT_EPS };+}+/*** Canonicalize joint bone names in a GLB ArrayBuffer. Returns a new buffer* with renamed nodes (and the count of bones rewritten); the original buffer@@ -187,8 +336,9 @@ export function canonicalizeGLBBones(arrayBuffer) {}const { renamed, samples } = canonicalizeJointNodes(json);- if (renamed === 0) {- return { buffer: arrayBuffer, renamed: 0, samples: [] };+ const orientation = canonicalizeArmatureOrientation(json);+ if (renamed === 0 && !orientation.corrected) {+ return { buffer: arrayBuffer, renamed: 0, samples: [], orientationCorrected: false };}// Repack. Chunk 1 (BIN) is optional — preserve it verbatim if present.@@ -231,5 +381,5 @@ export function canonicalizeGLBBones(arrayBuffer) {outU8.set(binBytes, binOffset + 8);}- return { buffer: out, renamed, samples };+ return { buffer: out, renamed, samples, orientationCorrected: orientation.corrected };}diff --git a/src/irl.js b/src/irl.jsindex e5f74d3b7..5d11a89e4 100644--- a/src/irl.js+++ b/src/irl.js@@ -58,6 +58,13 @@ import { anchorPoseToPin } from './irl/floor-anchor.js';import { initRoomMode } from './irl/room-mode.js';import { isFiniteReading, isCompassFresh, shouldUseAbsoluteYaw, resolveLockYaw, clampPitch } from './irl/sensor-fusion.js';import { pinBandAction } from './irl/proximity-band.js';+import {+ shouldCueArrival,+ relativeBearing,+ isFacingAgent,+ edgeNudgePlacement,+ nearestAgent,+} from './irl/proximity-cue.js';import { loadInto } from './shared/async-state.js';import { openMapPlacePicker } from './irl/map-place.js';import { openPrivacyCenter, maybeShowFirstRunDisclosure, getDiscoveryPrecision } from './irl/privacy-center.js';@@ -1331,8 +1338,10 @@ function onGPSPosition(pos) {// First fix: GPS is live, so the user can place + manage pins from here.if (!wasReady) revealMyPinsBtn();- // First fix: open the live pin stream for this location (D1). Falls back to the- // poll automatically if the realtime host is unreachable.+ // First fix: start the proximity poll (the sole pin-discovery transport) and join+ // the presence/reaction socket for this geocell. Pins are NOT streamed — they ride+ // the ~10 s REST poll; the socket carries only live presence + ambient reactions,+ // and the poll runs the whole session even if that socket never connects.if (!wasReady) startPinSync();// A lock was requested before the first fix — finish anchoring now that we@@ -2711,9 +2720,9 @@ function cancelPinGLB(pin) {if (pin._glbLoading) glbQueue.cancel(p => p === pin);}-// Apply a re-skin (C6) detected by the nearby-poll diff or a D1 pin_updated push:-// adopt the new versioned avatar_url + name and swap the rendered GLB. Cheap when-// nothing changed (version equal) so it's safe to call for every incoming pin.+// Apply a re-skin (C6) detected by the nearby-poll diff: adopt the new versioned+// avatar_url + name and swap the rendered GLB. Cheap when nothing changed (version+// equal) so it's safe to call for every incoming pin.function applyPinUpdate(pin, next) {const nextVer = Number(next.avatar_version) || 0;const prevVer = Number(pin.avatar_version) || 0;@@ -2743,16 +2752,6 @@ function reloadPinGLB(pin) {showDot(pin);}-// Realtime hook (D1) — entry point a `pin_updated { id, avatar_url,-// avatar_version }` event calls so co-located viewers swap a re-skinned agent's-// GLB the instant the owner saves, without waiting for the next nearby poll. The-// poll diff is the durable fallback; this just makes it feel instant. When Epic-// D's geohash-room transport lands, dispatch its pin_updated payloads here.-export function handleRealtimePinUpdate(evt) {- if (!evt || evt.type !== 'pin_updated' || !evt.id) return;- const pin = nearbyPins.find(p => p.id === evt.id);- if (pin) applyPinUpdate(pin, evt);-}function updateNearbyBadge() {const badge = document.getElementById('irl-nearby-badge');@@ -4946,7 +4945,7 @@ async function saveCalibrate() {throw new Error(m);}// Commit the corrected pose onto the live pin so it persists this session and- // every nearby viewer's next re-fetch picks it up (realtime push rides on D1).+ // every nearby viewer picks it up on their next proximity re-fetch (~10 s).pin.lat = _cal.lat; pin.lng = _cal.lng;pin.anchor_yaw_deg = _cal.yaw; pin.heading = Math.round(_cal.yaw);pin.anchor_height_m = _cal.height;diff --git a/src/irl/proximity-cue.js b/src/irl/proximity-cue.jsnew file mode 100644index 000000000..23de0005c--- /dev/null+++ b/src/irl/proximity-cue.js@@ -0,0 +1,136 @@+// Proximity-arrival cue policy (IRL task 03) — pure, DOM-free, clock-free.+//+// We deleted the list and the radar on purpose: an agent's location is private+// and you discover one only by physically walking into its ~40 m bubble. The cost+// of that privacy is that a user can stand 15 m from an agent, facing the wrong+// way, and never know it's there. This module is the policy behind the cue that+// fixes that — the in-world equivalent of hearing a sound nearby: "something is+// here, turn around." It points a *direction*, never a list or a coordinate.+//+// Everything here is a pure function of numbers + flags, so the gating (one cue+// per arrival, a global cooldown so a busy spot isn't a slot machine) and the+// directional geometry (screen-relative bearing → an edge-clamped nudge that+// recomputes as the device rotates, and fades once the agent is on-screen) are+// proven in a unit test with no Three.js, no DOM, and no real clock. irl.js wires+// the WebAudio chime / haptic / aria-live banner / edge-glow DOM onto these+// decisions; the privacy-sensitive math (how far, which way) lives only here and+// is fed *world offsets the viewer already renders*, never raw pin coordinates.++// Minimum gap between two arrival cues, regardless of how many agents arrive. A+// plaza where ten agents drift into range at once must buzz the user once, then+// stay quiet — discovery should feel like a tap on the shoulder, not a slot+// machine. Tuned to the 10 s proximity poll: long enough that a burst collapses+// to a single cue, short enough that two genuinely separate walk-ups each land.+export const CUE_COOLDOWN_MS = 8000;++// Decide whether an arrival should fire its cue (haptic + chime + banner) now.+// Pure: the caller owns the clock and the "last cue" timestamp; we only compare.+//+// now — current time in ms (caller passes Date.now()).+// lastCueAt — when the last cue fired, or null/undefined if none yet.+// cooldownMs — override the global cooldown (defaults to CUE_COOLDOWN_MS).+//+// Returns true when no cue has fired yet, or the cooldown has fully elapsed. The+// arrival *signal* itself is already debounced upstream (proximity-band.js only+// emits on a genuine, hysteresis-stable enter), so this layer is purely the+// "don't carpet-bomb a busy corner" rate limit — never the de-dupe of a single+// jittering agent.+export function shouldCueArrival(now, lastCueAt, cooldownMs = CUE_COOLDOWN_MS) {+ if (!Number.isFinite(now)) return false;+ if (lastCueAt == null || !Number.isFinite(lastCueAt)) return true;+ return now - lastCueAt >= cooldownMs;+}++// Normalise any angle (radians) to (-π, π]. Used so a bearing difference reads as+// the *shortest* turn — +0.1 rad is "barely right", not "almost all the way around".+export function normalizeAngle(rad) {+ let a = rad % (Math.PI * 2);+ if (a > Math.PI) a -= Math.PI * 2;+ if (a <= -Math.PI) a += Math.PI * 2;+ return a;+}++// Screen-relative bearing (radians) to a world offset, given where the viewer is+// looking. This is the heart of the directional nudge and the ONLY place a pin's+// position turns into a "which way to turn" — and even here it consumes the world+// offset {x, z} the viewer already renders (metres relative to the camera, from+// pinWorldPos), never a latitude/longitude, so nothing leaks that the on-screen+// scene wasn't already showing.+//+// x, z — the agent's world offset from the viewer in metres. In the IRL+// frame +x is screen-right and -z is forward (the camera looks down+// -z), so the agent's absolute bearing is atan2(x, -z) (0 = ahead,+// +π/2 = hard right, ±π = directly behind).+// cameraYaw — the viewer's facing in radians (0 = looking along -z = "north" of+// the local frame), matching irl.js cameraYaw.+//+// Returns the bearing *relative to where the camera points*: 0 = the agent is dead+// ahead of the current view, + = the user must turn right to face it, - = left,+// ±π = it's directly behind them. Recompute every frame as cameraYaw changes and+// the nudge tracks the agent live as the user rotates.+export function relativeBearing(x, z, cameraYaw) {+ const absolute = Math.atan2(x, -z);+ return normalizeAngle(absolute - cameraYaw);+}++// Is the agent comfortably within the view cone (so the visible avatar itself is+// the cue and the edge nudge should fade)? `relBearing` is the output of+// relativeBearing above; `halfFovRad` is half the camera's *horizontal* field of+// view. We require the agent to be inside ~85% of the half-FOV before we call it+// "on screen" — a small inset hysteresis so a pin hovering exactly on the frame+// edge doesn't flicker the nudge on and off as the user's hand shakes.+export function isFacingAgent(relBearing, halfFovRad) {+ if (!Number.isFinite(relBearing) || !Number.isFinite(halfFovRad)) return false;+ return Math.abs(relBearing) <= halfFovRad * 0.85;+}++// Place the edge nudge. Given the relative bearing and the viewport, return where+// to pin the arrow on the screen border and how to rotate it so it points toward+// the off-screen agent. We DON'T project the 3D point (it may be behind the camera,+// where projection flips); instead we map the bearing directly onto an ellipse+// inscribed in the safe-inset viewport, which is stable for the full ±π range and+// gives the "compass needle riding the screen edge" feel.+//+// relBearing — radians from relativeBearing(): 0 ahead, + right, - left, ±π behind.+// width — viewport width in CSS px.+// height — viewport height in CSS px.+// inset — px to keep the glow off the very edge (default 34) so it clears+// rounded corners / notches and reads as a deliberate UI element.+//+// Returns { x, y } (CSS px, where to centre the glow) and `rotateDeg` (the arrow's+// rotation in degrees, 0 = pointing straight up, increasing clockwise) so the head+// of the arrow aims along the bearing toward the agent.+export function edgeNudgePlacement(relBearing, width, height, inset = 34) {+ const b = normalizeAngle(relBearing);+ const cx = width / 2;+ const cy = height / 2;+ const rx = Math.max(8, cx - inset);+ const ry = Math.max(8, cy - inset);++ // Map the bearing onto the viewport ellipse. Screen +x is right (sin b) and the+ // agent being *ahead* (b = 0) should ride the TOP edge, so screen-up is -cos b.+ const dirX = Math.sin(b);+ const dirY = -Math.cos(b);+ const x = cx + dirX * rx;+ const y = cy + dirY * ry;++ // Arrow points along the bearing. atan2(dirX, -dirY) gives 0° = up, +90° = right,+ // matching a CSS rotate() of a glyph drawn pointing up.+ const rotateDeg = (Math.atan2(dirX, -dirY) * 180) / Math.PI;+ return { x, y, rotateDeg };+}++// Pick the single agent the nudge should point at. Per the spec we nudge toward the+// NEAREST in-range agent only — one clear "that way", never a confusing cluster of+// arrows. `agents` is an array of objects each carrying a numeric `distance` (the+// band distance from the viewer); returns the closest, or null for an empty set.+export function nearestAgent(agents) {+ let best = null;+ let bestDist = Infinity;+ for (const a of agents) {+ const d = a?.distance;+ if (!Number.isFinite(d)) continue;+ if (d < bestDist) { bestDist = d; best = a; }+ }+ return best;+}diff --git a/tests/agent-sniper-amm-exit.test.js b/tests/agent-sniper-amm-exit.test.jsnew file mode 100644index 000000000..f6703efb9--- /dev/null+++ b/tests/agent-sniper-amm-exit.test.js@@ -0,0 +1,211 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import BN from 'bn.js';++// ── Mocks ──────────────────────────────────────────────────────────────────+// amm-exit.js reaches the chain through api/_lib/pump.js (getAmmPoolState ++// getConnection) and @pump-fun/pump-swap-sdk. Mock both so the module's pure+// routing + pricing-shape logic is exercised without RPC. Resolved-module-id+// matching means the path here (relative to this test) intercepts the worker+// module's own '../../api/_lib/pump.js' import.++const mockGetAmmPoolState = vi.fn();+const mockSellBaseInput = vi.fn();+const mockSwapSolanaState = vi.fn();+const mockOfflineSellBaseInput = vi.fn();+const MOCK_POOL = '9WZDXbs5da3XuBTOBiGHqKkqFGC4j2HJvBQKzXAMsRg';++vi.mock('../api/_lib/pump.js', () => ({+ getAmmPoolState: (...a) => mockGetAmmPoolState(...a),+ getConnection: () => ({}),+}));++vi.mock('@pump-fun/pump-swap-sdk', () => ({+ sellBaseInput: (...a) => mockSellBaseInput(...a),+ PumpAmmSdk: class {+ sellBaseInput(...a) {+ return mockOfflineSellBaseInput(...a);+ }+ },+ OnlinePumpAmmSdk: class {+ swapSolanaState(...a) {+ return mockSwapSolanaState(...a);+ }+ },+}));++// Import AFTER mocks are registered.+const { isGraduated, quoteAmmSell, buildAmmSellInstructions } = await import(+ '../workers/agent-sniper/amm-exit.js'+);++const WSOL = 'So11111111111111111111111111111111111111112';+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const MINT = 'THREEsynthetic1111111111111111111111111111111';++function poolState({ quoteMint = WSOL, baseReserve = 1_000_000_000, quoteReserve = 1_000_000_000 } = {}) {+ return {+ poolKey: { toString: () => MOCK_POOL },+ pool: {+ quoteMint: { toString: () => quoteMint },+ baseMint: { toString: () => MINT },+ coinCreator: { toString: () => '11111111111111111111111111111111' },+ creator: { toString: () => '11111111111111111111111111111111' },+ },+ baseReserve: new BN(baseReserve),+ quoteReserve: new BN(quoteReserve),+ baseMintAccount: { decimals: 6 },+ globalConfig: { mock: true },+ feeConfig: null,+ };+}++function poolNotFound() {+ const e = new Error('pump.fun AMM pool not found for mint');+ e.status = 404;+ e.code = 'pool_not_found';+ return e;+}++describe('isGraduated — deterministic graduation detection', () => {+ beforeEach(() => {+ mockGetAmmPoolState.mockReset();+ });++ it('returns true when a canonical AMM pool exists', async () => {+ mockGetAmmPoolState.mockResolvedValueOnce(poolState());+ expect(await isGraduated({ network: 'mainnet', mint: MINT })).toBe(true);+ });++ it('returns false when no pool exists (still on the bonding curve)', async () => {+ mockGetAmmPoolState.mockRejectedValueOnce(poolNotFound());+ expect(await isGraduated({ network: 'mainnet', mint: MINT })).toBe(false);+ });++ it('rethrows a transient RPC error rather than reporting "not graduated"', async () => {+ mockGetAmmPoolState.mockRejectedValueOnce(+ Object.assign(new Error('rpc 502'), { code: 'pool_accounts_missing', status: 502 }),+ );+ await expect(isGraduated({ network: 'mainnet', mint: MINT })).rejects.toThrow('rpc 502');+ });+});++describe('quoteAmmSell — re-quote a graduated position off the AMM', () => {+ beforeEach(() => {+ mockGetAmmPoolState.mockReset();+ mockSellBaseInput.mockReset();+ });++ it('returns expected + min SOL out and the pool key', async () => {+ mockGetAmmPoolState.mockResolvedValueOnce(poolState());+ mockSellBaseInput.mockReturnValueOnce({+ uiQuote: new BN(9_800),+ minQuote: new BN(9_700),+ });++ const r = await quoteAmmSell({+ network: 'mainnet',+ mint: MINT,+ baseAmount: new BN(10_000),+ slippagePct: 5,+ });++ expect(r.expectedQuoteOut).toBe(9_800n);+ expect(r.minQuoteOut).toBe(9_700n);+ expect(r.poolKey).toBe(MOCK_POOL);+ expect(typeof r.priceImpactPct).toBe('number');+ expect(r.priceImpactPct).toBeGreaterThanOrEqual(0);+ });++ it('forwards the base amount, slippage, and live reserves to the SDK', async () => {+ mockGetAmmPoolState.mockResolvedValueOnce(poolState());+ mockSellBaseInput.mockReturnValueOnce({ uiQuote: new BN(50), minQuote: new BN(45) });++ await quoteAmmSell({ network: 'mainnet', mint: MINT, baseAmount: new BN(10_000), slippagePct: 5 });++ expect(mockSellBaseInput).toHaveBeenCalledOnce();+ const call = mockSellBaseInput.mock.calls[0][0];+ expect(call.base.toString()).toBe('10000');+ expect(call.slippage).toBe(5);+ expect(call.baseReserve.toString()).toBe('1000000000');+ expect(call.quoteReserve.toString()).toBe('1000000000');+ expect(call.globalConfig).toEqual({ mock: true });+ });++ it('computes a non-trivial price impact for a sale that moves the pool', async () => {+ // baseReserve=1e6, quoteReserve=1e6, sell 100_000 base, net 90_000 quote.+ // spot value = 100_000 * (1e6/1e6) = 100_000; impact = (100k-90k)/100k = 10%.+ mockGetAmmPoolState.mockResolvedValueOnce(+ poolState({ baseReserve: 1_000_000, quoteReserve: 1_000_000 }),+ );+ mockSellBaseInput.mockReturnValueOnce({ uiQuote: new BN(90_000), minQuote: new BN(85_000) });++ const r = await quoteAmmSell({+ network: 'mainnet',+ mint: MINT,+ baseAmount: new BN(100_000),+ slippagePct: 5,+ });+ expect(r.priceImpactPct).toBeCloseTo(10, 5);+ });++ it('propagates pool_not_found so callers know the coin is still on the curve', async () => {+ mockGetAmmPoolState.mockRejectedValueOnce(poolNotFound());+ await expect(+ quoteAmmSell({ network: 'mainnet', mint: MINT, baseAmount: new BN(1), slippagePct: 5 }),+ ).rejects.toMatchObject({ code: 'pool_not_found' });+ });++ it('refuses a non-SOL-quoted pool (sniper PnL is lamports-denominated)', async () => {+ mockGetAmmPoolState.mockResolvedValueOnce(poolState({ quoteMint: USDC }));+ await expect(+ quoteAmmSell({ network: 'mainnet', mint: MINT, baseAmount: new BN(1), slippagePct: 5 }),+ ).rejects.toMatchObject({ code: 'amm_quote_not_sol' });+ });+});++describe('buildAmmSellInstructions — build the on-chain AMM exit', () => {+ beforeEach(() => {+ mockGetAmmPoolState.mockReset();+ mockSellBaseInput.mockReset();+ mockSwapSolanaState.mockReset();+ mockOfflineSellBaseInput.mockReset();+ });++ it('builds instructions via swapSolanaState + offline sellBaseInput and surfaces the quote', async () => {+ mockGetAmmPoolState.mockResolvedValue(poolState());+ mockSellBaseInput.mockReturnValue({ uiQuote: new BN(9_800), minQuote: new BN(9_700) });+ mockSwapSolanaState.mockResolvedValueOnce({ pool: {} });+ const fakeIxs = [{ programId: 'ix1' }, { programId: 'ix2' }];+ mockOfflineSellBaseInput.mockResolvedValueOnce(fakeIxs);++ const r = await buildAmmSellInstructions({+ network: 'mainnet',+ mint: MINT,+ user: { toBase58: () => 'user' },+ baseAmount: new BN(10_000),+ slippagePct: 5,+ });++ expect(r.instructions).toBe(fakeIxs);+ expect(r.expectedQuoteOut).toBe(9_800n);+ expect(r.minQuoteOut).toBe(9_700n);+ expect(r.poolKey).toBe(MOCK_POOL);+ expect(mockOfflineSellBaseInput).toHaveBeenCalledOnce();+ const offCall = mockOfflineSellBaseInput.mock.calls[0];+ expect(offCall[1].toString()).toBe('10000');+ expect(offCall[2]).toBe(5);+ });++ it('propagates pool_not_found (cannot build against a curve that has not graduated)', async () => {+ mockGetAmmPoolState.mockRejectedValueOnce(poolNotFound());+ await expect(+ buildAmmSellInstructions({+ network: 'mainnet',+ mint: MINT,+ user: { toBase58: () => 'user' },+ baseAmount: new BN(1),+ slippagePct: 5,+ }),+ ).rejects.toMatchObject({ code: 'pool_not_found' });+ });+});diff --git a/tests/api/agents.test.js b/tests/api/agents.test.jsindex c1aa0290e..3644cf78b 100644--- a/tests/api/agents.test.js+++ b/tests/api/agents.test.js@@ -155,6 +155,72 @@ describe('GET /api/agents — list', () => {expect(status).toBe(200);expect(body.agents).toEqual([]);});++ it('exposes walletReady + public solana_address (never the secret)', async () => {+ authState.session = { id: 'user-1' };+ const SOL = 'So11111111111111111111111111111111111111112';+ sqlState.queue.push([+ {+ id: 'agent-w',+ user_id: 'user-1',+ name: 'Walleted',+ skills: [],+ meta: { solana_address: SOL, encrypted_solana_secret: 'ZW5jcnlwdGVk' },+ created_at: '2024-01-01T00:00:00Z',+ },+ ]);++ const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });+ expect(status).toBe(200);+ const a = body.agents[0];+ expect(a.solana_address).toBe(SOL);+ expect(a.walletReady).toBe(true);+ expect(a.wallet_ready).toBe(true);+ // The encrypted secret must never reach the client.+ expect(a.meta.encrypted_solana_secret).toBeUndefined();+ expect(JSON.stringify(a)).not.toMatch(/encrypted_solana_secret/);+ });++ it('reports walletReady=false and null solana_address for a legacy wallet-less agent', async () => {+ authState.session = { id: 'user-1' };+ sqlState.queue.push([+ {+ id: 'agent-legacy',+ user_id: 'user-1',+ name: 'Legacy',+ skills: [],+ meta: {},+ created_at: '2024-01-01T00:00:00Z',+ },+ ]);++ const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });+ expect(status).toBe(200);+ const a = body.agents[0];+ expect(a.solana_address).toBeNull();+ expect(a.walletReady).toBe(false);+ });++ it('reports walletReady=false when the address is present but the secret is missing', async () => {+ authState.session = { id: 'user-1' };+ const SOL = 'So11111111111111111111111111111111111111112';+ sqlState.queue.push([+ {+ id: 'agent-half',+ user_id: 'user-1',+ name: 'Half',+ skills: [],+ meta: { solana_address: SOL }, // no encrypted_solana_secret+ created_at: '2024-01-01T00:00:00Z',+ },+ ]);++ const { status, body } = await invoke({ method: 'GET', url: '/api/agents' });+ expect(status).toBe(200);+ const a = body.agents[0];+ expect(a.solana_address).toBe(SOL);+ expect(a.walletReady).toBe(false);+ });});describe('GET /api/agents/me — identity bootstrap', () => {diff --git a/tests/api/ensure-agent-wallet.test.js b/tests/api/ensure-agent-wallet.test.jsnew file mode 100644index 000000000..34876b3f5--- /dev/null+++ b/tests/api/ensure-agent-wallet.test.js@@ -0,0 +1,133 @@+// ensureAgentWallet() — the single custodial-wallet invariant.+//+// Verifies it: (1) returns an existing valid wallet without re-provisioning,+// (2) lazily provisions + persists a fresh keypair when the address/secret is+// missing, (3) repairs a row whose address parses but whose secret is gone (and+// vice-versa), (4) never returns or logs the decrypted secret, and (5) audit-logs+// every lazy provision. Real key generation + real PublicKey validation run; only+// the DB and the usage audit sink are mocked.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Keypair, PublicKey } from '@solana/web3.js';++// Captured UPDATE writes so we can assert what got persisted to meta.+const sqlState = { queue: [], calls: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ const query = typeof strings === 'string' ? strings : strings.join('?');+ sqlState.calls.push({ query, values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++vi.mock('../../api/_lib/env.js', () => ({+ env: { JWT_SECRET: 'test-secret-please-do-not-use-in-production-ever' },+}));++const auditEvents = [];+vi.mock('../../api/_lib/usage.js', () => ({+ recordEvent: vi.fn((evt) => auditEvents.push(evt)),+}));++const { ensureAgentWallet } = await import('../../api/_lib/agent-wallet.js');++function updateCalls() {+ return sqlState.calls.filter((c) => /update agent_identities/i.test(c.query));+}++beforeEach(() => {+ sqlState.queue = [];+ sqlState.calls = [];+ auditEvents.length = 0;+});++describe('ensureAgentWallet', () => {+ it('returns the existing wallet without re-provisioning when both fields are valid', async () => {+ const address = Keypair.generate().publicKey.toBase58();+ sqlState.queue.push([+ { id: 'agent-1', user_id: 'user-1', meta: { solana_address: address, encrypted_solana_secret: 'ZW5j' } },+ ]);++ const res = await ensureAgentWallet('agent-1', 'user-1');++ expect(res).toEqual({ address, created: false });+ expect(updateCalls()).toHaveLength(0);+ expect(auditEvents).toHaveLength(0);+ });++ it('lazily provisions and persists a fresh wallet when none exists', async () => {+ sqlState.queue.push([{ id: 'agent-2', user_id: 'user-2', meta: {} }]);++ const res = await ensureAgentWallet('agent-2', 'user-2', { reason: 'deposit' });++ expect(res.created).toBe(true);+ // Returned address must be a real, parseable Solana pubkey.+ expect(res.address).toMatch(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/);+ expect(() => new PublicKey(res.address)).not.toThrow();++ const writes = updateCalls();+ expect(writes).toHaveLength(1);+ const persistedMeta = JSON.parse(writes[0].values.find((v) => typeof v === 'string' && v.includes('solana_address')));+ expect(persistedMeta.solana_address).toBe(res.address);+ expect(typeof persistedMeta.encrypted_solana_secret).toBe('string');+ expect(persistedMeta.encrypted_solana_secret.length).toBeGreaterThan(0);+ // Provenance recorded.+ expect(persistedMeta.solana_wallet_source).toBe('lazy_provision');+ });++ it('audit-logs the lazy provision with the public address but never the secret', async () => {+ sqlState.queue.push([{ id: 'agent-3', user_id: 'user-3', meta: {} }]);++ const res = await ensureAgentWallet('agent-3', 'user-3', { reason: 'withdraw' });++ expect(auditEvents).toHaveLength(1);+ const evt = auditEvents[0];+ expect(evt.kind).toBe('solana_wallet_provision');+ expect(evt.tool).toBe('withdraw');+ expect(evt.agentId).toBe('agent-3');+ expect(evt.meta.address).toBe(res.address);+ // The secret must never appear anywhere in the audit payload.+ const serialized = JSON.stringify(evt);+ expect(serialized).not.toMatch(/encrypted_solana_secret/);+ });++ it('repairs a row whose address is present but the secret is missing', async () => {+ const address = Keypair.generate().publicKey.toBase58();+ sqlState.queue.push([{ id: 'agent-4', user_id: 'user-4', meta: { solana_address: address } }]);++ const res = await ensureAgentWallet('agent-4', 'user-4');++ expect(res.created).toBe(true);+ // A new keypair is minted (we can't recover a secret we never had), so the+ // address changes to one we hold the key for.+ expect(res.address).not.toBe(address);+ expect(updateCalls()).toHaveLength(1);+ });++ it('repairs a row whose address fails to parse', async () => {+ sqlState.queue.push([+ { id: 'agent-5', user_id: 'user-5', meta: { solana_address: 'not-a-real-base58-address!!', encrypted_solana_secret: 'ZW5j' } },+ ]);++ const res = await ensureAgentWallet('agent-5', 'user-5');++ expect(res.created).toBe(true);+ expect(res.address).toMatch(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/);+ expect(updateCalls()).toHaveLength(1);+ });++ it('never leaks the decrypted secret in the returned value', async () => {+ sqlState.queue.push([{ id: 'agent-6', user_id: 'user-6', meta: {} }]);+ const res = await ensureAgentWallet('agent-6', 'user-6');+ expect(Object.keys(res).sort()).toEqual(['address', 'created']);+ });++ it('throws a clean error for an unknown agent', async () => {+ sqlState.queue.push([]); // no row+ await expect(ensureAgentWallet('missing', 'user-x')).rejects.toThrow(/agent not found/);+ });++ it('requires an agentId', async () => {+ await expect(ensureAgentWallet(null)).rejects.toThrow(/agentId required/);+ });+});diff --git a/tests/api/irl-pins-hardening.test.js b/tests/api/irl-pins-hardening.test.jsindex 8b0f4881e..7895f8b6a 100644--- a/tests/api/irl-pins-hardening.test.js+++ b/tests/api/irl-pins-hardening.test.js@@ -323,7 +323,7 @@ describe('DELETE /api/irl/pins?all=1 — bulk device purge', () => {it('400s a bulk delete with no device token and never runs the delete', async () => {const { res, body } = await del({ all: '1' });expect(res.statusCode).toBe(400);- expect(body.error).toMatch(/device token/i);+ expect(body.error).toMatch(/device.?token/i);expect(deleteQueries()).toHaveLength(0);});diff --git a/tests/api/irl-reap-cron.test.js b/tests/api/irl-reap-cron.test.jsindex bf4e84eb5..b8290fa69 100644--- a/tests/api/irl-reap-cron.test.js+++ b/tests/api/irl-reap-cron.test.js@@ -41,45 +41,84 @@ function makeReqRes() {describe('irl-reap cron', () => {beforeEach(() => sqlMock.mockReset());- it('returns 200 (not 500) when neither table exists yet — nothing to reap', async () => {- // to_regclass probe → both NULL. No DELETE should ever be issued.- sqlMock.mockResolvedValueOnce([{ pins: null, reports: null }]);+ it('returns 200 (not 500) when no table exists yet — nothing to reap', async () => {+ // to_regclass probe → all NULL. No DELETE should ever be issued.+ sqlMock.mockResolvedValueOnce([{ pins: null, reports: null, interactions: null }]);const { req, res } = makeReqRes();await handler(req, res);expect(res.statusCode).toBe(200);- expect(res.body).toMatchObject({ ok: true, reapedPins: 0, reapedReports: 0 });+ expect(res.body).toMatchObject({ ok: true, reapedPins: 0, reapedReports: 0, reapedInteractions: 0 });// Exactly one query ran: the existence probe. No DELETE against a// non-existent relation (which is what 500'd in production).expect(sqlMock).toHaveBeenCalledTimes(1);});- it('reaps both tables when they exist', async () => {+ it('reaps pins, reports, and interactions (orphan + age-out) when all exist', async () => {sqlMock- .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports' }]) // probe- .mockResolvedValueOnce([{ id: 'p1' }, { id: 'p2' }]) // pins delete- .mockResolvedValueOnce([{ id: 'r1' }]); // reports delete+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports', interactions: 'irl_interactions' }]) // probe+ .mockResolvedValueOnce([{ id: 'p1' }, { id: 'p2' }]) // pins delete+ .mockResolvedValueOnce([{ id: 'r1' }]) // reports delete+ .mockResolvedValueOnce([{ id: 'ix-orphan' }]) // interactions orphan delete+ .mockResolvedValueOnce([{ id: 'ix-aged' }, { id: 'ix-aged2' }]); // interactions age-out deleteconst { req, res } = makeReqRes();await handler(req, res);expect(res.statusCode).toBe(200);- expect(res.body).toMatchObject({ ok: true, reapedPins: 2, reapedReports: 1 });- expect(sqlMock).toHaveBeenCalledTimes(3);+ // reapedInteractions sums the orphan sweep (1) and the age-out sweep (2).+ expect(res.body).toMatchObject({ ok: true, reapedPins: 2, reapedReports: 1, reapedInteractions: 3 });+ expect(sqlMock).toHaveBeenCalledTimes(5);});- it('purges all reports when the pins table is gone but reports remain', async () => {+ it('reaps an interaction orphaned by a removed pin (existence-guarded orphan sweep)', async () => {sqlMock- .mockResolvedValueOnce([{ pins: null, reports: 'irl_pin_reports' }]) // probe- .mockResolvedValueOnce([{ id: 'r1' }, { id: 'r2' }]); // unconditional reports delete+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: null, interactions: 'irl_interactions' }]) // probe+ .mockResolvedValueOnce([]) // pins delete — none expired+ .mockResolvedValueOnce([{ id: 'ix-orphan' }]) // interactions orphan delete — one orphan+ .mockResolvedValueOnce([]); // interactions age-out delete — none staleconst { req, res } = makeReqRes();await handler(req, res);expect(res.statusCode).toBe(200);- expect(res.body).toMatchObject({ ok: true, reapedPins: 0, reapedReports: 2 });- expect(sqlMock).toHaveBeenCalledTimes(2);+ expect(res.body).toMatchObject({ ok: true, reapedInteractions: 1 });+ // The orphan delete is the NOT EXISTS form (guarded), not the unconditional purge.+ const orphanCall = sqlMock.mock.calls.find(([s]) => {+ const q = Array.isArray(s) ? s.join(' ') : String(s);+ return /DELETE FROM irl_interactions ix/i.test(q) && /NOT EXISTS/i.test(q);+ });+ expect(orphanCall).toBeTruthy();+ });++ it('re-run after a clean sweep deletes nothing new (idempotent)', async () => {+ sqlMock+ .mockResolvedValueOnce([{ pins: 'irl_pins', reports: 'irl_pin_reports', interactions: 'irl_interactions' }]) // probe+ .mockResolvedValueOnce([]) // pins delete+ .mockResolvedValueOnce([]) // reports delete+ .mockResolvedValueOnce([]) // interactions orphan delete+ .mockResolvedValueOnce([]); // interactions age-out delete++ const { req, res } = makeReqRes();+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({ ok: true, reapedPins: 0, reapedReports: 0, reapedInteractions: 0 });+ });++ it('purges all reports + interactions when the pins table is gone (everything is an orphan)', async () => {+ sqlMock+ .mockResolvedValueOnce([{ pins: null, reports: 'irl_pin_reports', interactions: 'irl_interactions' }]) // probe+ .mockResolvedValueOnce([{ id: 'r1' }, { id: 'r2' }]) // unconditional reports delete+ .mockResolvedValueOnce([{ id: 'ix1' }]) // unconditional interactions delete+ .mockResolvedValueOnce([]); // interactions age-out delete++ const { req, res } = makeReqRes();+ await handler(req, res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toMatchObject({ ok: true, reapedPins: 0, reapedReports: 2, reapedInteractions: 1 });});it('rejects an unauthenticated request with 401', async () => {diff --git a/tests/glb-canonicalize.test.js b/tests/glb-canonicalize.test.jsindex f04b73cac..afd8f9215 100644--- a/tests/glb-canonicalize.test.js+++ b/tests/glb-canonicalize.test.js@@ -8,9 +8,11 @@*/import { describe, it, expect } from 'vitest';+import { Matrix4, Quaternion, Vector3 } from 'three';import {canonicalizeBoneName,canonicalizeJointNodes,+ canonicalizeArmatureOrientation,canonicalizeGLBBones,CANONICAL_BONES,} from '../src/glb-canonicalize.js';@@ -353,3 +355,90 @@ describe('canonicalizeGLBBones (full GLB rewrite)', () => {expect(20 + jLen).toBe(buffer.byteLength);});});++describe('canonicalizeArmatureOrientation', () => {+ const P90 = [Math.sin(Math.PI / 4), 0, 0, Math.cos(Math.PI / 4)]; // +90°X+ const M90 = [-Math.sin(Math.PI / 4), 0, 0, Math.cos(Math.PI / 4)]; // −90°X++ // Mixamo-shaped rig: armature(+90°X, uniform scale) → Hips(−90°X) → Spine → Head,+ // plus a sibling mesh node under the armature. Net bind pose is upright.+ function tiltedRigJson(armRot, hipsRot) {+ return {+ asset: { version: '2.0' },+ nodes: [+ { name: 'Armature', rotation: armRot, scale: [0.01, 0.01, 0.01], children: [1, 4] },+ { name: 'mixamorig:Hips', rotation: hipsRot, translation: [0, 100, 0], children: [2] },+ { name: 'mixamorig:Spine', translation: [0, 10, 0], children: [3] },+ { name: 'mixamorig:Head', translation: [0, 20, 0] },+ { name: 'Ch03' },+ ],+ skins: [{ joints: [1, 2, 3] }],+ scenes: [{ nodes: [0] }],+ scene: 0,+ };+ }++ function jointWorld(json, idx) {+ const parentOf = new Map();+ json.nodes.forEach((n, i) => {+ if (Array.isArray(n.children)) for (const c of n.children) parentOf.set(c, i);+ });+ const local = (n) => {+ const t = new Vector3();+ const r = new Quaternion();+ const s = new Vector3(1, 1, 1);+ if (n.translation) t.fromArray(n.translation);+ if (n.rotation) r.fromArray(n.rotation);+ if (n.scale) s.fromArray(n.scale);+ return new Matrix4().compose(t, r, s);+ };+ const w = (i) => {+ const p = parentOf.get(i);+ const m = local(json.nodes[i]);+ return p == null ? m : w(p).clone().multiply(m);+ };+ return w(idx);+ }++ it('folds a Mixamo +90/−90 split to an axis-aligned rig, losslessly', () => {+ const json = tiltedRigJson(P90.slice(), M90.slice());+ const hipsBefore = jointWorld(json, 1).elements.slice();+ const headBefore = jointWorld(json, 3).elements.slice();++ const res = canonicalizeArmatureOrientation(json);+ expect(res.corrected).toBe(true);+ expect(res.hipsIdentity).toBe(true);++ // Both the armature and the (counter-rotated) Hips are now identity.+ expect(json.nodes[0].rotation).toEqual([0, 0, 0, 1]);+ json.nodes[1].rotation.forEach((v, i) => expect(v).toBeCloseTo([0, 0, 0, 1][i], 6));++ // World matrices of the bones are preserved → the skinned mesh is unchanged.+ jointWorld(json, 1).elements.forEach((v, i) => expect(v).toBeCloseTo(hipsBefore[i], 4));+ jointWorld(json, 3).elements.forEach((v, i) => expect(v).toBeCloseTo(headBefore[i], 4));+ });++ it('is a no-op when the armature is already axis-aligned', () => {+ const json = tiltedRigJson([0, 0, 0, 1], [0, 0, 0, 1]);+ const res = canonicalizeArmatureOrientation(json);+ expect(res.corrected).toBe(false);+ });++ it('refuses to fold a non-uniform-scale armature (rotation would not commute)', () => {+ const json = tiltedRigJson(P90.slice(), M90.slice());+ json.nodes[0].scale = [0.01, 0.02, 0.01];+ const res = canonicalizeArmatureOrientation(json);+ expect(res.corrected).toBe(false);+ expect(json.nodes[0].rotation).toEqual(P90); // untouched+ });++ it('canonicalizeGLBBones reports orientationCorrected and produces a valid GLB', () => {+ const glb = buildGLB(tiltedRigJson(P90.slice(), M90.slice()), new Uint8Array([1, 2, 3, 4]));+ const res = canonicalizeGLBBones(glb);+ expect(res.orientationCorrected).toBe(true);+ expect(res.renamed).toBeGreaterThan(0); // mixamorig: names also canonicalized+ const dv = new DataView(res.buffer);+ expect(dv.getUint32(0, true)).toBe(GLB_MAGIC);+ expect(dv.getUint32(8, true)).toBe(res.buffer.byteLength);+ });+});diff --git a/tests/irl-presence-privacy.test.js b/tests/irl-presence-privacy.test.jsnew file mode 100644index 000000000..deafef3da--- /dev/null+++ b/tests/irl-presence-privacy.test.js@@ -0,0 +1,122 @@+// IRL presence privacy invariants (H1 — IRL-Hardening regression fence).+//+// The realtime presence channel (IrlRoom, the irl_world Colyseus room) is coarse+// BY CONSTRUCTION: a viewer's precise GPS is snapped to their own precision-6+// geocell centre plus bounded jitter and the raw fix is discarded, and the room+// never broadcasts a pin roster (pins travel ONLY over the per-viewer proximity+// read). This file locks both guarantees so a future edit that lets raw GPS+// survive — or repopulates the pins MapSchema — turns the build RED.+//+// Pure/offline: drives the real IrlRoom methods on a plain IrlState, no transport.++import { describe, it, expect, beforeEach } from 'vitest';++import { IrlRoom } from '../multiplayer/src/rooms/IrlRoom.js';+import { IrlState } from '../multiplayer/src/irl-schemas.js';+import { encodeGeohash, decodeGeohash } from '../multiplayer/src/geohash.js';++// A precise fix (sub-millimetre tail) somewhere ordinary.+const LAT = 37.77491234567;+const LNG = -122.41945678901;+const CELL = encodeGeohash(LAT, LNG, 6);++function makeRoom(cell = CELL) {+ const room = new IrlRoom();+ room.geocell = cell;+ room.state = new IrlState();+ room.state.geocell = cell;+ return room;+}+function client(sessionId) {+ return { sessionId, userData: {} };+}++describe('IrlRoom._coarseViewerPos — raw GPS never survives the server', () => {+ let room;+ beforeEach(() => { room = makeRoom(); });++ it('returns a point inside the viewer’s own geocell but NEVER equal to the input', () => {+ const cell = decodeGeohash(CELL);+ // Run many times: the jitter is random, so prove the invariant holds every draw.+ for (let i = 0; i < 200; i++) {+ const pos = room._coarseViewerPos(LAT, LNG);+ // The precise input must never be echoed back.+ expect(pos.lat).not.toBe(LAT);+ expect(pos.lng).not.toBe(LNG);+ // The coarsened point stays inside the cell it claims (centre ± half-extent).+ expect(Math.abs(pos.lat - cell.lat)).toBeLessThanOrEqual(cell.latErr);+ expect(Math.abs(pos.lng - cell.lng)).toBeLessThanOrEqual(cell.lngErr);+ }+ });++ it('the coarsened point is at least metres away from the true fix (not a rounding no-op)', () => {+ // A precision-6 cell is ~1.2 km; the centre is far from an arbitrary corner+ // fix, so the coarsened coordinate is a different place, not a trimmed float.+ const pos = room._coarseViewerPos(LAT, LNG);+ const dLatM = Math.abs(pos.lat - LAT) * 111_320;+ const dLngM = Math.abs(pos.lng - LNG) * 111_320 * Math.cos(LAT * Math.PI / 180);+ // At least one axis must differ by a real distance — the cell snap guarantees it.+ expect(dLatM + dLngM).toBeGreaterThan(1);+ });++ it('a viewer with no/invalid fix is placed at the room cell centre, never (0,0)', () => {+ const cell = decodeGeohash(CELL);+ const pos = room._coarseViewerPos(NaN, NaN);+ expect(Math.abs(pos.lat - cell.lat)).toBeLessThanOrEqual(cell.latErr);+ expect(Math.abs(pos.lng - cell.lng)).toBeLessThanOrEqual(cell.lngErr);+ // Null-island is the failure mode we explicitly forbid.+ expect(pos.lat === 0 && pos.lng === 0).toBe(false);+ });+});++describe('IrlRoom presence — only the coarse marker leaves the server', () => {+ let room;+ beforeEach(() => { room = makeRoom(); });++ it('onJoin stores the coarse position, never the raw GPS the client reported', () => {+ room.onJoin(client('s1'), { lat: LAT, lng: LNG, agent: 'agent-1' });+ const viewer = room.state.viewers.get('s1');+ expect(viewer).toBeTruthy();+ expect(viewer.lat).not.toBe(LAT);+ expect(viewer.lng).not.toBe(LNG);+ const cell = decodeGeohash(CELL);+ expect(Math.abs(viewer.lat - cell.lat)).toBeLessThanOrEqual(cell.latErr);+ expect(Math.abs(viewer.lng - cell.lng)).toBeLessThanOrEqual(cell.lngErr);+ });++ it('a default (non-ghost) viewer reveals no avatar — counted, never positioned-by-identity', () => {+ room.onJoin(client('s2'), { lat: LAT, lng: LNG, agent: 'agent-2' });+ const viewer = room.state.viewers.get('s2');+ expect(viewer.ghost).toBe(false);+ expect(viewer.avatar).toBe('');+ });+});++describe('IrlRoom — never broadcasts a pin roster', () => {+ it('the pins MapSchema stays empty after a join (pins ride the proximity read, not the socket)', () => {+ const room = makeRoom();+ room.onJoin(client('s1'), { lat: LAT, lng: LNG, agent: 'agent-1' });+ room.onJoin(client('s2'), { lat: LAT, lng: LNG, agent: 'agent-2' });+ // Presence is populated…+ expect(room.state.viewers.size).toBe(2);+ // …but the pin roster is NEVER populated by the realtime room. A non-empty+ // pins map here would mean a placement's coordinates leaked over the socket.+ expect(room.state.pins.size).toBe(0);+ });++ it('an interaction reaction carries no coordinate, token, or actor identity', () => {+ const room = makeRoom();+ const sent = [];+ room.broadcast = (event, payload) => sent.push({ event, payload });+ room._handleInteraction(client('s1'), { type: 'open', pinId: 'pin-abc' });+ expect(sent).toHaveLength(1);+ const { event, payload } = sent[0];+ expect(event).toBe('reaction');+ // Exactly the privacy-clean trio — nothing locational or identifying.+ expect(Object.keys(payload).sort()).toEqual(['pinId', 'ts', 'type']);+ expect(payload).not.toHaveProperty('lat');+ expect(payload).not.toHaveProperty('lng');+ expect(payload).not.toHaveProperty('deviceToken');+ expect(payload).not.toHaveProperty('viewer');+ });+});diff --git a/tests/irl-proximity-cue.test.js b/tests/irl-proximity-cue.test.jsnew file mode 100644index 000000000..2e92f6bf5--- /dev/null+++ b/tests/irl-proximity-cue.test.js@@ -0,0 +1,202 @@+// Proximity-arrival cue policy (src/irl/proximity-cue.js).+//+// The cue is the delight that makes a list-less, radar-less discovery model feel+// alive instead of dead: a haptic + chime + "look around" banner + an edge glow+// that points toward the nearest off-screen agent and fades once you turn to face+// it. All of that rides on this pure policy. These tests pin the two contracts the+// privacy model leans on — (1) the cue is rate-limited so a busy spot can't slot-+// machine the user, and (2) the directional math points a *direction* derived from+// the world offset the viewer already renders, never a coordinate, and tracks the+// agent live as the device rotates, fading the moment the agent is on-screen.++import { describe, it, expect } from 'vitest';++import {+ CUE_COOLDOWN_MS,+ shouldCueArrival,+ normalizeAngle,+ relativeBearing,+ isFacingAgent,+ edgeNudgePlacement,+ nearestAgent,+} from '../src/irl/proximity-cue.js';++describe('shouldCueArrival — global cooldown (no slot machine)', () => {+ it('fires the very first arrival (no prior cue)', () => {+ expect(shouldCueArrival(1000, null)).toBe(true);+ expect(shouldCueArrival(1000, undefined)).toBe(true);+ });++ it('suppresses a second arrival inside the cooldown window', () => {+ const t0 = 100000;+ expect(shouldCueArrival(t0, null)).toBe(true);+ // Ten agents drift in over the next few seconds — the band emits ten arrival+ // signals, but the user feels exactly one buzz until the cooldown lapses.+ expect(shouldCueArrival(t0 + 1000, t0)).toBe(false);+ expect(shouldCueArrival(t0 + CUE_COOLDOWN_MS - 1, t0)).toBe(false);+ });++ it('allows the next cue once the full cooldown has elapsed', () => {+ const t0 = 100000;+ expect(shouldCueArrival(t0 + CUE_COOLDOWN_MS, t0)).toBe(true);+ expect(shouldCueArrival(t0 + CUE_COOLDOWN_MS + 5000, t0)).toBe(true);+ });++ it('honours a custom cooldown override', () => {+ expect(shouldCueArrival(2000, 1000, 2000)).toBe(false);+ expect(shouldCueArrival(3000, 1000, 2000)).toBe(true);+ });++ it('never fires on a non-finite clock (defensive)', () => {+ expect(shouldCueArrival(NaN, null)).toBe(false);+ expect(shouldCueArrival(Infinity, null)).toBe(false);+ });++ it('treats a corrupt lastCueAt as "no prior cue" rather than blocking forever', () => {+ expect(shouldCueArrival(5000, NaN)).toBe(true);+ });+});++describe('normalizeAngle — shortest-turn wrapping', () => {+ it('leaves an in-range angle untouched', () => {+ expect(normalizeAngle(0)).toBe(0);+ expect(normalizeAngle(Math.PI / 4)).toBeCloseTo(Math.PI / 4, 10);+ });++ it('wraps past +π to the negative equivalent (shortest turn)', () => {+ // 270° clockwise is really 90° counter-clockwise.+ expect(normalizeAngle((3 * Math.PI) / 2)).toBeCloseTo(-Math.PI / 2, 10);+ });++ it('wraps a large multi-turn angle back into (-π, π]', () => {+ expect(normalizeAngle(Math.PI * 4 + 0.3)).toBeCloseTo(0.3, 10);+ expect(normalizeAngle(-Math.PI * 4 - 0.3)).toBeCloseTo(-0.3, 10);+ });+});++describe('relativeBearing — which way to turn (from a world offset, not coords)', () => {+ // Frame: +x screen-right, -z forward (camera looks down -z), cameraYaw 0 = ahead.+ it('reads 0 when the agent is dead ahead and the camera faces forward', () => {+ expect(relativeBearing(0, -10, 0)).toBeCloseTo(0, 6);+ });++ it('reads +π/2 (turn right) for an agent directly to the screen-right', () => {+ expect(relativeBearing(10, 0, 0)).toBeCloseTo(Math.PI / 2, 6);+ });++ it('reads -π/2 (turn left) for an agent directly to the screen-left', () => {+ expect(relativeBearing(-10, 0, 0)).toBeCloseTo(-Math.PI / 2, 6);+ });++ it('reads ±π for an agent directly behind the viewer', () => {+ expect(Math.abs(relativeBearing(0, 10, 0))).toBeCloseTo(Math.PI, 6);+ });++ it('tracks the agent live as the user rotates the camera', () => {+ // Agent fixed dead-ahead in the world; rotating the camera 90° right means the+ // agent is now 90° to the LEFT of the new view — the nudge must follow.+ const ahead = relativeBearing(0, -10, 0);+ const turnedRight = relativeBearing(0, -10, Math.PI / 2);+ expect(ahead).toBeCloseTo(0, 6);+ expect(turnedRight).toBeCloseTo(-Math.PI / 2, 6);+ });+});++describe('isFacingAgent — fade the nudge once the agent is on screen', () => {+ const halfFov = (70 * Math.PI) / 180 / 2; // ~35° half-FOV++ it('is true when the agent sits near the centre of the view cone', () => {+ expect(isFacingAgent(0, halfFov)).toBe(true);+ expect(isFacingAgent(halfFov * 0.5, halfFov)).toBe(true);+ });++ it('is false when the agent is outside the (inset) view cone — keep nudging', () => {+ expect(isFacingAgent(halfFov, halfFov)).toBe(false); // exactly at the edge+ expect(isFacingAgent(Math.PI, halfFov)).toBe(false); // directly behind+ expect(isFacingAgent(halfFov * 0.86, halfFov)).toBe(false); // just past the 0.85 inset+ });++ it('rejects non-finite inputs defensively', () => {+ expect(isFacingAgent(NaN, halfFov)).toBe(false);+ expect(isFacingAgent(0, NaN)).toBe(false);+ });+});++describe('edgeNudgePlacement — stable for the full ±π range (no projection flip)', () => {+ const W = 390;+ const H = 844; // iPhone-ish portrait+ const inset = 34;++ it('rides the top edge when the agent is dead ahead', () => {+ const { x, y, rotateDeg } = edgeNudgePlacement(0, W, H, inset);+ expect(x).toBeCloseTo(W / 2, 6); // centred horizontally+ expect(y).toBeCloseTo(inset, 6); // pinned to the top safe edge+ expect(rotateDeg).toBeCloseTo(0, 6); // arrow points straight up+ });++ it('rides the right edge and points right when the agent is to the right', () => {+ const { x, y, rotateDeg } = edgeNudgePlacement(Math.PI / 2, W, H, inset);+ expect(x).toBeCloseTo(W - inset, 6);+ expect(y).toBeCloseTo(H / 2, 6);+ expect(rotateDeg).toBeCloseTo(90, 6);+ });++ it('rides the left edge and points left when the agent is to the left', () => {+ const { x, y, rotateDeg } = edgeNudgePlacement(-Math.PI / 2, W, H, inset);+ expect(x).toBeCloseTo(inset, 6);+ expect(y).toBeCloseTo(H / 2, 6);+ expect(rotateDeg).toBeCloseTo(-90, 6);+ });++ it('rides the bottom edge and points down when the agent is behind (the key case)', () => {+ // The whole point of the cue: the agent is BEHIND you. Projection would flip+ // here; the bearing→ellipse map stays sane and tells you to look back/down.+ const { x, y, rotateDeg } = edgeNudgePlacement(Math.PI, W, H, inset);+ expect(x).toBeCloseTo(W / 2, 6);+ expect(y).toBeCloseTo(H - inset, 6);+ expect(Math.abs(rotateDeg)).toBeCloseTo(180, 6);+ });++ it('keeps the glow inside the safe-inset viewport for every bearing', () => {+ for (let deg = -180; deg <= 180; deg += 7) {+ const { x, y } = edgeNudgePlacement((deg * Math.PI) / 180, W, H, inset);+ expect(x).toBeGreaterThanOrEqual(inset - 1e-6);+ expect(x).toBeLessThanOrEqual(W - inset + 1e-6);+ expect(y).toBeGreaterThanOrEqual(inset - 1e-6);+ expect(y).toBeLessThanOrEqual(H - inset + 1e-6);+ }+ });++ it('never collapses the ellipse on a tiny viewport', () => {+ const { x, y } = edgeNudgePlacement(Math.PI / 3, 40, 40, 34);+ expect(Number.isFinite(x)).toBe(true);+ expect(Number.isFinite(y)).toBe(true);+ });+});++describe('nearestAgent — one clear "that way", never a cluster of arrows', () => {+ it('returns the closest of several in-range agents', () => {+ const agents = [+ { id: 'a', distance: 22 },+ { id: 'b', distance: 9 },+ { id: 'c', distance: 31 },+ ];+ expect(nearestAgent(agents).id).toBe('b');+ });++ it('returns null for an empty set', () => {+ expect(nearestAgent([])).toBeNull();+ });++ it('skips entries with a non-finite distance', () => {+ const agents = [+ { id: 'x', distance: NaN },+ { id: 'y', distance: 14 },+ ];+ expect(nearestAgent(agents).id).toBe('y');+ });++ it('returns null when no entry has a usable distance', () => {+ expect(nearestAgent([{ id: 'x' }, { id: 'y', distance: NaN }])).toBeNull();+ });+});diff --git a/workers/agent-sniper/README.md b/workers/agent-sniper/README.mdindex 7839fcde9..57080f270 100644--- a/workers/agent-sniper/README.md+++ b/workers/agent-sniper/README.md@@ -25,8 +25,9 @@ It is deliberately **not** a Vercel cron: hourly ticks can't snipe a launch.| `first-claim-watch.js` | `startFirstClaimWatch` — polls the fee-claim stream, scores first-ever claims, holds the owner-set delay, snipes via `executeBuy`. || `keys.js` | `loadAgentKeypair` — decrypts the agent secret via `recoverSolanaAgentKeypair`, TTL-cached, audited. || `trade-client.js` | Wraps `PumpTradeClient`; `signAndSend` assembles a v0 tx, signs with the agent keypair, broadcasts, confirms. |-| `executor.js` | `executeBuy` / `executeSell` — every guardrail, the idempotency lock, the only place that signs. |-| `positions.js` | `runPositionSweep` — re-quotes open positions and triggers exits. |+| `executor.js` | `executeBuy` / `executeSell` — every guardrail, the idempotency lock, the only place that signs. Routes graduated coins through the AMM. |+| `positions.js` | `runPositionSweep` — re-quotes open positions (curve OR AMM) and triggers exits. |+| `amm-exit.js` | `quoteAmmSell` / `buildAmmSellInstructions` / `isGraduated` — post-graduation AMM pricing + sell build (shared with the user-driven path's pool resolution). |State lives in two tables (migrations `…20260615020000_agent_sniper.sql` +`…20260615030000_sniper_first_claim.sql`): `agent_sniper_strategies` (owner-armed@@ -95,9 +96,26 @@ Arm a test agent (owned by you, wallet funded with a little SOL) by inserting astrategy row, then watch it score → open → exit. Flip to `SNIPER_MODE=live`with tiny caps to land one real trade. `Ctrl-C` drains in-flight buys and exits.-## Known gap (fast-follow)+## Graduated-position exit-Bonding-curve exits only. A position that **graduates** mid-hold can't be sold on-the curve — it's flagged `exit_reason='graduated'` and parked for the AMM-exit-follow-up (via `buildPumpSwapInnerIx`). Short `max_hold_seconds` / take-profit-keep most positions exiting before graduation in the meantime.+A position whose coin **graduates** off the bonding curve mid-hold is exited+automatically through the canonical pump AMM pool — it never parks. The+bonding-curve sell path detects graduation (the SDK's `CoinGraduatedError`), then+re-routes the same exit through `amm-exit.js` (`buildAmmSellInstructions`), which+reuses the platform's pool resolution (`getAmmPoolState`) and `PumpAmmSdk`+(`sellBaseInput`) — identical to the user-driven sell in `api/pump/[action].js`.+The slippage-derived min-out floor is embedded on-chain, so a thin post-graduation+pool can't sandwich the exit.++`runPositionSweep` re-quotes graduated positions off the AMM (not the dead curve),+so stop-loss / trailing / take-profit / timeout keep firing against the real+post-graduation price, and PnL is computed against the live AMM quote. A position+flagged `error='graduated:awaiting_amm_exit'` is re-quoted and exited on the next+sweep — no terminal park state.++To clear a backlog (or force the exit right after deploy instead of waiting for+the next poll), run the one-shot backfill — idempotent, honors `SNIPER_MODE`:++```bash+SNIPER_MODE=simulate node scripts/sniper-backfill-graduated.mjs+```diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex dba6cafa3..7ac80a4fd 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -261,8 +261,12 @@ export async function executeSell({ cfg, position, reason }) {} catch (err) {// A failed sell must NOT terminate the position — leave it 'open' so the// next tick retries the exit rather than stranding the bag as 'failed'.- await sql`UPDATE agent_sniper_positions SET status = 'open', error = ${errCode(err)}, last_quoted_at = now() WHERE id = ${position.id}`;- log.warn('sell failed (will retry)', { ...tag, code: errCode(err), err: err?.message });+ // Preserve the graduated marker so the retry stays on the AMM path instead+ // of bouncing back through the dead curve to rediscover graduation.+ const wasGraduated = typeof position.error === 'string' && position.error.startsWith('graduated');+ const errState = wasGraduated ? `graduated:amm_exit_retry:${errCode(err)}` : errCode(err);+ await sql`UPDATE agent_sniper_positions SET status = 'open', error = ${errState}, last_quoted_at = now() WHERE id = ${position.id}`;+ log.warn('sell failed (will retry)', { ...tag, code: errCode(err), graduated: wasGraduated, err: err?.message });return { status: 'retry', reason: errCode(err) };}});diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.jsindex 030c1d8be..417db3b7e 100644--- a/workers/agent-sniper/positions.js+++ b/workers/agent-sniper/positions.js@@ -10,6 +10,7 @@ import { log } from './log.js';import { getTradeCtx } from './trade-client.js';import { getOpenPositions } from './strategy-store.js';import { executeSell } from './executor.js';+import { quoteAmmSell } from './amm-exit.js';function pct(n) {const x = Number(n);@@ -41,28 +42,14 @@ async function tickPosition(cfg, pos) {return;}- const ctx = await getTradeCtx(cfg.network);- const mintPk = new ctx.web3.PublicKey(pos.mint);- const baseAmount = new ctx.BN(BigInt(pos.base_amount).toString());+ const baseAmount = new (await getTradeCtx(cfg.network)).BN(BigInt(pos.base_amount).toString());const slippagePct = (pos.slippage_bps ?? 500) / 100;+ const graduated = typeof pos.error === 'string' && pos.error.startsWith('graduated');- let value;- try {- const quote = await ctx.client.quoteForSell({ mint: mintPk, baseAmount, slippagePct });- value = Number(quote.expectedQuoteOut.toString());- } catch (err) {- if (err?.name === 'CoinGraduatedError') {- await sql`- UPDATE agent_sniper_positions- SET error = 'graduated:awaiting_amm_exit', exit_reason = 'graduated', last_quoted_at = now()- WHERE id = ${pos.id}- `;- log.warn('position graduated — needs AMM exit', { agent: pos.agent_id, mint: pos.mint });- return;- }- log.warn('position re-quote failed', { mint: pos.mint, err: err?.message });- return;- }+ const value = graduated+ ? await requoteGraduated(cfg, pos, baseAmount, slippagePct)+ : await requoteCurve(cfg, pos, baseAmount, slippagePct);+ if (value == null) return; // transient quote failure — try again next sweepconst prevPeak = Number(pos.peak_value_lamports || pos.entry_quote_lamports || 0);const peak = Math.max(prevPeak, value);@@ -76,6 +63,49 @@ async function tickPosition(cfg, pos) {if (reason) await executeSell({ cfg, position: pos, reason });}+// Re-quote a still-on-curve position off the bonding curve. On graduation, flag+// the position once so the NEXT sweep re-quotes it off the AMM (and executeSell+// routes the exit there) — never park it. Returns null on a transient failure.+async function requoteCurve(cfg, pos, baseAmount, slippagePct) {+ const ctx = await getTradeCtx(cfg.network);+ const mintPk = new ctx.web3.PublicKey(pos.mint);+ try {+ const quote = await ctx.client.quoteForSell({ mint: mintPk, baseAmount, slippagePct });+ return Number(quote.expectedQuoteOut.toString());+ } catch (err) {+ if (err?.name === 'CoinGraduatedError') {+ await sql`+ UPDATE agent_sniper_positions+ SET error = 'graduated:awaiting_amm_exit', last_quoted_at = now()+ WHERE id = ${pos.id} AND status = 'open'+ `;+ // Flag in-memory too so a same-tick executeSell takes the AMM branch+ // directly instead of re-hitting the dead curve.+ pos.error = 'graduated:awaiting_amm_exit';+ log.info('position graduated — switching to AMM exit', { agent: pos.agent_id, mint: pos.mint });+ // Quote off the AMM on the same tick so exit triggers fire immediately.+ return await requoteGraduated(cfg, pos, baseAmount, slippagePct);+ }+ log.warn('position re-quote failed', { mint: pos.mint, err: err?.message });+ return null;+ }+}++// Re-quote a graduated position off the canonical AMM pool. Same exit math, real+// post-graduation price. Returns null on a transient failure (pool not yet+// readable, RPC hiccup) so the position holds and retries rather than mis-exiting.+async function requoteGraduated(cfg, pos, baseAmount, slippagePct) {+ try {+ const { expectedQuoteOut } = await quoteAmmSell({+ network: cfg.network, mint: pos.mint, baseAmount, slippagePct,+ });+ return Number(expectedQuoteOut);+ } catch (err) {+ log.warn('amm re-quote failed', { mint: pos.mint, code: err?.code, err: err?.message });+ return null;+ }+}+/** Run one sweep over all open positions. Errors on one position never abort the rest. */export async function runPositionSweep(cfg) {let positions;