Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Simplify IRL pins to direct room-anchor, drop realtime publish channel

nirholasa4e650d3f41c
diff --git a/api/_lib/irl-publish.js b/api/_lib/irl-publish.js
deleted file mode 100644
index 323efeaca..000000000
--- a/api/_lib/irl-publish.js
+++ /dev/null
@@ -1,60 +0,0 @@
-// IRL realtime publish transport — the Vercel→Colyseus webhook for D1 live pin
-// sync. This is the single place that actually talks to the multiplayer host;
-// callers (api/irl/pins.js lifecycle, api/_lib/irl-realtime.js reskin hook) hand
-// it a typed pin change and never block on the result.
-//
-// Vercel functions can't hold a WebSocket, so when a pin is placed / moved /
-// re-skinned / removed we fire a signed HTTP webhook at the standalone Colyseus
-// host, which fans the change into the matching geocell room as a schema delta
-// every viewer there receives within the patch interval. Best-effort by design:
-// the pin is already persisted in Neon and every viewer's poll fallback / next
-// room load reconciles it, so a publish failure degrades to "slightly slower",
-// never to data loss. Never awaited on a request's critical path.
-//
-// Keep byte-for-byte in sync with the verifier (multiplayer/src/irl-publish-auth.js):
-// signed = `irl:<geocell>:<type>:<ts>:<base64url(sha256(JSON(pin)))>`
-// sig = base64url(HMAC_SHA256(MULTIPLAYER_SHARED_SECRET, signed))
-
-import { env } from './env.js';
-import { hmacSha256, sha256Base64Url } from './crypto.js';
-
-const PUBLISH_TYPES = new Set(['pin:add', 'pin:update', 'pin:remove']);
-
-/**
- * Publish a pin change to the multiplayer host. Returns a small result object;
- * callers fire-and-forget (`void publishIrlPin(...)`) and never block on it.
- * @param {'pin:add'|'pin:update'|'pin:remove'} type
- * @param {string} geocell precision-6 cell the pin lives in
- * @param {object} pin wire object — full ({ id, lat, lng, heading, avatarUrl, … })
- * for add, a partial subset for update, or just { id } for remove
- */
-export async function publishIrlPin(type, geocell, pin = {}) {
- if (!PUBLISH_TYPES.has(type)) return { delivered: false, reason: 'bad_type' };
- if (typeof geocell !== 'string' || !geocell) return { delivered: false, reason: 'no_geocell' };
- const base = env.MULTIPLAYER_INTERNAL_URL;
- if (!base) return { delivered: false, reason: 'unconfigured' };
- try {
- const ts = Math.floor(Date.now() / 1000);
- const pinHash = await sha256Base64Url(JSON.stringify(pin ?? {}));
- const sig = await hmacSha256(
- env.MULTIPLAYER_SHARED_SECRET,
- `irl:${geocell}:${type}:${ts}:${pinHash}`,
- );
- const res = await fetch(`${base}/internal/irl-publish`, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- 'x-mp-signature': sig,
- 'x-mp-timestamp': String(ts),
- },
- body: JSON.stringify({ geocell, type, pin }),
- signal: AbortSignal.timeout(2500),
- });
- if (!res.ok) return { delivered: false, reason: `http_${res.status}` };
- const body = await res.json().catch(() => ({}));
- const count = Number(body?.delivered) || 0;
- return { delivered: count > 0, count };
- } catch (err) {
- return { delivered: false, reason: err?.name === 'TimeoutError' ? 'timeout' : 'error' };
- }
-}
diff --git a/api/_lib/irl-realtime.js b/api/_lib/irl-realtime.js
deleted file mode 100644
index b7a5adbf6..000000000
--- a/api/_lib/irl-realtime.js
+++ /dev/null
@@ -1,66 +0,0 @@
-// IRL realtime fan-out — the single server-side emit point for pin lifecycle
-// events that co-located viewers react to in real time.
-//
-// Epic D owns the actual WS/geohash transport. Until it lands, this is a hook,
-// not a live channel: it computes the geohash room a change belongs to and the
-// minimal payload a viewer needs to swap a pin's rendered GLB in place, then
-// hands them to whatever transport is wired (none yet). The DURABLE contract is
-// the poll path — src/irl.js loadNearbyPins diffs avatar_version on its next
-// cycle and swaps the GLB — so propagation is correct with or without D1; this
-// hook only makes it feel instant once realtime exists.
-//
-// Wiring D1: implement publishPinEvent() to push `event` to room `irl:<room>`
-// (e.g. d1.publish(`irl:${room}`, event)). Every caller already routes through
-// here, so that one function is the only thing realtime has to fill in.
-
-import { encodeGeohash } from './geohash.js';
-
-// ~1.2 km cells (precision 6) — coarse enough that a viewer within the 150 m
-// nearby radius always shares (or borders) the changed pin's room, fine enough
-// that a city-wide change doesn't wake every client. The transport can fan a
-// change out to the cell plus its 8 neighbours when it lands; the poll fallback
-// covers any edge a single cell misses.
-const ROOM_PRECISION = 6;
-
-function roomFor(lat, lng) {
- if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
- return encodeGeohash(lat, lng, ROOM_PRECISION) || null;
-}
-
-// D1 transport: a re-skin is a PARTIAL pin:update carrying only the new
-// avatar_url, so the geocell room swaps the GLB without disturbing the pin's
-// other live fields. Best-effort — the import is lazy so this file stays cheap to
-// load, and any transport error is swallowed by the caller (Rule 9: a realtime
-// hiccup must never fail the owner's save; the poll path still propagates).
-async function publishPinEvent(room, event) {
- if (!room || !event?.id) return false;
- const pin = { id: event.id };
- if (event.avatar_url) pin.avatarUrl = event.avatar_url;
- const { publishIrlPin } = await import('./irl-publish.js');
- const res = await publishIrlPin('pin:update', room, pin);
- return !!res?.delivered;
-}
-
-/**
- * Emit a `pin_updated` event so co-located viewers swap a re-skinned pin's GLB
- * without waiting for their next nearby poll. Best-effort and non-throwing —
- * the caller never awaits propagation, and the poll path is authoritative.
- *
- * @param {object} pin { id, lat, lng, avatar_url, avatar_version }
- * @returns {{ room: string|null, event: object }} the room + payload that was emitted
- */
-export function emitPinUpdated(pin) {
- const room = roomFor(Number(pin?.lat), Number(pin?.lng));
- const event = {
- type: 'pin_updated',
- id: pin?.id,
- avatar_url: pin?.avatar_url ?? null,
- avatar_version: Number(pin?.avatar_version) || 0,
- };
- if (room) {
- // Fire-and-forget; swallow transport errors (Rule 9 — a realtime hiccup
- // must never fail the owner's save, and the poll fallback still propagates).
- Promise.resolve(publishPinEvent(room, event)).catch(() => {});
- }
- return { room, event };
-}
diff --git a/api/irl/pins.js b/api/irl/pins.js
index 01828cff7..b3aa2f82a 100644
--- a/api/irl/pins.js
+++ b/api/irl/pins.js
@@ -1,7 +1,7 @@
/**
* IRL GPS Pins — place 3D agents at real-world GPS coordinates.
*
- * GET /api/irl/pins?lat=&lng=&radius=150 nearby pins (public)
+ * GET /api/irl/pins?lat=&lng=&radius=40 nearby pins (public, tight proximity)
* GET /api/irl/pins/mine?deviceToken= my pins (device token or auth)
* GET /api/irl/pins?mine=1 my pins (auth required)
* POST /api/irl/pins { lat, lng, heading, avatarUrl, avatarName, caption, agentId }
@@ -12,7 +12,6 @@
* POST /api/irl/pins/interact { pinId, event, deviceToken } log a tap/view
*/
-import { timingSafeEqual } from 'node:crypto';
import { cors, json, wrap, rateLimited } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
@@ -20,9 +19,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { WORD_BLACKLIST } from '../../src/profanity.js';
import { guardianConfig, assess, decide } from '../_lib/granite-guardian.js';
import { encodeGeohash } from '../_lib/geohash.js';
-import { publishIrlPin } from '../_lib/irl-publish.js';
import { validateAppearance } from '../_lib/accessories.js';
-import { emitPinUpdated } from '../_lib/irl-realtime.js';
// ── Moderation, safety & density caps (D4) ──────────────────────────────────
// Everything below makes the public, shared IRL world safe to launch: content
@@ -328,9 +325,8 @@ async function handleCalibrate(res, { id, session, body }) {
WHERE id = ${id}
RETURNING id, lat, lng, heading, anchor_yaw_deg, anchor_height_m, gps_accuracy_m
`;
- // Realtime (D1): a calibrate is a partial pin:update of position + heading, so
- // every nearby viewer sees the corrected spot move live instead of on re-fetch.
- void publishIrlPin('pin:update', realtimeCell(row.lat, row.lng), pinWire(row));
+ // The corrected spot reaches nearby viewers on their next proximity poll — pin
+ // positions are never broadcast as a roster, only read by someone standing near it.
return json(res, 200, { pin: row, calibrated: true });
}
@@ -340,9 +336,8 @@ async function handleCalibrate(res, { id, session, body }) {
// slot/preset allow-list the studio uses, bake a new GLB onto the pin's clean
// BASE avatar (never the prior bake — so layers/accessories can't stack), store
// it on the first-party CDN, bump avatar_version, and persist. Every nearby
-// viewer's loadNearbyPins poll then diffs the version and swaps the GLB; D1
-// (emitPinUpdated) pushes it instantly once realtime lands. A null/empty
-// manifest reverts the pin to its bare base avatar.
+// viewer's loadNearbyPins poll then diffs the version and swaps the GLB. A
+// null/empty manifest reverts the pin to its bare base avatar.
async function handleOutfitChange(res, { id, session, body }) {
const manifest = body.avatar_manifest ?? body.avatarManifest ?? null;
if (manifest !== null && (typeof manifest !== 'object' || Array.isArray(manifest))) {
@@ -400,88 +395,23 @@ async function handleOutfitChange(res, { id, session, body }) {
`;
if (!row) return json(res, 404, { error: 'not found' });
- // Realtime fan-out (D1) — co-located viewers swap the GLB within seconds
- // without waiting for their next poll. No-op until D1 lands; the poll path
- // (avatar_version diff) is the durable contract either way.
- emitPinUpdated(row);
-
+ // The re-skin reaches co-located viewers on their next proximity poll, which
+ // diffs avatar_version and swaps the GLB. There is no realtime fan-out: a pin's
+ // data only travels to a viewer who is physically near it.
return json(res, 200, { pin: row });
}
-// ── Realtime publish helpers (D1) ───────────────────────────────────────────
-// The irl_world room is keyed by a precision-6 geocell (~1.2 km), the coarse cell
-// every nearby viewer joins. Matches src/irl-net.js and multiplayer/src/rooms/
-// IrlRoom.js so a publish always lands in the right live room. (The committed
-// geocell7/GEOCELL_PRECISION column is the FINER precision-7 cell used for the D4
-// density cap — a different lattice; both derive from the same encoder.)
-const REALTIME_PRECISION = 6;
-function realtimeCell(lat, lng) {
- return encodeGeohash(Number(lat), Number(lng), REALTIME_PRECISION);
-}
-
-// Build the camelCase wire object the room consumes from a DB row, including ONLY
-// the columns the row actually has. An add returns the full row (RETURNING *) so
-// every field rides; an update / calibrate returns a narrow column set, so only
-// those become a partial pin:update — the room never zeroes a field the caller
-// didn't touch.
-function pinWire(row) {
- const w = { id: row.id };
- if ('lat' in row) w.lat = Number(row.lat);
- if ('lng' in row) w.lng = Number(row.lng);
- if ('heading' in row) w.heading = Number(row.heading) || 0;
- if ('avatar_url' in row) w.avatarUrl = row.avatar_url ?? '';
- if ('avatar_name' in row) w.avatarName = row.avatar_name ?? '';
- if ('caption' in row) w.caption = row.caption ?? '';
- if ('x402_endpoint' in row) w.x402Endpoint = row.x402_endpoint ?? '';
- if ('agent_id' in row) w.agentId = row.agent_id ?? '';
- if ('placed_at' in row) w.placedAt = row.placed_at ? Date.parse(row.placed_at) || 0 : 0;
- // Room frame — emit camelCase so the realtime publish wire matches the schema
- // field names IrlRoom.coerceRoom reads. Only present when the row carries them.
- if ('room_id' in row) w.roomId = row.room_id ?? '';
- if ('rel_east_m' in row) w.relEast = Number(row.rel_east_m) || 0;
- if ('rel_north_m' in row) w.relNorth = Number(row.rel_north_m) || 0;
- if ('origin_lat' in row) w.originLat = Number(row.origin_lat) || 0;
- if ('origin_lng' in row) w.originLng = Number(row.origin_lng) || 0;
- if ('origin_yaw_deg' in row) w.originYawDeg = Number(row.origin_yaw_deg) || 0;
- return w;
-}
-
-// ── Internal hydration auth (bulk location-scrape guard) ────────────────────
-// The bbox feed is server-to-server only: the Colyseus irl_world room loads its
-// 3×3 geocell window through it on room create. Unlike the nearby feed (capped
-// at a 500 m radius / 50 pins), bbox returns up to 500 pins over a multi-km box,
-// so an OPEN bbox endpoint would let anyone grid the planet and bulk-download
-// every placement's exact GPS. Gate it on the same shared multiplayer secret the
-// publish webhook already uses; the only caller is IrlRoom, which sends the
-// header. Secret resolution is kept byte-for-byte in sync with
-// multiplayer/src/irl-publish-auth.js (multiplayerSecret).
-function internalSecret() {
- return (
- process.env.MULTIPLAYER_SHARED_SECRET ||
- process.env.HOLDER_PASS_SECRET ||
- 'dev-insecure-multiplayer-secret'
- );
-}
-function internalRequestOk(req) {
- const provided = req.headers?.['x-mp-internal'];
- if (typeof provided !== 'string' || !provided) return false;
- const a = Buffer.from(provided);
- const b = Buffer.from(internalSecret());
- return a.length === b.length && timingSafeEqual(a, b);
-}
-
export default wrap(async (req, res) => {
cors(req, res, { methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'] });
if (req.method === 'OPTIONS') return res.end();
await ensureTable();
- // Public GET reads (the nearby feed + my-pins) are IP rate-limited so the
- // precise-coordinate feed can't be systematically gridded into a bulk location
- // scrape. A legit viewer polls nearby every ~15 s (≈4/min) — well under the
- // 60/min public ceiling — while a scripted sweep trips it fast. The bbox
- // hydration path is excluded here: it's gated separately as internal-only.
- if (req.method === 'GET' && req.query.bbox == null) {
+ // Every public GET read (the nearby feed + my-pins) is IP rate-limited so the
+ // tight proximity feed can't be systematically gridded into a bulk location
+ // scrape. A legit viewer polls nearby every ~10 s (≈6/min) — well under the
+ // 60/min public ceiling — while a scripted sweep trips it fast.
+ if (req.method === 'GET') {
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
}
@@ -526,51 +456,21 @@ export default wrap(async (req, res) => {
return json(res, 200, { pins: rows });
}
- // ── GET — pins in a bounding box (IRL realtime room hydration, D1) ─────────
- // The Colyseus irl_world room loads its 3×3 geocell window on create through
- // this box query (server-to-server). Same public projection as the nearby feed
- // — never owner ids — but selected by an explicit lat/lng box instead of a
- // radius, because a 3×3 precision-6 window (~3.6 km) exceeds the nearby radius
- // cap. Reuses the existing lat/lng index; capped + size-guarded against scrapes.
- if (req.method === 'GET' && req.query.bbox != null) {
- // Internal-only: a valid shared-secret header proves this is the Colyseus
- // room hydrating its window, not a public scraper. Without it, refuse — the
- // public nearby feed (radius-capped) is the only location read the open web
- // gets. 403 (not 401) so a scanner learns nothing about credentials.
- if (!internalRequestOk(req)) return json(res, 403, { error: 'forbidden' });
-
- const parts = String(req.query.bbox).split(',').map((s) => parseFloat(s));
- if (parts.length !== 4 || parts.some((n) => !isFinite(n))) {
- return json(res, 400, { error: 'bbox must be minLat,minLng,maxLat,maxLng' });
- }
- let [minLat, minLng, maxLat, maxLng] = parts;
- if (minLat > maxLat) [minLat, maxLat] = [maxLat, minLat];
- if (minLng > maxLng) [minLng, maxLng] = [maxLng, minLng];
- // A legit 3×3 precision-6 window is ~0.03°; 0.2° (~22 km) is a generous
- // ceiling that still rejects a wide-area harvest even from an internal caller.
- if ((maxLat - minLat) > 0.2 || (maxLng - minLng) > 0.2) {
- return json(res, 400, { error: 'bbox too large' });
- }
- const rows = await sql`
- SELECT id, agent_id, lat, lng, heading,
- avatar_url, avatar_name, caption, x402_endpoint, placed_at, avatar_version,
- room_id, rel_east_m, rel_north_m, origin_lat, origin_lng, origin_yaw_deg
- FROM irl_pins
- WHERE lat BETWEEN ${minLat} AND ${maxLat}
- AND lng BETWEEN ${minLng} AND ${maxLng}
- AND hidden_at IS NULL
- AND (expires_at IS NULL OR expires_at > NOW())
- ORDER BY placed_at DESC
- LIMIT 500
- `;
- return json(res, 200, { pins: rows });
- }
-
- // ── GET — nearby pins ─────────────────────────────────────────────────────
+ // ── GET — nearby pins (the ONLY way another agent's location is revealed) ──
+ // A placed agent is private by location: its coordinates reach a viewer only
+ // through this read, and only when that viewer is physically within a tight
+ // radius of it — so an agent is "stumbled upon" in AR by someone standing near
+ // it, never handed out as a browseable roster/map. There is no bbox/window
+ // feed and no realtime broadcast of pins: the radius is hard-capped small, the
+ // caller's own lat/lng is required, and the read is IP rate-limited above so a
+ // scripted grid-sweep can't reconstruct the map.
if (req.method === 'GET') {
const lat = parseFloat(req.query.lat);
const lng = parseFloat(req.query.lng);
- const radius = Math.min(500, Math.max(10, parseFloat(req.query.radius ?? '150')));
+ // Tight proximity gate: default 40 m, hard-capped at 60 m. Large enough to
+ // render an agent as you walk up and point your camera at its spot, small
+ // enough that one read only ever exposes the handful right where you stand.
+ const radius = Math.min(60, Math.max(10, parseFloat(req.query.radius ?? '40')));
if (!isFinite(lat) || !isFinite(lng)) {
return json(res, 400, { error: 'lat and lng are required' });
@@ -843,11 +743,9 @@ export default wrap(async (req, res) => {
RETURNING *
`;
- // Realtime (D1): fan this placement to every viewer in the geocell so it
- // appears on their screen within ~1 s, no reload. Fire-and-forget — the pin
- // is already persisted and the poll fallback reconciles if the push drops.
- void publishIrlPin('pin:add', realtimeCell(lat, lng), pinWire(pin));
-
+ // No realtime fan-out: a new placement is never broadcast as a roster. It
+ // surfaces to a viewer only on their next proximity poll, and only once they
+ // are physically within the nearby radius of where it was dropped.
return json(res, 201, { pin: { ...pin, permanent: expiresAt === null } });
}
@@ -940,10 +838,8 @@ export default wrap(async (req, res) => {
`;
if (!row) return json(res, 404, { error: 'not found' });
- // Realtime (D1): push the edit live to nearby viewers. pinWire carries only
- // the RETURNING columns, so it's a partial pin:update — untouched fields stay.
- void publishIrlPin('pin:update', realtimeCell(row.lat, row.lng), pinWire(row));
-
+ // The edit reaches nearby viewers on their next proximity poll — never as a
+ // broadcast. A pin's fields only travel to someone physically near it.
return json(res, 200, { pin: row });
}
@@ -983,9 +879,8 @@ export default wrap(async (req, res) => {
if (!result.length) {
return json(res, 404, { error: 'pin not found or not yours' });
}
- // Realtime (D1): tell every nearby viewer to remove the pin live.
- const gone = result[0];
- void publishIrlPin('pin:remove', realtimeCell(gone.lat, gone.lng), { id: gone.id });
+ // A removed pin simply stops appearing in nearby viewers' next proximity
+ // poll; there is no realtime remove broadcast to fan out.
return json(res, 200, { ok: true });
}
diff --git a/api/irl/report.js b/api/irl/report.js
index 9166a6d1e..4d142352b 100644
--- a/api/irl/report.js
+++ b/api/irl/report.js
@@ -24,15 +24,9 @@ import { cors, json, wrap, rateLimited } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { publishIrlPin } from '../_lib/irl-publish.js';
-import { encodeGeohash } from '../_lib/geohash.js';
// Distinct reporters required before a pin is queued out of public view.
const REPORT_HIDE_THRESHOLD = 3;
-// The irl_world realtime room is keyed by a precision-6 geocell (~1.2 km) — match
-// REALTIME_PRECISION in api/irl/pins.js so a hide publishes into the same live room
-// the pin's add/update/delete events used.
-const REALTIME_PRECISION = 6;
const MAX_REASON_LEN = 240;
// Canonical reasons the UI offers; anything else collapses to 'other'. Kept as a
// closed set so the (future) review console can triage by category.
@@ -140,21 +134,10 @@ export default wrap(async (req, res) => {
RETURNING id
`;
hidden = rows.length > 0;
- // Realtime (D1): the first reporter to cross the threshold pushes a pin:remove
- // into the pin's geocell room, so every co-located viewer who already has it
- // loaded sees it vanish within ~1 s — not just on their next nearby re-fetch.
- // Guarded on the conditional UPDATE above so concurrent reports fire it once.
- // Fire-and-forget: the hide is already persisted and the hidden_at filter on
- // every read path is the durable contract if the push drops.
- const plat = Number(pin.lat);
- const plng = Number(pin.lng);
- if (hidden && Number.isFinite(plat) && Number.isFinite(plng)) {
- void publishIrlPin(
- 'pin:remove',
- encodeGeohash(plat, plng, REALTIME_PRECISION),
- { id: pinId },
- );
- }
+ // Once hidden, the pin stops appearing in every read path (all are filtered
+ // on hidden_at IS NULL), so a co-located viewer drops it on their next
+ // proximity poll. There is no realtime remove broadcast — a pin's location
+ // is never fanned out to a room, so neither is its removal.
}
return json(res, 200, { ok: true, reports: n, hidden });
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index 5222350c8..c4de86855 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -26,8 +26,6 @@ import { worldPersistence } from './persistence.js';
import { flushAllPlayers } from './playerStore.js';
import { socialHub } from './social-hub.js';
import { verifyNotifySignature } from './presence-token.js';
-import { irlRegistry } from './irl-registry.js';
-import { verifyIrlPublish } from './irl-publish-auth.js';
const PORT = Number(process.env.PORT || 2567);
const HOST = process.env.HOST || '0.0.0.0';
@@ -94,26 +92,11 @@ app.post('/internal/notify', express.json({ limit: '16kb' }), (req, res) => {
res.json({ delivered });
});
-// IRL realtime pin publish webhook (D1). Vercel can't hold a WebSocket, so when
-// the three.ws API mutates a pin (/api/irl/pins POST/PATCH/DELETE) it fires this
-// signed webhook; we fan the change into every live geocell room whose 3×3 window
-// covers the pin's cell, where it becomes a Colyseus schema delta the viewers
-// there receive within the patch interval. HMAC-signed with the shared secret and
-// bound to the exact body + a fresh timestamp, so only the API can inject pin
-// changes and a captured request can't be replayed or tampered.
-app.post('/internal/irl-publish', express.json({ limit: '32kb' }), (req, res) => {
- const { geocell, type, pin } = req.body || {};
- const sig = req.headers['x-mp-signature'];
- const ts = req.headers['x-mp-timestamp'];
- if (typeof geocell !== 'string' || typeof type !== 'string' || !geocell || !type) {
- return res.status(400).json({ error: 'bad_request' });
- }
- if (!verifyIrlPublish(geocell, type, pin || {}, ts, sig)) {
- return res.status(401).json({ error: 'bad_signature' });
- }
- const delivered = irlRegistry.dispatch(geocell, type, pin || {});
- res.json({ delivered });
-});
+// The IRL world (irl_world) is a presence + reaction room only — it is NOT a pin
+// transport. Placed agents are private by location and reach a viewer solely via
+// the per-viewer /api/irl/pins proximity read when they are physically near one,
+// so there is no pin-publish webhook here: nothing fans pin coordinates into a
+// room to be broadcast to every client. See rooms/IrlRoom.js.
// Admin monitor UI — exposes live room/client state, so it must NOT be open to
// the world in production. Mount it only when protected by basic-auth creds
diff --git a/multiplayer/src/irl-publish-auth.js b/multiplayer/src/irl-publish-auth.js
deleted file mode 100644
index eadd76861..000000000
--- a/multiplayer/src/irl-publish-auth.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// Verifier for the IRL pin publish webhook (POST /internal/irl-publish).
-//
-// Vercel can't hold a WebSocket, so when the three.ws API mutates a pin
-// (POST/PATCH/DELETE /api/irl/pins) it fires this signed HTTP webhook at the
-// standalone Colyseus host, which fans the change into the matching geocell room
-// as a schema patch. The signature binds the request to the exact delivered body
-// and a fresh timestamp, so a captured tuple can't be replayed with a different
-// pin or after the freshness window.
-//
-// Keep byte-for-byte in sync with the API signer (api/_lib/irl-realtime.js):
-// signed = `irl:<geocell>:<type>:<ts>:<base64url(sha256(JSON(pin)))>`
-// sig = base64url(HMAC_SHA256(secret, signed))
-// secret = MULTIPLAYER_SHARED_SECRET (→ HOLDER_PASS_SECRET → public dev secret),
-// the same fallback chain presence-token.js / persistence.js use.
-
-import crypto from 'node:crypto';
-
-// The shared secret this Colyseus host proves identity with — both as the
-// verifier of inbound publish webhooks AND as the bearer the room presents when
-// it hydrates pins from the internal-only bbox feed (api/irl/pins.js). Kept as
-// one resolver so the two directions can never drift. Mirrors the API-side
-// internalSecret() in api/irl/pins.js byte-for-byte.
-export function multiplayerSecret() {
- return (
- process.env.MULTIPLAYER_SHARED_SECRET ||
- process.env.HOLDER_PASS_SECRET ||
- 'dev-insecure-multiplayer-secret'
- );
-}
-
-function secret() {
- return multiplayerSecret();
-}
-
-function timingSafeEqualStr(a, b) {
- const ab = Buffer.from(String(a || ''));
- const bb = Buffer.from(String(b || ''));
- if (ab.length !== bb.length) return false;
- return crypto.timingSafeEqual(ab, bb);
-}
-
-// Maximum age (seconds) an irl-publish signature stays valid. The API mints and
-// delivers within a couple of round-trips, so a tight window bounds replay while
-// clearing normal network + clock-skew jitter. Mirrors NOTIFY_MAX_AGE_S.
-const PUBLISH_MAX_AGE_S = 120;
-
-export function verifyIrlPublish(geocell, type, pin, ts, sig) {
- if (typeof sig !== 'string' || !sig) return false;
- if (typeof geocell !== 'string' || typeof type !== 'string') return false;
- const tsNum = Number(ts);
- if (!Number.isFinite(tsNum)) return false;
- const nowS = Math.floor(Date.now() / 1000);
- if (Math.abs(nowS - tsNum) > PUBLISH_MAX_AGE_S) return false;
- const pinHash = crypto
- .createHash('sha256')
- .update(JSON.stringify(pin ?? {}))
- .digest('base64url');
- const expected = crypto
- .createHmac('sha256', secret())
- .update(`irl:${geocell}:${type}:${tsNum}:${pinHash}`)
- .digest('base64url');
- return timingSafeEqualStr(sig, expected);
-}
diff --git a/multiplayer/src/irl-registry.js b/multiplayer/src/irl-registry.js
deleted file mode 100644
index 0bb99d9bd..000000000
--- a/multiplayer/src/irl-registry.js
+++ /dev/null
@@ -1,68 +0,0 @@
-// IRL room registry — the lookup that lets the HTTP publish webhook find the live
-// Colyseus room(s) a pin change belongs to.
-//
-// Colyseus routes WebSocket traffic through the matchmaker, but the publish
-// webhook arrives as a plain Express POST with no room context. Each IrlRoom
-// registers itself here under its CENTRE geocell on create and unregisters on
-// dispose; the webhook then resolves the rooms whose 3×3 window covers a pin's
-// cell and patches their state directly.
-//
-// Why fan out to neighbours: a room centred on cell C holds pins for C plus its 8
-// neighbours. A pin in cell P therefore belongs in every room whose window
-// includes P — i.e. every room centred on P or one of P's neighbours. Geohash
-// 8-neighbour adjacency is symmetric, so the set of covering centres is exactly
-// { P } ∪ neighbours(P). We register by centre and dispatch over that 9-cell set.
-
-import { geohashNeighbors } from './geohash.js';
-
-class IrlRegistry {
- constructor() {
- this._byCell = new Map(); // centre geocell → Set<IrlRoom>
- }
-
- register(cell, room) {
- if (!cell || !room) return;
- let set = this._byCell.get(cell);
- if (!set) {
- set = new Set();
- this._byCell.set(cell, set);
- }
- set.add(room);
- }
-
- unregister(cell, room) {
- const set = this._byCell.get(cell);
- if (!set) return;
- set.delete(room);
- if (set.size === 0) this._byCell.delete(cell);
- }
-
- // Apply a pin change to every room whose window covers `cell`. Returns how many
- // rooms received it (0 = nobody is watching this area right now, which is fine —
- // the pin is already persisted and the next viewer to join loads it from Neon).
- dispatch(cell, type, pin) {
- if (!cell) return 0;
- const centres = [cell, ...geohashNeighbors(cell)];
- const seen = new Set();
- let delivered = 0;
- for (const c of centres) {
- const set = this._byCell.get(c);
- if (!set) continue;
- for (const room of set) {
- if (seen.has(room)) continue;
- seen.add(room);
- try {
- room.applyPublish(type, pin);
- delivered++;
- } catch (err) {
- console.warn('[irl-registry] applyPublish threw:', err?.message);
- }
- }
- }
- return delivered;
- }
-}
-
-// One registry shared by every IrlRoom in the process — that shared map is what
-// lets the stateless webhook reach the right live rooms.
-export const irlRegistry = new IrlRegistry();
diff --git a/multiplayer/src/rooms/IrlRoom.js b/multiplayer/src/rooms/IrlRoom.js
index 5469a8aad..5e97a03c2 100644
--- a/multiplayer/src/rooms/IrlRoom.js
+++ b/multiplayer/src/rooms/IrlRoom.js
@@ -1,34 +1,27 @@
-// IrlRoom — the realtime broadcast hub for the three.ws /irl world (D1).
+// IrlRoom — the realtime presence + reaction hub for the three.ws /irl world.
//
-// Unlike WalkRoom, this room is NOT the source of truth. Neon (via the Vercel API
-// at /api/irl/pins) owns the pins; this room is a live mirror of the pins inside
-// one geocell window, so every viewer standing in that cell sees a place / move /
-// remove the instant it happens instead of on their next poll.
+// This room is deliberately NOT a pin transport. Placed agents are private by
+// location: a pin's coordinates (and, for a shared room, its origin + offsets)
+// are revealed only to a viewer who is physically within the nearby radius of it
+// — through the per-viewer /api/irl/pins proximity read — never broadcast here as
+// a browseable roster. An earlier design synced every pin in a ~3.6 km geocell
+// window into this room's state and delta-broadcast it to every connected client,
+// which handed anyone who joined a cell the exact GPS of every agent across a
+// neighbourhood. That roster broadcast is gone: pins never enter the synced state
+// and never leave the server over this socket.
//
-// Data flow:
-// - onCreate loads the cell's current pins from the API into state.pins.
-// - A Vercel POST/PATCH/DELETE on a pin fires the signed /internal/irl-publish
-// webhook → irlRegistry.dispatch → this room's applyPublish() patches the
-// MapSchema → Colyseus delta-broadcasts to everyone in the room.
-// - A late joiner is handed the whole MapSchema on connect (schema sync), so it
-// never misses pins that were placed before it arrived.
-//
-// The room holds a 3×3 geocell window (centre + up to 8 neighbours) so a pin that
-// straddles a cell edge within the client's nearby radius is still present in the
-// stream; the client does the final per-viewer radius filtering.
-//
-// Presence (live viewers) is D2 — onJoin adds a viewer at the cell centre +
-// bounded jitter (NEVER precise GPS), heartbeats refresh it, and a reaper prunes
-// the stale ones; Colyseus delta-broadcasts the `viewers` map so every client
-// derives the "N viewing nearby" count and optional ghost markers for free.
-// Interaction reactions are D3. Moderation / caps are D4.
+// What this room DOES carry, both privacy-clean by construction:
+// - Presence (D2): each viewer is added at their own precision-6 cell centre +
+// bounded jitter (NEVER precise GPS), heartbeats refresh liveness, a reaper
+// prunes the stale ones; Colyseus delta-broadcasts the `viewers` map so every
+// client derives the "N viewing nearby" count and optional opt-in ghosts.
+// - Reactions (D3): an ambient { pinId, type, ts } flourish so a co-located
+// agent visibly emotes for bystanders. No GPS, no wallet, no actor identity.
import { Room } from '@colyseus/core';
-import { IrlPin, IrlViewer, IrlState } from '../irl-schemas.js';
-import { encodeGeohash, geohashNeighbors, decodeGeohashBounds, decodeGeohash } from '../geohash.js';
-import { irlRegistry } from '../irl-registry.js';
-import { multiplayerSecret } from '../irl-publish-auth.js';
+import { IrlViewer, IrlState } from '../irl-schemas.js';
+import { encodeGeohash, decodeGeohash } from '../geohash.js';
import {
isReactionType,
reactionAllowed,
@@ -36,22 +29,15 @@ import {
REACTION_LEDGER_MAX,
} from '../irl-reactions.js';
-// The three.ws API this server reads authoritative pins from. Mirrors
-// persistence.js / WalkRoom's WORLD_API_BASE — the multiplayer process has no DB
-// of its own; Neon is reached only through the Vercel API.
-const API_BASE = (process.env.WORLD_API_BASE || 'https://three.ws').replace(/\/$/, '');
-
const GEOCELL_RE = /^[0-9bcdefghjkmnpqrstuvwxyz]{6}$/; // precision-6 base32 (no a/i/l/o)
const PATCH_RATE_MS = 100; // 10 Hz delta flush — well under the ~1 s liveness target
const MAX_CLIENTS = 200; // a busy real-world spot; viewers only receive broadcasts
-const MAX_PINS = 500; // hard ceiling on the synced set, guards the join-time sync
-const PUBLISH_TYPES = new Set(['pin:add', 'pin:update', 'pin:remove']);
// ── D2 presence tuning ───────────────────────────────────────────────────────
const HEARTBEAT_STALE_MS = 30_000; // drop a viewer this long without a heartbeat
const REAPER_INTERVAL_MS = 10_000; // sweep cadence (≤ stale window, so a drop lands < HEARTBEAT_STALE_MS + this)
const MAX_VIEWERS = 200; // cap the synced presence set (matches MAX_CLIENTS)
-const GHOST_AVATAR_MAX = 1024; // clamp a shared avatar URL, same ceiling as a pin's
+const GHOST_AVATAR_MAX = 1024; // clamp a shared avatar URL
// Fraction of a cell's half-extent to jitter a viewer's marker within. < 1 keeps
// the marker inside the cell it claims, while spreading co-located viewers apart
// so two ghosts never stack perfectly. The jitter is set once on join and never
@@ -64,72 +50,11 @@ function coerceHeading(v) {
return Number.isFinite(n) ? ((Math.round(n) % 360) + 360) % 360 : 0;
}
-// Coerce a pin from either the API's snake_case row projection (room load) or the
-// webhook's camelCase wire object (publish) into the IrlPin field set, clamped so
-// a single oversized field can't bloat the synced state handed to every viewer.
-function coercePin(raw) {
- if (!raw || typeof raw !== 'object') return null;
- const id = String(raw.id || '').slice(0, 64);
- if (!id) return null;
- const lat = Number(raw.lat);
- const lng = Number(raw.lng);
- if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
- const str = (v, max) => (v == null ? '' : String(v).slice(0, max));
- let placedAt = 0;
- if (Number.isFinite(Number(raw.placedAt))) placedAt = Number(raw.placedAt);
- else if (raw.placed_at) { const t = Date.parse(raw.placed_at); if (Number.isFinite(t)) placedAt = t; }
- const headingRaw = Number(raw.heading);
- return {
- id,
- lat,
- lng,
- heading: Number.isFinite(headingRaw) ? ((Math.round(headingRaw) % 360) + 360) % 360 : 0,
- avatarUrl: str(raw.avatarUrl ?? raw.avatar_url, 1024),
- avatarName: str(raw.avatarName ?? raw.avatar_name, 64),
- caption: str(raw.caption, 200),
- x402Endpoint: str(raw.x402Endpoint ?? raw.x402_endpoint, 512),
- agentId: str(raw.agentId ?? raw.agent_id, 64),
- placedAt,
- ...coerceRoom(raw),
- };
-}
-
-// Room-frame fields (append-only). Carried through realtime so a shared cluster
-// renders from its exact relative offsets, not each pin's noisy GPS. Accepts the
-// API's snake_case row (room load) or the webhook's camelCase wire (publish), and
-// clamps the offset to a building-scale ceiling so the synced state can't be bent
-// into a cross-map jump. A missing/empty roomId yields a legacy standalone pin.
-const ROOM_ID_RE = /^[a-z0-9-]{1,64}$/;
-const REL_MAX_M = 500;
-function coerceRoom(raw) {
- const roomId = String(raw.roomId ?? raw.room_id ?? '').slice(0, 64);
- if (!roomId || !ROOM_ID_RE.test(roomId)) {
- return { roomId: '', relEast: 0, relNorth: 0, originLat: 0, originLng: 0, originYawDeg: 0 };
- }
- const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
- const clampRel = (v) => Math.max(-REL_MAX_M, Math.min(REL_MAX_M, num(v)));
- const oLat = num(raw.originLat ?? raw.origin_lat);
- const oLng = num(raw.originLng ?? raw.origin_lng);
- // An invalid origin demotes the pin to standalone rather than placing a room at 0,0.
- if (!(oLat >= -90 && oLat <= 90 && oLng >= -180 && oLng <= 180) || (oLat === 0 && oLng === 0)) {
- return { roomId: '', relEast: 0, relNorth: 0, originLat: 0, originLng: 0, originYawDeg: 0 };
- }
- return {
- roomId,
- relEast: clampRel(raw.relEast ?? raw.rel_east_m),
- relNorth: clampRel(raw.relNorth ?? raw.rel_north_m),
- originLat: oLat,
- originLng: oLng,
- originYawDeg: ((num(raw.originYawDeg ?? raw.origin_yaw_deg) % 360) + 360) % 360,
- };
-}
-
export class IrlRoom extends Room {
constructor() {
super();
this.maxClients = MAX_CLIENTS;
this.geocell = '';
- this.window = new Set(); // centre + neighbour cells this room mirrors
// D3 debounce ledger: `${sessionId} ${pinId}` → lastTs of the last open/view
// reaction, so a jittery tap can't spam every co-located phone (pay/message
// bypass this entirely). Pruned when it crosses REACTION_LEDGER_MAX.
@@ -162,183 +87,21 @@ export class IrlRoom extends Room {
// clock is owned by the room and torn down automatically on dispose.
this.clock.setInterval(() => this._reapStaleViewers(), REAPER_INTERVAL_MS);
- // The cells this room is responsible for: its centre plus the 8 neighbours.
- this.window = new Set([this.geocell, ...geohashNeighbors(this.geocell)].filter(Boolean));
-
- // Register so the publish webhook can reach this room (by centre cell).
- if (this.geocell) irlRegistry.register(this.geocell, this);
-
- // Hydrate the current live pins for this window from the authoritative API
- // before the first client renders, so newcomers drop into the real world —
- // not an empty one that fills in only as future changes arrive.
- if (this.geocell) {
- try {
- await this._loadPins();
- } catch (err) {
- console.warn(`[irl_world ${this.roomId} cell=${this.geocell}] pin load failed:`, err?.message);
- }
- }
-
- console.log(`[irl_world ${this.roomId} cell=${this.geocell || 'invalid'}] created (${this.state.pins.size} pins)`);
- }
-
- async _loadPins() {
- // Bounding box of the 3×3 window (centre + neighbours). A box query reuses the
- // API's lat/lng index and needs no geohash decode server-side — the window is
- // a coarse pre-filter; the client does the final per-viewer radius filtering.
- const bbox = this._windowBounds();
- if (!bbox) return;
- const url = `${API_BASE}/api/irl/pins?bbox=${bbox.minLat},${bbox.minLng},${bbox.maxLat},${bbox.maxLng}`;
- // The bbox feed is internal-only (it would otherwise be a bulk GPS-scrape
- // vector). Present the shared multiplayer secret so the API trusts this as
- // server-to-server room hydration rather than a public read.
- const res = await fetch(url, {
- headers: { accept: 'application/json', 'x-mp-internal': multiplayerSecret() },
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const body = await res.json();
- const pins = Array.isArray(body?.pins) ? body.pins : [];
- for (const raw of pins) {
- if (this.state.pins.size >= MAX_PINS) break;
- const p = coercePin(raw);
- if (p && !this.state.pins.has(p.id)) this.state.pins.set(p.id, this._toSchema(p));
- }
- }
-
- // Union of the decoded bounds of every cell in this room's window → the lat/lng
- // box the API hydration query selects.
- _windowBounds() {
- let minLat = Infinity, minLng = Infinity, maxLat = -Infinity, maxLng = -Infinity;
- for (const cell of this.window) {
- const b = decodeGeohashBounds(cell);
- if (b.latMin < minLat) minLat = b.latMin;
- if (b.lngMin < minLng) minLng = b.lngMin;
- if (b.latMax > maxLat) maxLat = b.latMax;
- if (b.lngMax > maxLng) maxLng = b.lngMax;
- }
- if (!Number.isFinite(minLat)) return null;
- return { minLat, minLng, maxLat, maxLng };
- }
-
- _toSchema(p) {
- const pin = new IrlPin();
- pin.id = p.id;
- pin.lat = p.lat;
- pin.lng = p.lng;
- pin.heading = p.heading;
- pin.avatarUrl = p.avatarUrl;
- pin.avatarName = p.avatarName;
- pin.caption = p.caption;
- pin.x402Endpoint = p.x402Endpoint;
- pin.agentId = p.agentId;
- pin.placedAt = p.placedAt;
- pin.roomId = p.roomId;
- pin.relEast = p.relEast;
- pin.relNorth = p.relNorth;
- pin.originLat = p.originLat;
- pin.originLng = p.originLng;
- pin.originYawDeg = p.originYawDeg;
- return pin;
- }
-
- // Apply a publish webhook to the synced state. Called by irlRegistry.dispatch
- // for every room whose window covers the pin's cell. A remove deletes the entry;
- // an add (re)writes the full pin; an update on an EXISTING pin is a partial merge
- // — only the fields present in the payload change, so a re-skin that carries just
- // { id, avatarUrl } can't blank the caption/name. Colyseus then delta-broadcasts
- // only what actually changed. (The placer's own client filters its own pin out,
- // see src/irl.js.)
- applyPublish(type, raw) {
- if (!PUBLISH_TYPES.has(type)) return;
-
- if (type === 'pin:remove') {
- const id = String(raw?.id || '').slice(0, 64);
- if (id) this.state.pins.delete(id);
- return;
- }
-
- const id = String(raw?.id || '').slice(0, 64);
- if (!id) return;
- const existing = this.state.pins.get(id);
-
- // Full write: a fresh placement, or an update for a pin this room hasn't seen
- // yet (it joined the window between this room's load and now).
- if (type === 'pin:add' || !existing) {
- const p = coercePin(raw);
- if (!p) return;
- if (existing) { this._assignFull(existing, p); return; }
- if (this.state.pins.size >= MAX_PINS) return; // guard the synced set
- this.state.pins.set(id, this._toSchema(p));
- return;
- }
-
- // Partial update of an existing pin — only the provided fields move.
- this._applyPartial(existing, raw);
- }
-
- _assignFull(pin, p) {
- pin.lat = p.lat;
- pin.lng = p.lng;
- pin.heading = p.heading;
- pin.avatarUrl = p.avatarUrl;
- pin.avatarName = p.avatarName;
- pin.caption = p.caption;
- pin.x402Endpoint = p.x402Endpoint;
- pin.agentId = p.agentId;
- pin.placedAt = p.placedAt;
- pin.roomId = p.roomId;
- pin.relEast = p.relEast;
- pin.relNorth = p.relNorth;
- pin.originLat = p.originLat;
- pin.originLng = p.originLng;
- pin.originYawDeg = p.originYawDeg;
- }
-
- // Merge only the fields actually present in a partial pin:update wire object
- // (camelCase, as the API's pinWire emits), clamped the same way as a full coerce.
- _applyPartial(pin, raw) {
- const lat = Number(raw.lat);
- const lng = Number(raw.lng);
- if (Number.isFinite(lat)) pin.lat = lat;
- if (Number.isFinite(lng)) pin.lng = lng;
- if (raw.heading !== undefined) {
- const h = Number(raw.heading);
- if (Number.isFinite(h)) pin.heading = ((Math.round(h) % 360) + 360) % 360;
- }
- if (raw.avatarUrl !== undefined) pin.avatarUrl = String(raw.avatarUrl || '').slice(0, 1024);
- if (raw.avatarName !== undefined) pin.avatarName = String(raw.avatarName || '').slice(0, 64);
- if (raw.caption !== undefined) pin.caption = String(raw.caption || '').slice(0, 200);
- if (raw.x402Endpoint !== undefined) pin.x402Endpoint = String(raw.x402Endpoint || '').slice(0, 512);
- if (raw.agentId !== undefined) pin.agentId = String(raw.agentId || '').slice(0, 64);
- // Room-frame fields move together on a room-origin calibrate (the whole
- // cluster shifts), so a pin:update carrying origin/rel re-merges them. Reuse
- // the same coerce/clamp; only overwrite when the payload actually re-states
- // a valid room (an empty/invalid room block leaves the existing frame intact).
- if (raw.roomId !== undefined || raw.relEast !== undefined || raw.originLat !== undefined) {
- const r = coerceRoom(raw);
- if (r.roomId) {
- pin.roomId = r.roomId;
- pin.relEast = r.relEast;
- pin.relNorth = r.relNorth;
- pin.originLat = r.originLat;
- pin.originLng = r.originLng;
- pin.originYawDeg = r.originYawDeg;
- }
- }
- // placedAt is immutable for a given pin; never patched.
+ console.log(`[irl_world ${this.roomId} cell=${this.geocell || 'invalid'}] created (presence + reactions)`);
}
// D3 — turn a viewer's interaction into an ambient reaction for the whole cell.
- // Validates the type, requires a pin this room actually mirrors, debounces the
- // noisy open/view types per (session, pin), then broadcasts a privacy-clean
- // { pinId, type, ts } to everyone in the room (the sender included, so their own
- // tap is driven by the same authoritative event the others see). No GPS, no
- // wallet, no actor identity ever rides this channel.
+ // Validates the type, debounces the noisy open/view types per (session, pin),
+ // then broadcasts a privacy-clean { pinId, type, ts } to everyone in the room
+ // (the sender included, so their own tap is driven by the same authoritative
+ // event the others see). No GPS, no wallet, no actor identity ever rides this
+ // channel — and because the room holds no pin state, a reaction for a pinId a
+ // given client isn't rendering is simply a no-op on that client.
_handleInteraction(client, payload) {
const type = typeof payload?.type === 'string' ? payload.type : '';
if (!isReactionType(type)) return;
const pinId = String(payload?.pinId || '').slice(0, 64);
- if (!pinId || !this.state.pins.has(pinId)) return; // only react for pins we hold
+ if (!pinId) return;
const now = Date.now();
if (this._reactionLedger.size > REACTION_LEDGER_MAX) {
@@ -433,7 +196,6 @@ export class IrlRoom extends Room {
}
onDispose() {
- if (this.geocell) irlRegistry.unregister(this.geocell, this);
this._reactionLedger.clear();
console.log(`[irl_world ${this.roomId} cell=${this.geocell || 'invalid'}] disposed`);
}
diff --git a/prompts/agent-fixes/fix-agents-8004-search-timeout.md b/prompts/agent-fixes/fix-agents-8004-search-timeout.md
deleted file mode 100644
index de6b11423..000000000
--- a/prompts/agent-fixes/fix-agents-8004-search-timeout.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# Fix: GET /api/agents/8004/search — 6 × 504 (subgraph query timeout)
-
-## Context
-
-`GET /api/agents/8004/search` returns 504 on 6 requests. The endpoint queries the Agent0 ERC-8004 subgraph (a Graph Protocol endpoint) for on-chain agent listings. When the subgraph is slow or the query is complex, the function exceeds Vercel's timeout.
-
-## Root Cause
-
-Read `api/agents/8004/search.js` in full before touching anything.
-
-The search endpoint:
-1. Calls `searchAgents()` from the agent0 SDK, which hits a Graph Protocol subgraph endpoint
-2. Has a hard timeout guard that returns 504 when exceeded (visible at line 123)
-3. Does NOT limit the subgraph query complexity — a text search (`q` param) triggers a more expensive query plan
-
-The 504 occurs when:
-- The subgraph RPC endpoint is slow (Graph Protocol hosted service has variable latency)
-- The query includes text search (`q=...`) which requires a `CONTAINS` or `STARTS_WITH` filter on the subgraph, which is slower than a simple list
-- The default timeout budget is too long, causing Vercel to kill the function before the internal timeout fires
-
-## What You Must Fix — Completely
-
-### Fix 1: Verify and tighten the timeout budget
-
-Read `api/agents/8004/search.js` to find the `SUBGRAPH_TIMEOUT_MS` or equivalent constant. If the timeout is ≥ 8000ms, reduce it:
-
-```javascript
-const SUBGRAPH_TIMEOUT_MS = 6_000; // leave margin before Vercel's 10s default
-```
-
-The `Promise.race` against a timeout at line 123 should use this value. Vercel's default function timeout for free/hobby plans is 10 seconds; for Pro it's 60 seconds (but Vercel kills functions that are unresponsive faster than the nominal limit).
-
-### Fix 2: Reduce default page size for search queries
-
-Text search queries are more expensive. When `q` is provided, cap the `limit` lower:
-
-```javascript
-const hasQuery = q.length > 0;
-const effectiveLimit = hasQuery
- ? Math.min(limit, 10) // smaller result set for text searches
- : Math.min(limit, 50); // larger result set for simple listing
-```
-
-This reduces the data the subgraph must scan and transfer.
-
-### Fix 3: Add pagination parameters correctly
-
-Read line 92–94 in `api/agents/8004/search.js`. The endpoint accepts `limit` and `skip` params but the comment says the SDK's `searchAgents()` ignores `limit` at the subgraph level. If this is confirmed, pass `first` and `skip` directly to the GraphQL query instead of using the SDK's abstraction:
-
-```javascript
-// Instead of:
-const agents = await sdk.searchAgents({ ... });
-
-// Use direct GraphQL query with explicit pagination:
-const query = `{
- agents(first: ${effectiveLimit}, skip: ${skip}, where: { ... }) {
- id
- name
- description
- ...
- }
-}`;
-const result = await fetch(subgraphUrl, {
- method: 'POST',
- body: JSON.stringify({ query }),
- signal: AbortSignal.timeout(SUBGRAPH_TIMEOUT_MS)
-});
-```
-
-This gives full control over the subgraph query plan.
-
-### Fix 4: Return partial results on timeout instead of 504
-
-Rather than returning 504 on timeout, return whatever was fetched before the deadline (or an empty array with a `timed_out: true` flag):
-
-```javascript
-let agents = [];
-let timedOut = false;
-try {
- agents = await Promise.race([
- fetchAgents(params),
- new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('timeout'), { code: 'TIMEOUT' })), SUBGRAPH_TIMEOUT_MS))
- ]);
-} catch (err) {
- if (err.code === 'TIMEOUT') {
- timedOut = true;
- console.warn('[agents/8004/search] subgraph timeout, returning empty');
- } else {
- throw err;
- }
-}
-
-return json(res, 200, { agents, timed_out: timedOut, total: agents.length });
-```
-
-A 200 with `timed_out: true` is better UX than a 504 — the UI can show "Results may be incomplete" instead of an error page.
-
-### Verify the fix
-
-1. Start the dev server (`npm run dev`)
-2. Request `GET /api/agents/8004/search?chain=8453` — must return 200 with a list of agents
-3. Request `GET /api/agents/8004/search?chain=8453&q=defi` — must return 200 within 8 seconds (text search)
-4. No 504 responses in Vercel logs after deploy
-
-## Do Not
-
-- Do not remove the timeout guard — subgraph endpoints can hang indefinitely without it
-- Do not return 504 when a timeout occurs — return 200 with partial/empty results and `timed_out: true`
-- Do not cache subgraph results indefinitely — use a TTL of 60s maximum since on-chain state changes
-
-## Related Files
-
-- `api/agents/8004/search.js` — the search handler (primary fix target)
-- `api/agents/8004/agent.js` — similar timeout pattern (reference)
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-agents-8004-search-timeout.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-agents-solana-rpc-cache.md b/prompts/agent-fixes/fix-agents-solana-rpc-cache.md
deleted file mode 100644
index 54e36be3f..000000000
--- a/prompts/agent-fixes/fix-agents-solana-rpc-cache.md
+++ /dev/null
@@ -1,148 +0,0 @@
-# Fix: /api/agents/*/solana — Solana RPC 429 on wallet balance checks, no caching
-
-## Context
-
-Multiple `/api/agents/{id}/solana` endpoints log balance fetch failures with:
-
-```
-[agents/solana/wallet] balance fetch failed Error: failed to get balance of account X:
-Error: 429 Too Many Requests: {"jsonrpc":"2.0","error":{"code":-32429,"message":"max usage reached"}}
-```
-
-The endpoints return 200 (not 500) but the wallet balance in the response is null or 0, which the frontend renders as "balance unavailable." This affects every user who views an agent's Solana wallet details.
-
-Note: the 404s on `/api/agents/{uuid}/solana` are NOT a bug — those agents simply don't have Solana wallets registered. Only the 429-related balance failures need fixing.
-
-## Root Cause
-
-Read `api/agents/solana/_handlers.js` and `api/_lib/balances.js` in full before touching anything.
-
-Wallet balance fetches call `connection.getBalance(pubkey)` using a `Connection` instance pointed at `SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'`. When `SOLANA_RPC_URL` is not set (same infrastructure gap as `fix-pump-agent-stats-rpc-429.md`), the public endpoint rate-limits at scale.
-
-The secondary problem is that there is no caching — every page load triggers a fresh RPC call. Even with a paid RPC, hitting it on every request for popular agents is wasteful and fragile.
-
-## What You Must Fix — Completely
-
-### Fix 1: Set SOLANA_RPC_URL (infrastructure — same as pump-agent-stats fix)
-
-If `SOLANA_RPC_URL` is not set in Vercel env, set it to a paid Helius or QuickNode endpoint. See `fix-pump-agent-stats-rpc-429.md` for provisioning instructions. A single paid RPC endpoint fixes both the pump-stats cron AND the agent wallet balance calls.
-
-### Fix 2: Cache wallet balances to reduce RPC calls
-
-In `api/_lib/balances.js` (or wherever `getBalance()` is called for agent wallets), wrap the fetch with a short-TTL cache using Upstash Redis:
-
-```javascript
-import { Redis } from '@upstash/redis';
-
-const redis = process.env.UPSTASH_REDIS_REST_URL
- ? new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN })
- : null;
-
-const BALANCE_TTL_SECONDS = 60;
-
-export async function getCachedSolBalance(pubkeyStr, connection) {
- const cacheKey = `sol:balance:${pubkeyStr}`;
-
- if (redis) {
- const cached = await redis.get(cacheKey).catch(() => null);
- if (cached !== null) return Number(cached);
- }
-
- const lamports = await connection.getBalance(new PublicKey(pubkeyStr));
-
- if (redis) {
- await redis.set(cacheKey, lamports, { ex: BALANCE_TTL_SECONDS }).catch(() => {});
- }
-
- return lamports;
-}
-```
-
-Replace direct `connection.getBalance()` calls with `getCachedSolBalance()`. A 60-second TTL means a popular agent's balance is fetched from RPC at most once per minute regardless of traffic.
-
-If Upstash Redis is not available (see `fix-x402-upstash-redis.md`), use a module-level in-memory Map as fallback:
-
-```javascript
-const memCache = new Map(); // { pubkey → { value, expiresAt } }
-
-function getMemCached(key) {
- const entry = memCache.get(key);
- return entry && Date.now() < entry.expiresAt ? entry.value : null;
-}
-
-function setMemCached(key, value, ttlMs) {
- memCache.set(key, { value, expiresAt: Date.now() + ttlMs });
-}
-```
-
-The in-memory cache is per-instance (not shared across Vercel replicas) but still reduces RPC calls significantly for any single replica.
-
-### Fix 3: Add 429 retry with exponential backoff for balance checks
-
-In the balance fetch code, wrap the RPC call with a single retry on 429:
-
-```javascript
-async function fetchBalanceWithRetry(connection, pubkey, retries = 1) {
- try {
- return await connection.getBalance(pubkey);
- } catch (err) {
- if (retries > 0 && /429|rate.limit/i.test(err?.message || '')) {
- await new Promise(r => setTimeout(r, 500));
- return fetchBalanceWithRetry(connection, pubkey, retries - 1);
- }
- throw err;
- }
-}
-```
-
-Do NOT retry more than once — the goal is to recover from a transient spike, not to loop on a systematically rate-limited endpoint.
-
-### Fix 4: Return a graceful response on persistent 429
-
-If the balance fetch fails after retry, return a response with `balance: null` and a `balance_error: 'rpc_rate_limited'` field rather than letting the error propagate:
-
-```javascript
-let balance = null;
-let balanceError = null;
-try {
- balance = await getCachedSolBalance(wallet, connection);
-} catch (err) {
- balanceError = /429|rate.limit/i.test(err?.message || '') ? 'rpc_rate_limited' : 'rpc_error';
- console.warn('[agents/solana/balance]', err?.message);
-}
-```
-
-The frontend should display "Balance unavailable" when `balance_error` is set, rather than showing 0 or crashing.
-
-### Verify the fix
-
-1. Start the dev server with a valid `SOLANA_RPC_URL` set in `.env`
-2. Request `GET /api/agents/{id}/solana` for an agent with a registered wallet — must return 200 with a non-null balance
-3. Make the same request twice in rapid succession — the second must return the cached value (confirm by checking that only one RPC call is made via logs or network tab)
-
-## Do Not
-
-- Do not cache indefinitely — use a TTL of 60 seconds maximum for balances (stale balances mislead users).
-- Do not suppress all RPC errors — log them at WARN level so they appear when debugging.
-- Do not return fake/hardcoded balances on error.
-
-## Related Files
-
-- `api/agents/solana/_handlers.js` — agent solana endpoint handlers
-- `api/_lib/balances.js` — wallet balance fetching (primary fix target)
-- `api/_lib/pump.js:23` — `SOLANA_RPC_URL` fallback pattern (reference)
-- `fix-pump-agent-stats-rpc-429.md` — same infrastructure fix for SOLANA_RPC_URL
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-agents-solana-rpc-cache.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-auth-register-seed-agent.md b/prompts/agent-fixes/fix-auth-register-seed-agent.md
deleted file mode 100644
index 9426e5984..000000000
--- a/prompts/agent-fixes/fix-auth-register-seed-agent.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Fix: POST /api/auth/register — NeonDB cold-start failures in seedDefaultAgent
-
-## Context
-
-User registration occasionally returns 500 with an unhandled rejection from `seedDefaultAgent`:
-
-```
-Unhandled Rejection: NeonDbError: Error connecting to database: fetch failed
- at execute (...@neondatabase/serverless/index.mjs:1549)
- at async seedDefaultAgent (api/_lib/seed-default-agent.js:20)
-```
-
-The user account is created successfully, but the 500 response makes the user think registration failed. This causes duplicate registration attempts.
-
-## Current State — Verify Before Changing Anything
-
-Read `api/_lib/seed-default-agent.js` in full and `api/auth/[action].js` around line 147 before touching anything.
-
-The current code in `seed-default-agent.js` **may already have a fix** in place:
-- Lines 23–75 have a try/catch with retry logic
-- Line 51: one retry after 1 second on first failure
-- Line 72: catches all second-attempt errors and returns null
-
-And in `api/auth/[action].js` at line 147:
-```javascript
-queueMicrotask(() => seedDefaultAgent(user.id));
-```
-
-`queueMicrotask()` fires asynchronously — errors inside it do NOT propagate to the HTTP response. If both the try/catch AND the queueMicrotask are in place, the 500 from this source should be impossible.
-
-**If both safeguards are already in the code as described above, this issue is already fixed. Verify and close.**
-
-## If the Fix Is NOT Yet Complete
-
-### Fix 1: Wrap seedDefaultAgent in try/catch in seed-default-agent.js
-
-The entire exported function must be wrapped in try/catch with retry:
-
-```javascript
-export async function seedDefaultAgent(userId) {
- try {
- const [agent] = await sql`INSERT INTO agent_identities ... RETURNING id`;
- return agent?.id || null;
- } catch (err) {
- console.warn('[seed-default-agent] first attempt failed, retrying', { userId, error: err?.message });
- await new Promise(r => setTimeout(r, 1000));
- try {
- const [agent] = await sql`INSERT INTO agent_identities ... RETURNING id`;
- return agent?.id || null;
- } catch (err2) {
- console.error('[seed-default-agent] failed', { userId, error: err2?.message });
- return null; // Never propagate — registration must succeed regardless
- }
- }
-}
-```
-
-**Critical:** Both catch blocks must return `null`, never `throw`. A failed agent seed is recoverable — the user can create an agent manually.
-
-### Fix 2: Use queueMicrotask for the seed call in auth/register
-
-In `api/auth/[action].js`, wherever `seedDefaultAgent` is called after registration, it must NOT be awaited in the request handler:
-
-```javascript
-// Wrong — awaiting makes seed failures block the 201 response:
-await seedDefaultAgent(user.id);
-
-// Correct — fire-and-forget, never blocks the response:
-queueMicrotask(() => seedDefaultAgent(user.id));
-```
-
-If the current code already uses `queueMicrotask()`, no change is needed here.
-
-### Verify the fix
-
-1. Start the dev server (`npm run dev`)
-2. Register a new user via the registration endpoint — must return 201 regardless of whether the seed agent succeeds
-3. Check that a default agent eventually appears for the user (it may take up to 2 seconds due to the retry delay)
-4. Temporarily break the DB connection in local dev (e.g., invalid DATABASE_URL) and verify registration still returns 201
-
-## Do Not
-
-- Do not await `seedDefaultAgent` in the registration handler — it must never block the 201 response
-- Do not propagate seed errors to the user — log them and return null
-- Do not remove the retry logic — Neon cold-start failures recover quickly on the second attempt
-
-## Related Files
-
-- `api/_lib/seed-default-agent.js` — the seed function (verify try/catch is complete)
-- `api/auth/[action].js:147` — the queueMicrotask call (verify it's fire-and-forget)
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-auth-register-seed-agent.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-avatars-reconstruct-env.md b/prompts/agent-fixes/fix-avatars-reconstruct-env.md
deleted file mode 100644
index 0c539c72b..000000000
--- a/prompts/agent-fixes/fix-avatars-reconstruct-env.md
+++ /dev/null
@@ -1,118 +0,0 @@
-# Fix: POST /api/avatars/{id}/reconstruct — 14 × 501 (REPLICATE_RECONSTRUCT_MODEL not set)
-
-## Context
-
-The avatar reconstruction endpoint (`POST /api/avatars/{id}/reconstruct` or equivalent reconstruct action) returns 501 Not Implemented on every request. The frontend's avatar regeneration UI shows a spinner that never completes.
-
-Error:
-```
-{ code: 'regen_unconfigured', status: 501 }
-```
-
-## Root Cause
-
-Read `api/avatars/_actions.js` lines 691–740 and `api/avatars/REGENERATE.md` before touching anything.
-
-The reconstruct handler checks for a configured Replicate model:
-```javascript
-if (!env.REPLICATE_RECONSTRUCT_MODEL) {
- return error(res, 501, 'regen_unconfigured', 'Reconstruction is not configured');
-}
-```
-
-`REPLICATE_RECONSTRUCT_MODEL` is not set in the Vercel production environment. Without it, no avatar reconstruction jobs can be submitted, and every attempt returns 501.
-
-The second dependency is `REPLICATE_API_TOKEN` — without this, even if the model is configured, Replicate API calls will fail.
-
-## What You Must Fix — Completely
-
-### Step 1: Set REPLICATE_RECONSTRUCT_MODEL in Vercel
-
-Per `api/avatars/REGENERATE.md`, the default model is `firtoz/trellis`:
-
-```bash
-vercel env add REPLICATE_RECONSTRUCT_MODEL production
-# When prompted, enter: firtoz/trellis
-```
-
-If you want to pin a specific version for reproducibility:
-```
-firtoz/trellis:a1e62aa99e3d40aed1de4cd4c5c4b1f5ec25c32f8b38f6dec71b80d6083b0f4f
-```
-
-Check Replicate's model page for the latest stable version tag.
-
-### Step 2: Set REPLICATE_API_TOKEN if not already set
-
-```bash
-vercel env ls | grep REPLICATE_API_TOKEN
-```
-
-If not present:
-```bash
-vercel env add REPLICATE_API_TOKEN production
-# Enter your Replicate API token from https://replicate.com/account/api-tokens
-```
-
-Also add both to `.env` for local dev:
-```
-REPLICATE_RECONSTRUCT_MODEL=firtoz/trellis
-REPLICATE_API_TOKEN=r8_<your-token>
-```
-
-### Step 3: Verify the reconstruction flow end-to-end
-
-Read `api/avatars/_actions.js` lines 390–450 (the reconstruct job completion handler) to understand what happens after Replicate finishes:
-1. Replicate webhook delivers the result to the job status endpoint
-2. The job result is materialized as a new avatar row
-3. The frontend polls `avatar_regen_jobs` for completion
-
-Verify the webhook URL is configured in Replicate's callback — the `reconstruct` submission must include a `webhook` field pointing to the production jobs endpoint. Check whether `VERCEL_URL` or a hardcoded production URL is used for the webhook.
-
-### Step 4: Update the frontend to surface "unavailable" gracefully
-
-In `src/dashboard-next/` (find the page that calls the reconstruct endpoint), if `REPLICATE_RECONSTRUCT_MODEL` is intentionally unset, the UI must show "Avatar reconstruction is not available" rather than an infinite spinner.
-
-Look for where the `reconstruct` action is dispatched and add a handler for the 501 response:
-```javascript
-if (response.status === 501) {
- // show a clear "feature not available" message, not a spinner
-}
-```
-
-### Verify the fix
-
-1. Set env vars locally in `.env`
-2. Start dev server (`npm run dev`)
-3. Navigate to the avatar reconstruction UI
-4. Trigger a reconstruction — must submit to Replicate and return a job ID (200 response)
-5. The UI must poll for completion and display the result when done
-
-After Vercel deploy:
-- `POST /api/avatars/{id}/reconstruct` must return 200/202 (job submitted) not 501
-
-## Do Not
-
-- Do not set `REPLICATE_RECONSTRUCT_MODEL` to a non-existent or invalid model name — verify it exists at https://replicate.com/firtoz/trellis
-- Do not stub the Replicate call — reconstruction must go through the real Replicate API
-- Do not remove the 501 guard — it's correct behavior when the env var is missing; the fix is to set the env var
-
-## Related Files
-
-- `api/avatars/_actions.js:691–740` — reconstruct handler
-- `api/avatars/_actions.js:390–450` — job completion and avatar materialization
-- `api/avatars/REGENERATE.md` — full env var documentation for this feature
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-avatars-reconstruct-env.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-billing-withdrawals-42p18.md b/prompts/agent-fixes/fix-billing-withdrawals-42p18.md
deleted file mode 100644
index fe2bd16ff..000000000
--- a/prompts/agent-fixes/fix-billing-withdrawals-42p18.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# Fix: GET /api/billing/withdrawals returns 500 — SQL 42P18 LIMIT/OFFSET type error
-
-## Context
-
-Every authenticated user who loads the monetize/billing page triggers a 500 from `GET /api/billing/withdrawals?limit=50`. The page cannot display withdrawal history. This has been firing continuously in production.
-
-Error in Vercel logs:
-```
-NeonDbError: could not determine data type of parameter $2
- severity: 'ERROR'
- code: '42P18'
- routine: 'pg_analyze_and_rewrite_varparams'
- at execute (node_modules/@neondatabase/serverless/index.mjs:1556:55)
- at async api/billing/withdrawals/index.js:36
-```
-
-## Root Cause
-
-Read `api/billing/withdrawals/index.js` in full before touching anything.
-
-PostgreSQL's extended query protocol requires type information for all parameters at parse time. In a `LIMIT $N OFFSET $N` clause, PostgreSQL has no type context for those parameters — it cannot infer they should be integers — and rejects the query with error code 42P18 ("indeterminate datatype").
-
-The Neon serverless driver (`@neondatabase/serverless`) uses the extended query protocol. When you write:
-```javascript
-sql`SELECT ... WHERE user_id = ${user.id} ORDER BY ... LIMIT ${limit} OFFSET ${offset}`
-```
-The driver sends `limit` and `offset` as untyped parameters ($2 and $3). Postgres sees:
-```sql
-SELECT ... WHERE user_id = $1 ORDER BY ... LIMIT $2 OFFSET $3
-```
-Parameters $2 and $3 have no type context → 42P18.
-
-The `user.id` parameter ($1) works fine because `WHERE user_id = $1` lets Postgres infer from the column type.
-
-Note: there is already a comment in the file explaining the 42P18 avoidance pattern for the `status` parameter — the same fix was applied there but was missed for `limit`/`offset`.
-
-## What You Must Fix — Completely
-
-### In `api/billing/withdrawals/index.js`
-
-There are **four SQL template literals** in the GET handler that use `${limit}` and `${offset}`. Find them all and add `::int` casts.
-
-Change every occurrence of:
-```javascript
-limit ${limit} offset ${offset}
-```
-To:
-```javascript
-limit ${limit}::int offset ${offset}::int
-```
-
-The `::int` cast is a PostgreSQL-side type annotation that appears as `LIMIT $N::int OFFSET $N::int` in the prepared statement. This gives the query planner the type context it needs and eliminates the 42P18 error.
-
-The four locations are:
-1. The withdrawals query in the `status` branch (where `status` is truthy)
-2. The withdrawals query in the no-status branch
-3. The count query in the `status` branch (check if it uses limit/offset — if not, no change needed)
-4. The count query in the no-status branch (same check)
-
-If the count queries don't include LIMIT/OFFSET they don't need the cast. Audit all four and apply the cast wherever `${limit}` or `${offset}` appear in SQL position.
-
-### Verify the fix
-
-After editing, run:
-```bash
-node -e "
-import('./api/billing/withdrawals/index.js').then(() => console.log('module loads OK')).catch(e => console.error(e))
-"
-```
-
-Then test the endpoint locally with a real authenticated session (or via the Playwright scripts in `scripts/`) and confirm the withdrawals panel loads without error.
-
-Verify the Vercel deployment shows no more 42P18 errors for `/api/billing/withdrawals` after deploy.
-
-## Do Not
-
-- Do not switch to raw string interpolation for the limit/offset values — even though they are already sanitized by `parseInt` + `Math.min`, parameterized queries are the correct pattern.
-- Do not change the branching logic for `status` — that fix is already correct and must stay.
-- Do not add a try/catch that silently swallows the DB error and returns empty results — the error must be fixed at the SQL level.
-
-## Related Files
-
-- `api/billing/withdrawals/index.js` — the only file to change
-- `src/dashboard-next/pages/monetize.js:69` — the frontend caller (no change needed here)
-
-Fix this completely. After the fix, `GET /api/billing/withdrawals?limit=50` must return a valid JSON response with the `withdrawals` array for any authenticated user.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-billing-withdrawals-42p18.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-chat-502-upstream.md b/prompts/agent-fixes/fix-chat-502-upstream.md
deleted file mode 100644
index 7a827f0ba..000000000
--- a/prompts/agent-fixes/fix-chat-502-upstream.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# Fix: POST /api/chat — 18 × 502 errors from upstream AI provider failures
-
-## Context
-
-`POST /api/chat` returns 502 (bad gateway) on 18 requests. The 502 comes from upstream AI providers (Anthropic or the worker proxy) returning 5xx responses that the handler propagates directly to the client.
-
-## Root Cause
-
-Read `api/chat.js` lines 280–370 in full before touching anything.
-
-The handler already has multi-provider fallback logic at line 314:
-```javascript
-if ((upstream.status === 429 || upstream.status >= 500) && routeIdx + 1 < fallbackRoutes.length) {
- // fall over to next route
-}
-```
-
-The 502 errors occur when **all fallback routes are exhausted** — every configured provider returned 5xx. When that happens, the handler returns 502 with the upstream error message.
-
-Two distinct failure modes:
-1. **All providers simultaneously returning 5xx** — rare but possible during an Anthropic or OpenAI incident.
-2. **Fallback routes not configured** — if `fallbackRoutes` has only one entry, the first failure immediately returns 502 with no retry.
-
-Additionally, the handler logs the error at `console.error` level (line 333) but the upstream error **message** may be truncated at 400 characters, making it hard to diagnose which provider failed and why.
-
-## What You Must Fix — Completely
-
-### Step 1: Audit the fallback route configuration
-
-Read `api/chat.js` to find where `fallbackRoutes` is built. Identify:
-- How many routes are configured in production (check env vars like `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `CHAT_WORKER_URL`)
-- Whether any route is missing its API key (which would cause it to skip or fail immediately)
-
-If only one provider is configured, the fallback logic is irrelevant and any provider 5xx becomes a user-facing 502.
-
-Verify all required env vars are set in Vercel production:
-```bash
-vercel env ls | grep -E "ANTHROPIC_API_KEY|OPENAI_API_KEY|CHAT_WORKER_URL"
-```
-
-### Step 2: Add single-provider retry before failover
-
-For the case where the primary provider returns a transient 5xx (e.g., 503 Service Unavailable), add one retry before falling to the next provider:
-
-In `api/chat.js`, in the route loop, before the `if (routeIdx + 1 < fallbackRoutes.length)` check, retry once on 5xx:
-
-```javascript
-// First try
-upstream = await fetch(route.url, { ... });
-
-// One retry on transient 5xx (503/504 are most common transient errors)
-if ([503, 504].includes(upstream.status)) {
- await new Promise(r => setTimeout(r, 500));
- upstream = await fetch(route.url, { ... });
-}
-```
-
-Only retry 503 and 504 (gateway-level transient errors). Do NOT retry 400, 401, 422 (client errors) or 500 (provider bugs) — those won't recover on retry.
-
-### Step 3: Improve error logging for provider failures
-
-At line 333, the current log is:
-```javascript
-console.error(`[chat:${route.name}]`, upstream.status, text.slice(0, 400));
-```
-
-Enhance it to log the route name and whether it was a final failure:
-```javascript
-const isFinal = routeIdx + 1 >= fallbackRoutes.length;
-console.error(
- `[chat:${route.name}]`,
- upstream.status,
- isFinal ? '(final — no more fallbacks)' : '(failing over)',
- text.slice(0, 400)
-);
-```
-
-This lets you distinguish "all providers failed" from "primary failed, fell back" in the logs.
-
-### Step 4: Add a user-friendly error body on final 502
-
-When all providers fail, the current response is:
-```javascript
-return error(res, 502, 'upstream_error', `${route.name} returned ${upstream.status}...`);
-```
-
-Add a generic message so the frontend can show a human-readable error:
-```javascript
-return error(res, 502, 'upstream_error', 'AI chat provider is temporarily unavailable. Please try again in a moment.');
-```
-
-The frontend chat UI should display this message to the user rather than a raw error object.
-
-### Verify the fix
-
-1. Start the dev server (`npm run dev`)
-2. Send a POST to `/api/chat` with a valid session and message body — must return a streaming SSE response without 502
-3. Verify the response streams correctly and completes without error
-
-For provider failure simulation:
-- Temporarily set `ANTHROPIC_API_KEY` to an invalid value in `.env` local dev
-- Send a chat request — should fall over to the next provider (OpenAI or worker proxy) and succeed
-
-## Do Not
-
-- Do not add retry for non-transient errors (400, 401, 422, 500).
-- Do not remove the existing fallback route logic — it's the primary resilience mechanism.
-- Do not add infinite retry loops — maximum one retry per provider, then fall over.
-- Do not mock the AI responses or hardcode fallback text.
-
-## Related Files
-
-- `api/chat.js:280–370` — primary route loop and fallback logic
-- `api/chat.js:427–440` — fallback routes configuration
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-chat-502-upstream.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-club-leaderboard-db.md b/prompts/agent-fixes/fix-club-leaderboard-db.md
deleted file mode 100644
index 1677b5e4a..000000000
--- a/prompts/agent-fixes/fix-club-leaderboard-db.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Fix: GET /api/club/leaderboard — 16 × 500 errors, missing DB column or table
-
-## Context
-
-`GET /api/club/leaderboard` returns 500 on 16 requests. No error message appears in the Vercel logs for these failures, which means the error is being swallowed without logging — or the log is being emitted at a severity level that doesn't appear in the log export.
-
-## Root Cause
-
-Read `api/club/leaderboard.js` in full before touching anything.
-
-The leaderboard query joins `club_dancer_wallets` with `club_tips`. The query references `t.paid_at` (the timestamp of a completed tip payment). Most likely:
-1. The `paid_at` column does not exist on `club_tips` in the production database, causing a PostgreSQL column-not-found error.
-2. OR one of the two tables (`club_dancer_wallets`, `club_tips`) does not exist at all.
-
-A secondary possibility is that the `wrap()` HTTP helper catches the error and returns 500 but does not log it with the full error context. Investigate the error path fully.
-
-## What You Must Fix — Completely
-
-### Step 1: Identify the actual error
-
-Read `api/club/leaderboard.js` fully. Identify where `runForWindow()` or the main query runs, and confirm the try/catch path logs the error with full context including `err.code` and `err.message`.
-
-If the current catch block is:
-```javascript
-} catch (err) {
- console.error('[club/leaderboard]', err?.message || err);
-```
-
-Change it to:
-```javascript
-} catch (err) {
- console.error('[club/leaderboard]', err?.code, err?.message || err);
- throw err; // or return error(res, 500, ...)
-```
-
-This ensures the Postgres error code (`42703` for column not found, `42P01` for table not found) appears in logs.
-
-### Step 2: Audit the DB schema
-
-Connect to the production Neon database and verify:
-
-```sql
--- Verify tables exist
-SELECT table_name FROM information_schema.tables
-WHERE table_name IN ('club_dancer_wallets', 'club_tips')
-AND table_schema = 'public';
-
--- If club_tips exists, verify columns
-SELECT column_name, data_type FROM information_schema.columns
-WHERE table_name = 'club_tips'
-ORDER BY ordinal_position;
-
--- If club_dancer_wallets exists, verify columns
-SELECT column_name, data_type FROM information_schema.columns
-WHERE table_name = 'club_dancer_wallets'
-ORDER BY ordinal_position;
-```
-
-### Step 3: Add missing columns or tables
-
-If `club_tips.paid_at` is missing, add it:
-```sql
-ALTER TABLE club_tips ADD COLUMN IF NOT EXISTS paid_at timestamptz;
-```
-
-If `club_dancer_wallets` is missing, check `api/_lib/migrations/` for the migration that creates it and apply it:
-```bash
-psql "$DATABASE_URL" -f api/_lib/migrations/<relevant-file>.sql
-```
-
-Record the fix in `api/_lib/migrations/` with a new idempotent SQL file. Do not apply ad-hoc schema changes without a migration file — every schema change must have a corresponding migration.
-
-### Step 4: Verify the leaderboard endpoint works
-
-After fixing the schema:
-1. Start the dev server (`npm run dev`)
-2. Request `/api/club/leaderboard` — it must return 200 with valid JSON containing `{ leaderboard: [...] }` (or equivalent structure)
-3. If no club_tips rows exist, the endpoint must return an empty leaderboard, not an error
-
-Confirm no 500 errors appear in Vercel logs after deploy.
-
-## Do Not
-
-- Do not return empty results silently when the DB query fails — the error must be logged with full context.
-- Do not remove the leaderboard feature if the DB tables are missing — create the migration.
-- Do not apply schema changes directly in Neon console without also adding a migration file in `api/_lib/migrations/`.
-
-## Related Files
-
-- `api/club/leaderboard.js` — the endpoint handler
-- `api/_lib/migrations/` — where the fix migration must go if schema changes are needed
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-club-leaderboard-db.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-erc8004-crawl-timeout.md b/prompts/agent-fixes/fix-erc8004-crawl-timeout.md
deleted file mode 100644
index 39071e461..000000000
--- a/prompts/agent-fixes/fix-erc8004-crawl-timeout.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Fix: cron/erc8004-crawl — multiple 504 timeouts (block chunk size and RPC timeouts)
-
-## Context
-
-The `erc8004-crawl` cron job times out on some deployments with 504 errors. The cron scans EVM chain logs for ERC-8004 agent registration events using `eth_getLogs` on public RPC endpoints. When the block range is too large or the RPC is slow, the function hits Vercel's timeout.
-
-## Root Cause
-
-Read `api/cron/[name].js` at `handleErc8004Crawl` (line 111) and `erc8004CrawlChain` (line 145) before touching anything.
-
-The current `ERC8004_BLOCK_CHUNK = 2_000` is noted in the code comment: "Public RPCs typically allow 2000-block ranges; lower this if a chain's RPC rejects with 'block range'." The 504 timeouts may occur because:
-
-1. **A specific chain's public RPC is slow** — some chains (e.g., Polygon, Arbitrum) have public RPCs with high latency or strict block range limits lower than 2000.
-2. **Multiple chains are crawled in a single cron run** — if there are many chains in `CHAINS`, the total time across all of them exceeds `CRAWL_BUDGET_MS = 240_000` (240 seconds), but Vercel's actual function timeout for cron jobs may be lower.
-3. **`erc8004EnrichMetadata` hangs** — the metadata enrichment step fetches external URLs for 25 agents per run. If any of those URLs hangs, the entire function waits.
-
-## What You Must Fix — Completely
-
-### Fix 1: Reduce ERC8004_BLOCK_CHUNK for slower chains
-
-Read `erc8004CrawlChain` and the `CHAINS` array. Identify which chains are present.
-
-For chains with known slow RPCs (Polygon, Base, Arbitrum, Optimism on free-tier public RPCs), reduce the chunk size. Either:
-
-**Option A:** Reduce the global default:
-```javascript
-const ERC8004_BLOCK_CHUNK = 1_000; // Reduced from 2000 — safer for all public RPCs
-```
-
-**Option B:** Add per-chain chunk size override:
-```javascript
-// In the CHAINS array:
-{ id: 137, name: 'polygon', rpcUrl: '...', registry: '...', blockChunk: 500 }
-
-// In erc8004CrawlChain:
-const chunkSize = chain.blockChunk || ERC8004_BLOCK_CHUNK;
-const toBlock = Math.min(fromBlock + chunkSize - 1, latestBlock);
-```
-
-Option B is cleaner because it lets you tune per-chain without affecting well-functioning chains.
-
-### Fix 2: Add per-RPC-call timeout via AbortSignal
-
-Read `erc8004RpcCall` function. Verify it has a timeout. If not, add one:
-
-```javascript
-async function erc8004RpcCall(rpcUrl, method, params) {
- const resp = await fetch(rpcUrl, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- signal: AbortSignal.timeout(ERC8004_FETCH_TIMEOUT_MS), // already defined as 10_000
- });
- if (!resp.ok) throw new Error(`RPC ${resp.status}: ${method}`);
- const data = await resp.json();
- if (data.error) throw new Error(`RPC error: ${data.error.message || JSON.stringify(data.error)}`);
- return data.result;
-}
-```
-
-The `ERC8004_FETCH_TIMEOUT_MS = 10_000` constant already exists — verify it's being used in the actual fetch call with `AbortSignal.timeout()`.
-
-### Fix 3: Add per-metadata-URL timeout in erc8004EnrichMetadata
-
-Read `erc8004EnrichMetadata`. Each external metadata URL fetch must have a timeout:
-
-```javascript
-const resp = await fetch(metadataUrl, {
- signal: AbortSignal.timeout(5_000), // 5 seconds max per metadata URL
-});
-```
-
-If a metadata URL hangs (e.g., IPFS gateway slow), it must not block the entire enrichment batch.
-
-### Fix 4: Verify CRAWL_BUDGET_MS is respected for Vercel's actual limit
-
-The `CRAWL_BUDGET_MS = 240_000` assumes a 300-second Vercel timeout (the maximum for Pro plan cron jobs). Verify in `vercel.json` that the `erc8004-crawl` function has `"maxDuration": 300` set:
-
-```json
-"functions": {
- "api/cron/[name].js": {
- "maxDuration": 300
- }
-}
-```
-
-If `maxDuration` is not set, the default is 10 seconds (hobby) or 60 seconds (Pro) — far less than 240 seconds. The budget check at line 125 (`Date.now() - crawlStart > CRAWL_BUDGET_MS`) would never fire before Vercel kills the function.
-
-### Verify the fix
-
-1. After making the changes, trigger the cron manually:
- ```bash
- curl -H "Authorization: Bearer $CRON_SECRET" https://three.ws/api/cron/erc8004-crawl
- ```
-2. Must return a valid JSON report within 30 seconds: `{"chains":[...],"enriched":N,"errors":[]}`
-3. No 504 responses in Vercel logs for this cron after deploy
-
-## Do Not
-
-- Do not set `ERC8004_BLOCK_CHUNK = 0` or skip the crawl — it must scan real on-chain data
-- Do not increase `CRAWL_BUDGET_MS` beyond 270_000 (270s) — leave at least 30 seconds of margin before Vercel's hard kill
-- Do not remove the chain-level error handling in `erc8004CrawlChain` — one chain failing must not abort all others
-
-## Related Files
-
-- `api/cron/[name].js:96` — `ERC8004_BLOCK_CHUNK` constant
-- `api/cron/[name].js:111` — `handleErc8004Crawl`
-- `api/cron/[name].js:145` — `erc8004CrawlChain`
-- `api/cron/[name].js:106` — `ERC8004_FETCH_TIMEOUT_MS`
-- `vercel.json` — `maxDuration` for the cron function
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-erc8004-crawl-timeout.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-marketplace-agents-500.md b/prompts/agent-fixes/fix-marketplace-agents-500.md
deleted file mode 100644
index 206bba56e..000000000
--- a/prompts/agent-fixes/fix-marketplace-agents-500.md
+++ /dev/null
@@ -1,118 +0,0 @@
-# Fix: GET /api/marketplace/agents — 105 × 500 errors, likely 42P18 on LIMIT/OFFSET
-
-## Context
-
-`GET /api/marketplace/agents` (the main public marketplace listing) returns 500 on ~105 requests. This is the highest-traffic public endpoint — every visitor to the marketplace page hits it. The error body contains no upstream detail because the log line is `console.error('[marketplace/list]', err?.message || err)` which truncates the message.
-
-## Root Cause
-
-Read `api/marketplace/[action].js` lines 342–412 in full before touching anything.
-
-The `handleList` function at line 367 runs a `sql.transaction()` with two queries. The second query ends with:
-
-```javascript
-LIMIT ${limit + 1} OFFSET ${offset}
-```
-
-`limit` and `offset` are JavaScript numbers (validated by `Number()` + `Math.min/max`). However, when passed as template literal interpolations into a Neon `sql\`...\`` tag inside `sql.transaction()`, PostgreSQL's extended query protocol cannot infer their types — they appear as bare `$N` parameters in LIMIT/OFFSET position with no type context.
-
-This produces PostgreSQL error **42P18** (`could not determine data type of parameter $N`), the same class of bug that affects `api/billing/withdrawals/index.js`. The fix is identical: add `::int` casts.
-
-Additionally, audit that all referenced tables and columns exist in the production Neon database. The query joins `skill_purchases`, `agent_reviews`, `asset_prices`, and `avatars` — any missing column causes a different class of 500 that would also be visible in logs.
-
-## What You Must Fix — Completely
-
-### Fix 1: Add `::int` casts to LIMIT and OFFSET in `handleList`
-
-In `api/marketplace/[action].js` at the marketplace listing query (around line 406):
-
-**Change:**
-```javascript
-LIMIT ${limit + 1} OFFSET ${offset}
-```
-
-**To:**
-```javascript
-LIMIT ${limit + 1}::int OFFSET ${offset}::int
-```
-
-The `::int` cast is a PostgreSQL-side type annotation. It appears as `LIMIT $N::int OFFSET $N::int` in the prepared statement, giving the query planner the type context it needs.
-
-Also check the second `handleList` function (for the "mine" or admin variant if one exists, around line 437) — if it also has `LIMIT/OFFSET` interpolations, apply the same cast.
-
-### Fix 2: Verify referenced tables and columns exist
-
-Run these queries against the production Neon database (use `psql "$DATABASE_URL"` or the Neon console):
-
-```sql
--- Verify all tables used in the marketplace join exist
-SELECT table_name FROM information_schema.tables
-WHERE table_name IN ('agent_identities', 'avatars', 'users', 'skill_purchases', 'agent_reviews', 'asset_prices')
-AND table_schema = 'public';
-
--- Verify specific columns used in the query
-SELECT column_name FROM information_schema.columns
-WHERE table_name = 'skill_purchases' AND column_name IN ('agent_id', 'status', 'created_at', 'confirmed_at');
-
-SELECT column_name FROM information_schema.columns
-WHERE table_name = 'agent_reviews' AND column_name IN ('agent_id', 'rating');
-
-SELECT column_name FROM information_schema.columns
-WHERE table_name = 'asset_prices' AND column_name IN ('item_type', 'item_id', 'is_active', 'amount', 'currency_mint', 'chain', 'mint_decimals');
-
-SELECT column_name FROM information_schema.columns
-WHERE table_name = 'avatars' AND column_name IN ('id', 'thumbnail_key', 'deleted_at');
-```
-
-If any column is missing, add it with a migration in `api/_lib/migrations/`. Do not alter the query to skip columns — add the missing columns.
-
-### Fix 3: Improve error logging to surface the full error
-
-The current `console.error('[marketplace/list]', err?.message || err)` truncates stack traces. Change it to log the full error code:
-
-```javascript
-} catch (err) {
- console.error('[marketplace/list]', err?.code, err?.message || err);
- return error(res, 500, 'db_error', 'Failed to load marketplace listing');
-}
-```
-
-The `err.code` will be `'42P18'` if it's a type inference error, or another Postgres error code if something else is failing. This makes future diagnosis instant.
-
-### Verify the fix
-
-1. After making the code change, run the module syntax check:
- ```bash
- node --input-type=module <<'EOF'
- import('./api/marketplace/[action].js').then(() => console.log('OK')).catch(e => console.error(e.message))
- EOF
- ```
-
-2. Start the dev server (`npm run dev`) and navigate to the marketplace page. The agent listing must load without errors and the network tab must show a successful response from `/api/marketplace/agents`.
-
-3. Verify no 42P18 or other 500 errors appear in Vercel logs for this endpoint after deploy.
-
-## Do Not
-
-- Do not add a try/catch around the `sql.transaction()` that returns an empty array on DB error — fix the root cause.
-- Do not remove the `sql\`SET LOCAL statement_timeout = '8000'\`` line — it protects against query hangs and must stay.
-- Do not switch to raw string interpolation for limit/offset even though they're validated integers — parameterized queries with `::int` casts is the correct pattern.
-
-## Related Files
-
-- `api/marketplace/[action].js:367–411` — `handleList`, the broken query
-- `api/billing/withdrawals/index.js` — same 42P18 pattern (see `fix-billing-withdrawals-42p18.md` for reference)
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-marketplace-agents-500.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-mocap-clips-sql-params.md b/prompts/agent-fixes/fix-mocap-clips-sql-params.md
deleted file mode 100644
index a7ced3bfe..000000000
--- a/prompts/agent-fixes/fix-mocap-clips-sql-params.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Fix: GET /api/mocap/clips — 6 × 500 errors, SQL positional parameter mismatch
-
-## Context
-
-`GET /api/mocap/clips` and `POST /api/mocap/clips` each return 500 on some requests. The `handleList` function uses a raw SQL string with positional parameters (`$1`, `$2`, etc.) built up dynamically via `params.push()`. The parameter indices must exactly match the push order, including conditional branches.
-
-## Root Cause
-
-Read `api/mocap/clips.js` in full before touching anything, paying close attention to `handleList` and the conditional `kindFilter` branch (line 87).
-
-The function builds an SQL string and a `params` array conditionally. The `$N` placeholder indices in the SQL string must match the index at which each value was pushed into `params`. When `kindFilter` is provided, it adds an extra parameter — if the SQL template uses a hardcoded `$4` but the `kindFilter` push changes the expected index, the query will either fail with a parameter count mismatch or bind the wrong value.
-
-Specifically examine:
-1. The order of `params.push()` calls
-2. Whether the `$N` placeholders in the SQL string increment correctly for each conditional branch
-3. The cursor (`decoded.createdAt`) push and whether it's always at the same `$N` position regardless of the `kindFilter` branch
-
-## What You Must Fix — Completely
-
-### Fix 1: Audit and correct the parameter binding
-
-Read the full `handleList` function and trace every `params.push()` call:
-
-```
-params[0] = auth.userId or null
-params[1] = auth.userId or null (second occurrence)
-params[2] = kindFilter (conditional)
-params[3] = cursor value (conditional, position shifts when kindFilter added)
-params[4] = limit + 1
-```
-
-If `kindFilter` is truthy, every `$N` after the kindFilter push must be incremented by 1. Verify the SQL string does this correctly. If not, fix the SQL string to use the correct `$N` indices.
-
-A safer pattern is to build the WHERE clauses conditionally:
-
-```javascript
-const whereClauses = ['deleted_at IS NULL'];
-const params = [];
-
-if (auth.userId) {
- params.push(auth.userId);
- whereClauses.push(`user_id = $${params.length}`);
-}
-if (kindFilter && /^[a-z]+$/.test(kindFilter)) {
- params.push(kindFilter);
- whereClauses.push(`kind = $${params.length}`);
-}
-// cursor
-if (decoded?.createdAt) {
- params.push(decoded.createdAt);
- whereClauses.push(`created_at < $${params.length}`);
-}
-// limit is always last
-params.push(limit + 1);
-const limitPlaceholder = `$${params.length}::int`;
-
-const sqlStr = `
- SELECT ...
- WHERE ${whereClauses.join(' AND ')}
- ORDER BY created_at DESC
- LIMIT ${limitPlaceholder}
-`;
-```
-
-This pattern uses `$${params.length}` to self-document the index, making it impossible to have a mismatch.
-
-### Fix 2: Verify the LIMIT/OFFSET parameter has `::int` cast
-
-The Neon serverless driver has the same 42P18 problem for LIMIT/OFFSET as described in `fix-billing-withdrawals-42p18.md`. If the raw SQL uses `$N` in LIMIT position without a type cast, add `::int`:
-
-```sql
--- Change:
-LIMIT $4
--- To:
-LIMIT $4::int
-```
-
-### Fix 3: Improve error logging
-
-The current catch at line 113 does:
-```javascript
-console.error('[mocap/clips/list]', err?.message || err);
-```
-
-Add the error code so future diagnosis is instant:
-```javascript
-console.error('[mocap/clips/list]', err?.code, err?.message || err);
-```
-
-### Fix 4: Verify POST 405 is not from vercel.json
-
-The 405 on `POST /api/mocap/clips` suggests the route may be restricted to GET. Check `vercel.json` for any route entry that limits this path to GET methods. If found, remove the method restriction — the handler correctly accepts both GET and POST.
-
-### Verify the fix
-
-1. Start the dev server (`npm run dev`)
-2. Request `GET /api/mocap/clips` as an authenticated user — must return 200 with a `clips` array
-3. Request `GET /api/mocap/clips?kind=bvh` — must return filtered results without error
-4. Request `GET /api/mocap/clips?kind=bvh&cursor=<timestamp>` — must return paginated results
-
-No 500 errors should appear after these tests.
-
-## Do Not
-
-- Do not switch from raw SQL to tagged templates for this query — the code comment explains why (`"syntax error at or near $1"` is a known Neon limitation for this pattern).
-- Do not add a try/catch that returns empty arrays on failure — fix the root cause.
-
-## Related Files
-
-- `api/mocap/clips.js:62–115` — `handleList` function (primary fix target)
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-mocap-clips-sql-params.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-permissions-list-500.md b/prompts/agent-fixes/fix-permissions-list-500.md
deleted file mode 100644
index 905d3b8c0..000000000
--- a/prompts/agent-fixes/fix-permissions-list-500.md
+++ /dev/null
@@ -1,104 +0,0 @@
-# Fix: GET /api/permissions/list — 2 × 500 errors, unlogged DB failure
-
-## Context
-
-`GET /api/permissions/list` returns 500 on 2 requests. The endpoint manages agent delegation permissions. The error message does not appear in Vercel logs at a level visible in the export, which makes diagnosis impossible without surfacing the actual Postgres error code.
-
-## Root Cause
-
-Read `api/permissions/[action].js` lines 310–430 in full before touching anything.
-
-The `handleList` function runs two separate DB queries: a public query and an auth-gated query. Both are wrapped in try/catch blocks (lines 371 and 425) that call `console.error`. However, the error message format uses `err?.message || err` which omits the Postgres error code — making it impossible to distinguish a 42703 (missing column), 42P01 (missing table), 42P18 (type inference), or ECONNRESET (connection failure) in the logs.
-
-The most likely root causes:
-1. A referenced column in `agent_delegations` doesn't exist (e.g., `delegation_hash`, `chain_id`, `contract_address`).
-2. The `isDelegationValid()` call or an on-chain verification step is throwing an unhandled error.
-3. The `agent_delegations` table itself is missing or has a schema mismatch.
-
-## What You Must Fix — Completely
-
-### Step 1: Add full error context to both catch blocks
-
-In `api/permissions/[action].js`, update both error catch blocks in `handleList`:
-
-**Public query catch (around line 371):**
-```javascript
-} catch (err) {
- console.error('[permissions/list] public query failed', err?.code, err?.message || err);
- return error(res, 500, 'db_error', 'Failed to load permissions');
-}
-```
-
-**Auth query catch (around line 425):**
-```javascript
-} catch (err) {
- console.error('[permissions/list] auth query failed', err?.code, err?.message || err);
- return error(res, 500, 'db_error', 'Failed to load permissions');
-}
-```
-
-### Step 2: Verify the agent_delegations table schema
-
-Connect to the production Neon database and check:
-
-```sql
--- Verify agent_delegations exists and has required columns
-SELECT column_name, data_type FROM information_schema.columns
-WHERE table_name = 'agent_delegations'
-ORDER BY ordinal_position;
-
--- Verify agent_identities referenced columns
-SELECT column_name FROM information_schema.columns
-WHERE table_name = 'agent_identities'
-AND column_name IN ('id', 'user_id', 'deleted_at');
-
--- Verify user_wallets referenced columns
-SELECT column_name FROM information_schema.columns
-WHERE table_name = 'user_wallets'
-AND column_name IN ('user_id', 'address');
-```
-
-If any column is missing from `agent_delegations`, create a migration in `api/_lib/migrations/` to add it with `ADD COLUMN IF NOT EXISTS`.
-
-### Step 3: Check the delegations query for 42P18
-
-Read the SQL query in `handleList`. If it has `LIMIT $N OFFSET $N` in LIMIT/OFFSET position without a `::int` cast, add the cast:
-
-```sql
--- Change:
-LIMIT ${limit} OFFSET ${offset}
--- To:
-LIMIT ${limit}::int OFFSET ${offset}::int
-```
-
-### Step 4: Verify the fix
-
-1. Start the dev server (`npm run dev`)
-2. Request `GET /api/permissions/list` as an authenticated user — must return 200 with a `permissions` array (empty is fine if no delegations exist)
-3. Request `GET /api/permissions/list` as an unauthenticated user — must return 200 with public delegations only
-
-No 500 errors after these tests.
-
-## Do Not
-
-- Do not return empty results silently when the DB query fails — log the error and return a proper 500.
-- Do not alter the delegations schema without adding a migration file.
-
-## Related Files
-
-- `api/permissions/[action].js:310–430` — `handleList` function
-- `api/_lib/migrations/` — where schema fix migrations go
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-permissions-list-500.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-pump-agent-stats-rpc-429.md b/prompts/agent-fixes/fix-pump-agent-stats-rpc-429.md
deleted file mode 100644
index 373311ebe..000000000
--- a/prompts/agent-fixes/fix-pump-agent-stats-rpc-429.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# Fix: pump-agent-stats cron — 7,000+ 504 timeouts due to Solana RPC rate limiting
-
-## Context
-
-The `pump-agent-stats` cron job is completely broken in production, producing 7,200+ 504 timeout errors across all deployments (`3dagent-lkvpaeq68` alone has 4,085). The cron runs every minute and times out on Vercel's 30-second limit every single invocation without doing useful work.
-
-Vercel logs:
-```
-Server responded with 429 Too Many Requests. Retrying after 500ms delay...
-Server responded with 429 Too Many Requests. Retrying after 1000ms delay...
-Server responded with 429 Too Many Requests. Retrying after 2000ms delay...
-Server responded with 429 Too Many Requests. Retrying after 4000ms delay...
-Vercel Runtime Timeout Error: Task timed out after 30 seconds
-```
-
-## Root Cause
-
-Read `api/cron/[name].js` at `handlePumpAgentStats` (line 687) and `pumpStatsSnapshotMint` (line 806) before touching anything.
-
-`pumpStatsSnapshotMint` calls `getRpcFallback({ network })` which is implemented in `api/_lib/pump.js`:
-
-```javascript
-const RPC_MAINNET = () => process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-```
-
-When `SOLANA_RPC_URL` is not set in the Vercel environment, every RPC call goes to the public `https://api.mainnet-beta.solana.com` endpoint, which is aggressively rate-limited and returns 429 on almost every call in production-scale usage.
-
-The retry delays (500ms → 1s → 2s → 4s = 7.5s per mint) burn through the 22-second deadline before completing even 2 mints. The handler already has a deadline check and circuit breaker (3 consecutive 429s triggers early exit), but they only work correctly when the RPC succeeds on at least some calls. When every call returns 429 immediately, the circuit breaks after 3 mints and skips the rest — still logging errors and never making progress.
-
-**This is fundamentally an infrastructure configuration problem.** The code is correct. The fix is to set a paid, private Solana RPC endpoint.
-
-## What You Must Fix — Completely
-
-### Step 1: Provision a paid Solana RPC endpoint
-
-Options (in order of preference):
-1. **Helius** (https://helius.dev) — best support for `getSignaturesForAddress` used in `pumpStatsSnapshotMint`. Free tier includes 100k credits/day.
-2. **QuickNode** (https://quicknode.com) — reliable, paid plans.
-3. **Triton One** (https://triton.one) — performance-focused.
-
-Sign up, create a mainnet-beta endpoint, and get the HTTPS endpoint URL. It will look like:
-- Helius: `https://mainnet.helius-rpc.com/?api-key=<YOUR_KEY>`
-- QuickNode: `https://<name>.solana-mainnet.quiknode.pro/<KEY>/`
-
-### Step 2: Set SOLANA_RPC_URL in Vercel
-
-```bash
-vercel env add SOLANA_RPC_URL production
-# paste the RPC endpoint URL when prompted
-```
-
-Also add to `.env` for local dev:
-```
-SOLANA_RPC_URL=https://mainnet.helius-rpc.com/?api-key=<YOUR_DEV_KEY>
-```
-
-Optionally set a separate devnet endpoint:
-```bash
-vercel env add SOLANA_RPC_URL_DEVNET production
-```
-
-### Step 3: Verify the RPC is in use
-
-After setting the env var, trigger a manual cron invocation:
-```bash
-curl -H "Authorization: Bearer $CRON_SECRET" https://three.ws/api/cron/pump-agent-stats
-```
-
-Expected response: `{"scanned":N,"updated":M,"errors":0,"graduations":0,"timeouts":0,"rate_limited":0,"skipped":0}` with `updated > 0`.
-
-### Step 4: Code guard — add per-mint RPC timeout
-
-Read `pumpStatsSnapshotMint` (line 806) and confirm the `getSignaturesForAddress` call is wrapped. If not, add a per-call AbortSignal so an individual RPC call can't hang indefinitely:
-
-```javascript
-const conn = getRpcFallback({ network });
-const sigs = await conn.getSignaturesForAddress(mintPk, { limit: 50 }, 'confirmed');
-```
-
-The existing `Promise.race` timeout in the outer loop (`PUMP_STATS_MINT_TIMEOUT_MS`) already guards this, but confirm `PUMP_STATS_MINT_TIMEOUT_MS` is defined and set to a value less than `22_000 / PUMP_STATS_MAX_PER_RUN`.
-
-### Step 5: Confirm existing safeguards are working
-
-After deploying with the real RPC:
-- The deadline check at line 704 (`DEADLINE = Date.now() + 22_000`) must still function — do not remove it.
-- The circuit breaker at line 713 (`consecutiveRateLimit >= 3`) must still function — do not remove it.
-- On a paid RPC with proper rate limits, both safeguards should rarely trigger.
-
-### Step 6: Redeploy and monitor
-
-```bash
-# After adding env var, trigger redeploy
-vercel deploy --prod
-```
-
-Monitor for 5 minutes after deploy. Vercel logs for `pump-agent-stats` should show:
-- No more "429 Too Many Requests" messages
-- No more "Task timed out after 30 seconds"
-- Valid JSON report responses
-
-## Do Not
-
-- Do not reduce `ERC8004_BLOCK_CHUNK` or modify the circuit breaker logic — those are unrelated to the 429 problem.
-- Do not add a `X402_ALLOW_MEMORY_FALLBACK=1` style workaround — the RPC must be a real paid endpoint.
-- Do not use `https://api.mainnet-beta.solana.com` in production — it will rate-limit immediately.
-- Do not mock the Pump.fun or Solana calls — this cron must call real endpoints.
-
-## Related Files
-
-- `api/_lib/pump.js:23` — `RPC_MAINNET` fallback to public endpoint
-- `api/cron/[name].js:687` — `handlePumpAgentStats`
-- `api/cron/[name].js:806` — `pumpStatsSnapshotMint` (RPC call at line 867)
-
-The code change (if any) is minimal — just an env var configuration. The primary fix is infrastructure.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-pump-agent-stats-rpc-429.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-threews-subdomain-esm.md b/prompts/agent-fixes/fix-threews-subdomain-esm.md
deleted file mode 100644
index 18037fb30..000000000
--- a/prompts/agent-fixes/fix-threews-subdomain-esm.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# Fix: api/threews/subdomain — 5 × 500 crashes (ESM import of @bonfida/spl-name-service)
-
-## Context
-
-`GET /api/threews/subdomain` returns 500 on every cold-start with a Node.js process crash. The error in Vercel logs:
-
-```
-[api] unhandled file:///var/task/node_modules/@bonfida/spl-name-service/dist/esm/instructions/burnInstruction.js:1
-import"../node_modules/buffer/index.js";import{TransactionInstruction as i}from"@solana/web3.js"
-```
-
-This kills the entire process — the `SyntaxError: Cannot use import statement in a module` prevents the handler from ever running.
-
-## Root Cause
-
-Read `api/threews/subdomain.js` (the import block at the top) and `api/_lib/threews-sns.js` (the full file) before touching anything.
-
-`api/threews/subdomain.js` imports from `api/_lib/threews-sns.js` at the **top level**. `threews-sns.js` in turn imports from `@bonfida/spl-name-service` and `@solana/web3.js` using static ESM `import` statements.
-
-Vercel's Node.js serverless runtime bundles API functions as CommonJS (CJS) by default. When Vercel's bundler (`@vercel/nft`) encounters `@bonfida/spl-name-service`, it pulls in the ESM distribution (`dist/esm/`) which uses bare `import` statements. The CJS runtime cannot execute these and throws a `SyntaxError` at cold-start — before any request handler runs.
-
-The fix must happen at the import level, not in the handler body.
-
-## What You Must Fix — Completely
-
-### Option A: Convert to dynamic import in `api/_lib/threews-sns.js`
-
-This is the cleanest fix for Vercel CJS bundling.
-
-In `api/_lib/threews-sns.js`, change the static imports of `@bonfida/spl-name-service` to dynamic imports that are resolved at call time. Specifically:
-
-1. Remove the top-level `import { ... } from '@bonfida/spl-name-service'` statements.
-2. Inside any function that uses the `@bonfida` exports, add:
- ```javascript
- const { NameRegistryState, getHashedNameSync, getNameAccountKeySync } = await import('@bonfida/spl-name-service');
- ```
-3. Repeat the same pattern for any other ESM-only dependency that is currently statically imported.
-
-After this change, the module loads without error at cold-start. The first request that calls a SNS lookup will pay a small dynamic import overhead (cached by Node after the first call).
-
-### Option B: Add @bonfida to Vercel externals in vercel.json
-
-In `vercel.json`, check whether there is an `externals` configuration for the Node bundler. If so, add:
-```json
-"functions": {
- "api/**/*.js": {
- "external": ["@bonfida/spl-name-service", "@solana/web3.js"]
- }
-}
-```
-
-This tells `@vercel/nft` to leave these packages as native `require()`s rather than trying to inline them. This works only if the packages also ship a CJS distribution — verify this by checking `node_modules/@bonfida/spl-name-service/package.json` for a `main` or `exports.require` field.
-
-Choose Option A if Option B is not available or if the package is ESM-only.
-
-### Step 3: Verify the fix locally
-
-After making the change:
-```bash
-node --input-type=module <<'EOF'
-import('./api/threews/subdomain.js').then(() => console.log('OK')).catch(e => console.error('FAIL:', e.message))
-EOF
-```
-
-Must print `OK`. If it prints `FAIL`, resolve the remaining ESM crash before deploying.
-
-### Step 4: Test the endpoint end-to-end
-
-1. Start the dev server (`npm run dev`)
-2. Request `GET /api/threews/subdomain?label=test` as an unauthenticated user — should return 401 (not 500)
-3. Request with a valid auth session and a `label` param — should return 200 with subdomain details
-
-Confirm no crash in the Vercel logs after deploy.
-
-### Step 5: Set ZAUTH_API_KEY (related issue)
-
-The Vercel logs for this endpoint also show `[zauth] disabled: ZAUTH_API_KEY not set`. While not the crash cause, this means the zauth middleware is disabled. After fixing the ESM crash, set `ZAUTH_API_KEY` in Vercel env (see `fix-zauth-api-key.md`).
-
-## Do Not
-
-- Do not wrap the top-level import in a try/catch — ESM syntax errors in static imports cannot be caught at runtime.
-- Do not remove the SNS integration — it must continue to function for subdomain registration.
-- Do not use a stub or mock for `@bonfida/spl-name-service` — this must call the real Solana Name Service.
-
-## Related Files
-
-- `api/threews/subdomain.js` — static importer
-- `api/_lib/threews-sns.js` — the file with the ESM imports (primary fix target)
-- `vercel.json` — may need `externals` config (Option B only)
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-threews-subdomain-esm.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-widgets-index-routing.md b/prompts/agent-fixes/fix-widgets-index-routing.md
deleted file mode 100644
index 23530e2e9..000000000
--- a/prompts/agent-fixes/fix-widgets-index-routing.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Fix: GET /api/widgets/index — 404/405 (verify vercel.json route is present)
-
-## Context
-
-`GET /api/widgets/index` returns 404 on 3 requests. The widgets listing endpoint lives at `/api/widgets` (not `/api/widgets/index`), but some callers are requesting the `/index` path.
-
-## Current State — Verify Before Changing Anything
-
-Read `vercel.json` and check whether the alias route already exists:
-
-```bash
-grep -n "widgets/index" vercel.json
-```
-
-As of the last audit, `vercel.json` already contains:
-```json
-{ "src": "/api/widgets/index", "dest": "/api/widgets" }
-```
-
-**If this route is already in vercel.json, this issue may be already fixed.**
-
-## If the Route Is Missing
-
-Add the route alias to `vercel.json`:
-```json
-{
- "src": "/api/widgets/index",
- "dest": "/api/widgets"
-}
-```
-
-Place it before the wildcard `"/api/widgets/([A-Za-z0-9_-]+)"` route to ensure it takes priority.
-
-## Additionally: Fix the frontend caller
-
-Find the frontend code that calls `/api/widgets/index` and update it to call `/api/widgets` directly. The canonical path is `/api/widgets` — the `/index` alias is a workaround, not a permanent solution.
-
-Search for the caller:
-```bash
-grep -rn "widgets/index" src/
-```
-
-Update any hit to use the correct path `/api/widgets`.
-
-## Verify the fix
-
-1. Check `vercel.json` for the `/api/widgets/index` → `/api/widgets` route
-2. Search `src/` for any frontend code calling `/api/widgets/index` and update it
-3. After deploy, request `GET https://three.ws/api/widgets/index` — must return 200 (same as `/api/widgets`)
-
-## Related Files
-
-- `vercel.json` — route table
-- `api/widgets.js` or `api/widgets/index.js` — the handler (whichever exists)
-- `src/` — frontend callers using the `/index` path
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-widgets-index-routing.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-x402-pay-503.md b/prompts/agent-fixes/fix-x402-pay-503.md
deleted file mode 100644
index 7507af197..000000000
--- a/prompts/agent-fixes/fix-x402-pay-503.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Fix: POST /api/x402-pay — 2 × 503 (transient upstream payment service failure)
-
-## Context
-
-`POST /api/x402-pay` returned 503 (Service Unavailable) on 2 occasions. This is low volume (2 occurrences) but represents failed payment transactions — each 503 means a user's payment was not processed, which may or may not have debited their wallet.
-
-## Root Cause
-
-Read `api/x402-pay.js` in full before touching anything.
-
-The 503 can come from:
-1. **Coinbase x402 SDK upstream** — the payment settlement service returned 503 during the call to the Coinbase/x402 network
-2. **Upstash Redis** — the feed/idempotency layer that `api/x402-pay.js` uses directly could be unavailable, returning 503
-3. **A connected third-party service** (e.g., NFT minting, token transfer) being temporarily down
-
-This is likely a transient infrastructure issue, not a code bug. However, the handler may not be retrying on transient 5xx from the upstream payment network before returning 503 to the client.
-
-## What You Must Fix — Completely
-
-### Step 1: Identify the exact source of the 503
-
-Read `api/x402-pay.js` and trace what the handler calls:
-1. Where does it interact with the x402 payment network?
-2. What does it do with the Upstash Redis feed (`FEED_KEY = 'x402:pay:feed'`)?
-3. Does the 503 come from a `res.status(503)` in the handler, or is it propagated from an upstream fetch?
-
-Search for where the handler might return 503:
-```bash
-grep -n "503\|service_unavailable\|upstream\|settlement" api/x402-pay.js
-```
-
-### Step 2: Add retry logic for transient upstream 5xx
-
-Wherever the handler makes an external HTTP call (to the Coinbase x402 network, a settlement API, or similar), add one retry on 503/504:
-
-```javascript
-async function fetchWithRetry(url, options, retries = 1) {
- const resp = await fetch(url, options);
- if ((resp.status === 503 || resp.status === 504) && retries > 0) {
- console.warn('[x402-pay] upstream', resp.status, '— retrying in 500ms');
- await new Promise(r => setTimeout(r, 500));
- return fetchWithRetry(url, options, retries - 1);
- }
- return resp;
-}
-```
-
-Only retry transient errors (503, 504). Do NOT retry:
-- 400/422 (bad payment request — client error)
-- 402 (payment required — expected protocol response)
-- 409 (conflict/duplicate — idempotency key already used)
-
-### Step 3: Ensure idempotency before retry
-
-The x402 protocol uses idempotency keys to prevent double-processing. Before adding retry logic, verify that:
-1. The payment request includes an idempotency key in the upstream call
-2. The retry sends the **same** idempotency key
-3. The Upstash idempotency cache (see `api/_lib/x402/idempotency-cache.js`) is checked before the retry
-
-If the upstream has already processed the payment and returns 503 for the settlement confirmation (not the payment itself), the retry is safe. If the 503 comes from the initial payment authorization, only retry if you're certain the first request did not go through.
-
-### Step 4: Log the upstream response body on error
-
-The current handler likely logs `console.error('[x402-pay]', err.message)` or similar. Enhance to include the upstream status and response body for future diagnosis:
-
-```javascript
-} catch (err) {
- const detail = err?.response ? `${err.response.status}: ${await err.response.text().catch(() => '')}`.slice(0, 300) : err?.message;
- console.error('[x402-pay] upstream failure:', detail);
- return error(res, 503, 'payment_upstream_error', 'Payment processing temporarily unavailable. Your card has not been charged. Please try again.');
-}
-```
-
-The user-facing message is important — 503 from a payment endpoint must clearly tell users whether they were charged.
-
-### Verify the fix
-
-1. Start the dev server (`npm run dev`)
-2. Simulate the payment flow with a test x402 request — must succeed on the first attempt
-3. If you can simulate an upstream 503 (e.g., using a network intercept), verify the handler retries once and returns the upstream result, or returns a clear error on persistent failure
-
-## Do Not
-
-- Do not retry more than once — payment operations must be idempotent and minimal retries
-- Do not swallow errors and return 200 — if payment fails, the response must reflect that
-- Do not change the idempotency cache behavior
-
-## Related Files
-
-- `api/x402-pay.js` — the handler (primary fix target)
-- `api/_lib/x402/idempotency-cache.js` — idempotency layer
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-x402-pay-503.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/agent-fixes/fix-x402-upstash-redis.md b/prompts/agent-fixes/fix-x402-upstash-redis.md
deleted file mode 100644
index 4cde8d2c7..000000000
--- a/prompts/agent-fixes/fix-x402-upstash-redis.md
+++ /dev/null
@@ -1,105 +0,0 @@
-# Fix: All x402 endpoints returning 500 — Missing Upstash Redis credentials
-
-## Context
-
-Every `/api/x402/*` endpoint in production is completely non-functional. Each request returns HTTP 500 with exit code 1 before the handler runs. The root cause is a module-level throw in `api/_lib/x402/idempotency-cache.js` that fires at cold-start when `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are missing from the Vercel environment.
-
-Affected endpoints (all return 500 on every request):
-- `GET /api/x402/model-check`
-- `GET /api/x402/dance-tip`
-- `GET /api/x402/skill-marketplace`
-- `GET /api/x402/symbol-availability`
-- `POST /api/x402/mint-to-mesh-batch`
-
-Error seen in Vercel logs:
-```
-Error: [x402-idempotency] UPSTASH_REDIS_REST_URL/TOKEN required in production.
-Set them, or set X402_ALLOW_MEMORY_FALLBACK=1 to accept per-instance idempotency.
- at file:///var/task/api/_lib/x402/idempotency-cache.js:28:8
-Node.js process exited with exit status: 1.
-```
-
-## Root Cause
-
-Read `api/_lib/x402/idempotency-cache.js`. At line 27-31 there is a top-level `throw` that fires on module import when both `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` are absent AND `X402_ALLOW_MEMORY_FALLBACK` is not set. This crashes the entire Node.js process. Because this module is imported at the top level by every x402 handler, every cold-start fails.
-
-## What You Must Do — Complete Fix Required
-
-### Step 1: Check for existing Upstash credentials
-
-1. Check `.env` and `.env.local` for `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN`.
-2. Run `vercel env ls` to see if the variables exist in the Vercel project (they may exist but not be pulled locally).
-3. If the variables exist in Vercel but not locally, pull them: `vercel env pull`.
-
-### Step 2: If credentials do not exist anywhere
-
-You must provision a real Upstash Redis instance. Do not use `X402_ALLOW_MEMORY_FALLBACK=1` as the permanent solution — it breaks cross-replica idempotency (two Vercel instances can each accept the same payment ID, causing double-processing).
-
-Options:
-- Log into Upstash console and create a new Redis database (region: us-east-1 for lowest latency from Vercel iad1).
-- Or check if `UPSTASH_REDIS_REST_URL` is referenced in other Vercel env vars under a different name (e.g., `KV_REST_API_URL` from a Vercel KV integration) and wire those.
-
-### Step 3: Set the environment variables in Vercel
-
-```bash
-vercel env add UPSTASH_REDIS_REST_URL production
-vercel env add UPSTASH_REDIS_REST_TOKEN production
-```
-
-Also add to `.env` for local dev (using a separate dev Upstash database or using `X402_ALLOW_MEMORY_FALLBACK=1` locally only).
-
-### Step 4: Update `.env.example` or env documentation
-
-If a `.env.example` file exists at the project root, add entries for these two variables with a comment explaining they are required for x402 idempotency in production.
-
-### Step 5: Trigger a redeployment
-
-After setting env vars in Vercel, trigger a redeploy:
-```bash
-vercel deploy --prod
-```
-Or push a commit to `main` which will trigger auto-deploy.
-
-### Step 6: Verify
-
-After deploy, hit each affected endpoint and confirm:
-- `GET https://three.ws/api/x402/model-check` → should return 402 (payment required) or 200 (not 500)
-- `GET https://three.ws/api/x402/dance-tip` → same
-- `GET https://three.ws/api/x402/skill-marketplace` → same
-
-If you cannot make live HTTP requests, at minimum verify locally:
-```bash
-UPSTASH_REDIS_REST_URL=<url> UPSTASH_REDIS_REST_TOKEN=<token> node -e "import('./api/_lib/x402/idempotency-cache.js').then(() => console.log('OK')).catch(e => console.error(e.message))"
-```
-Must print `OK`.
-
-## Do Not
-
-- Do not set `X402_ALLOW_MEMORY_FALLBACK=1` in production as the permanent fix. The comment in the code says this is explicitly for per-instance fallback only and degrades idempotency guarantees.
-- Do not add a try/catch around the module throw to suppress it — that would silently break idempotency without anyone noticing.
-- Do not stub out the idempotency cache with a no-op for production.
-
-## Related Files
-
-- `api/_lib/x402/idempotency-cache.js` — the module that throws
-- `api/x402/model-check.js` — example endpoint importing the cache
-- `api/x402/dance-tip.js`
-- `api/x402/skill-marketplace.js`
-- `api/x402/symbol-availability.js`
-- `api/x402/mint-to-mesh-batch.js`
-
-Fix this completely. Every x402 endpoint must return non-500 responses after this fix is applied.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/agent-fixes/fix-x402-upstash-redis.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/animation-studio/01-avatar-loading-and-rigged-posing.md b/prompts/animation-studio/01-avatar-loading-and-rigged-posing.md
deleted file mode 100644
index bdaa870f8..000000000
--- a/prompts/animation-studio/01-avatar-loading-and-rigged-posing.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Task 1 — Load rigged avatars into /pose and pose real skeletons (gizmos + IK)
-
-> Read `prompts/animation-studio/00-README.md` first — it has the shared architecture, file
-> references, data shapes, and the non-negotiable rules. Follow `CLAUDE.md`. No mocks, no stubs,
-> wire 100%, design every state, verify in a real browser.
-
-You are extending the existing Pose Studio at `/pose` so it can pose **real rigged 3D avatars**,
-not just the built-in primitive mannequin. This is the foundation the keyframe timeline (Task 2)
-builds on, so the posing API you expose must be clean and skeleton-agnostic.
-
-## Outcome
-
-A user opening `/pose` can:
-1. Keep using the built-in primitive **mannequin** (current behavior) — this stays the default
- when no avatar is requested.
-2. Load a **rigged GLB avatar** via the `?avatar=<id>` URL param (works for demo avatar ids like
- `avatar_demo_disk_saga` and for real avatar ids), and via a **"Load avatar"** button that opens
- the existing avatar gallery picker (their own avatars when signed in, public/demo otherwise).
-3. **Pose the loaded rig**: select a bone, rotate it with on-screen **gizmos** (TransformControls)
- and fine sliders, and use **inverse kinematics** — drag a hand or foot and the limb chain solves.
-4. Reset pose, switch back to the mannequin, and read clear status/empty/error states throughout.
-
-## What to build
-
-### 1. Read the existing code first
-- [src/pose-studio.js](../../src/pose-studio.js), [src/pose-mannequin.js](../../src/pose-mannequin.js),
- [pages/pose.html](../../pages/pose.html). Understand `setupScene()`, the render loop, the
- raycaster/drag posing, the control panel, and the pose JSON shape.
-- [src/viewer.js](../../src/viewer.js) (~841–887) for the **GLTFLoader + Draco/KTX2/Meshopt decoder
- setup** — reuse this exact decoder configuration. Do not create a bare loader.
-- [src/avatar-gallery-picker.js](../../src/avatar-gallery-picker.js) — the picker you'll mount.
-- [src/avatar-export.js](../../src/avatar-export.js) for `normalizeBoneName()` — reuse it.
-- [api/_lib/demo-avatars.js](../../api/_lib/demo-avatars.js) for demo ids to test with.
-
-### 2. A skeleton-agnostic "rig" abstraction
-Introduce a small module (e.g. `src/pose-rig.js`) that presents a **uniform posing interface**
-over either the primitive `Mannequin` or a loaded skinned GLB:
-
-- `getBones()` → ordered list of posable bones with a canonical key (use `normalizeBoneName()`),
- a display label, and the underlying `THREE.Bone`/joint.
-- `getBoneQuaternion(key)` / `setBoneQuaternion(key, quat)` and Euler convenience getters/setters.
-- `getRootPosition()` / `setRootPosition(vec)` (Hips/pelvis translation).
-- `getPose()` / `applyPose(pose)` / `resetPose()` returning a **canonical pose object** keyed by
- normalized bone names with quaternions (so Task 2 can keyframe any rig uniformly). For the
- primitive mannequin, map its 16 joints onto the canonical names (pelvis→Hips, head→Head,
- shoulderL→LeftArm, etc.) so both paths produce the same pose shape.
-- A `bindToTarget` for IK chains (see below).
-
-The point: Task 2's timeline records `getPose()` snapshots and never needs to know whether it's a
-mannequin or a real avatar.
-
-### 3. Avatar loading
-- On boot, read `?avatar=<id>` from the URL. If present, fetch the avatar's GLB URL and load it:
- - For ids starting with `avatar_demo_`, resolve via the demo-avatars source / the public avatar
- API. For real ids, use `GET /api/avatars/public` (and `GET /api/avatars` with
- `credentials: 'include'` when signed in). Resolve to `model_url`.
- - Load with the reused GLTFLoader+decoders. On success, frame the camera to the model, swap the
- rig abstraction to the GLB skeleton, and remove/hide the primitive mannequin.
-- **"Load avatar" button** in the toolbar → `new AvatarGalleryPicker({ source: <'mine' if signed
- in else 'public'>, onSelect })`. On select, load that `model_url` and update the URL (`?avatar=`)
- without a full reload (history pushState) so the state is shareable.
-- A **"Mannequin"** option to return to the default primitive rig.
-- Handle every state: loading (skeleton/spinner with real progress from GLTFLoader `onProgress`),
- error (failed fetch / non-rigged GLB → actionable message), empty (signed-out user opening the
- picker sees public/demo avatars with a sign-in hint).
-
-### 4. Posing UX (the craftsmanship)
-- **Gizmos:** integrate `three/examples/jsm/controls/TransformControls.js` in rotate mode on the
- selected bone. Disable `OrbitControls` while dragging the gizmo (`dragging-changed` event).
-- **IK:** integrate `three/examples/jsm/animation/CCDIKSolver.js`. Define IK chains for the four
- limbs (shoulder→forearm→hand with a hand target; upper-leg→leg→foot with a foot target). Add
- draggable IK target handles so the user can pull a hand/foot and the chain solves. Provide a
- toggle between **FK** (rotate individual bones) and **IK** (drag end-effectors) posing modes.
- For the primitive mannequin, map IK chains onto its joints too (best-effort) or cleanly disable
- IK with an explanatory tooltip if a chain can't be built — never leave a dead toggle.
-- **Bone selection:** keep raycast click-to-select; also add a searchable bone list in the panel
- for rigs with many bones. Highlight the selected bone.
-- **Sliders:** keep per-axis fine rotation for the selected bone, driven by the rig abstraction.
-- **Presets:** keep the existing presets working for the mannequin; for real rigs, apply presets
- by mapping canonical bone names (skip bones the rig lacks).
-- Preserve PNG export.
-
-### 5. UI/UX + accessibility
-- Match the page's existing dark design tokens / CSS variables. Add hover/active/focus states and
- ARIA labels to every new control. Keyboard: `F`/`I` to toggle FK/IK, `R` to reset selected bone,
- `Esc` to deselect — show these in a small shortcuts hint.
-- Mobile-considerate layout (panels collapse at narrow widths).
-
-## Definition of done
-- `?avatar=avatar_demo_disk_saga` loads a real rigged avatar into `/pose`; "Load avatar" picker
- works; "Mannequin" returns to default — all verified in the browser with no console errors.
-- A user can select a bone, rotate it via gizmo + sliders, and drag a hand/foot with IK to repose
- the limb. FK/IK toggle works; no dead controls.
-- `getPose()` returns a canonical, normalized pose object for **both** mannequin and GLB rigs
- (verify by logging two snapshots). This is the contract Task 2 consumes.
-- Loading/empty/error states all designed and reachable. Network tab shows real avatar fetches.
-- `npm test` still green. Run the `completionist` subagent on changed files; fix all findings.
-- Leave a short handoff note: the rig API surface (method names) Task 2 should call.
-
-Do **not** build the timeline, saving, or monetization here — those are Tasks 2, 4, 6.
-Do not push unless the user explicitly approves (then push to both remotes per CLAUDE.md).
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/animation-studio/01-avatar-loading-and-rigged-posing.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/animation-studio/02-keyframe-timeline-and-export.md b/prompts/animation-studio/02-keyframe-timeline-and-export.md
deleted file mode 100644
index a394fb50d..000000000
--- a/prompts/animation-studio/02-keyframe-timeline-and-export.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Task 2 — Keyframe timeline, AnimationClip baking, live preview, and export
-
-> Read `prompts/animation-studio/00-README.md` first (shared architecture, clip format, rules).
-> Follow `CLAUDE.md`. No mocks, no stubs, wire 100%, design every state, verify in a real browser.
->
-> **Depends on Task 1** (`01-avatar-loading-and-rigged-posing.md`): a skeleton-agnostic rig
-> abstraction exposing `getPose()` / `applyPose(pose)` / per-bone quaternion getters/setters for
-> both the primitive mannequin and loaded GLB avatars. Read Task 1's handoff note for the exact
-> method names before starting.
-
-You are turning the poser into an **animation recorder**: the user sets a pose, drops a keyframe on
-a timeline, advances the playhead, re-poses, drops another keyframe — and the studio interpolates
-between keyframes and plays the result. This is how a walk cycle / wave / dance gets authored.
-
-## Outcome
-
-On `/pose`, with a mannequin or rigged avatar loaded, a user can:
-1. Add/move/delete **keyframes** on a timeline scrubber. Each keyframe captures the current pose.
-2. Scrub the playhead and see the rig interpolate between keyframes; **play/pause/loop** the whole
- animation in real time.
-3. Set animation **duration**, **fps**, per-keyframe **easing**, and **loop** on/off.
-4. **Bake** the keyframes into a `THREE.AnimationClip` whose tracks use canonical bone names — i.e.
- the exact format that plays everywhere on three.ws (see README "Animation clip format").
-5. **Export** the result as (a) a **GLB with embedded animation** and (b) a three.ws **clip JSON**.
-
-## What to build
-
-### 1. Keyframe data model
-- A keyframe = `{ id, time /* seconds */, pose /* canonical getPose() snapshot */, easing }`.
-- Keep them sorted by time. Adding a keyframe captures `rig.getPose()` at the current playhead.
- Re-dropping at an existing time updates it. Deleting and dragging-to-retime are supported.
-- Store the editing document as `{ name, duration, fps, loop, keyframes[] }` in module state. This
- is the in-memory project Task 4 will serialize/save.
-
-### 2. Interpolation + live preview
-Two acceptable approaches — choose one and implement it fully:
-- **(Preferred) Bake-then-mix:** build a `THREE.AnimationClip` from the keyframes (see baking
- below) and drive it with a `THREE.AnimationMixer`; scrub by `mixer.setTime(t)`; play by ticking
- `mixer.update(dt)` in the existing render loop. Re-bake when keyframes change (debounced).
-- **Manual interpolation:** between bracketing keyframes, `slerp` each bone quaternion and `lerp`
- the root position by the eased fraction, then `applyPose()`.
-
-Quaternion interpolation (slerp) for rotations is required — do not lerp Euler angles (gimbal
-artifacts). Apply per-keyframe easing (at minimum: linear, ease-in, ease-out, ease-in-out).
-
-### 3. Baking to a three.ws-compatible AnimationClip
-- For each posed bone, emit a `QuaternionKeyframeTrack` named `"<CanonicalBone>.quaternion"` with
- `times` = keyframe times and `values` = flattened `[x,y,z,w,...]`. Emit a
- `VectorKeyframeTrack`/position track `"Hips.position"` for root translation.
-- Use the **canonical Avaturn/Mixamo bone names** from the README (`Hips`, `Spine`, `Head`,
- `LeftArm`, `RightUpLeg`, ...). The rig abstraction from Task 1 already keys poses by normalized
- names — map them to these canonical track names so the clip plays on standard three.ws avatars.
-- The baked clip's `.toJSON()` must match the documented clip JSON shape
- (`{ name, duration, tracks:[{name,type,times,values}] }`). Verify by round-tripping through
- `AnimationClip.parse()`.
-
-### 4. Timeline UI (the craftsmanship)
-- A horizontal **timeline track** with a draggable **playhead**, time ruler (seconds), and
- **keyframe diamonds** the user can click to select, drag to retime, and delete.
-- Transport controls: play / pause / stop, loop toggle, jump-to-start/end, current-time readout.
-- Inputs for total **duration** and **fps**; an **easing** picker for the selected keyframe.
-- An **"Add keyframe"** button (and a keyboard shortcut, e.g. `K`) that captures the current pose
- at the playhead. Visual confirmation when a keyframe is added/updated.
-- **Optional polish (do if time allows, fully wired or omitted):** onion-skinning (ghost the
- neighbouring keyframe poses) to help align a walk cycle.
-- Empty state: when there are zero keyframes, explain the workflow ("Pose the figure, then press
- Add keyframe to start your animation"). Never a blank void.
-
-### 5. Export
-- **GLB with animation:** reuse the `GLTFExporter` path from [src/avatar-export.js](../../src/avatar-export.js)
- (it already passes `animations`). Export the current rig (or a clean skeleton when on the
- mannequin) with the baked clip embedded; download as `.glb`. The exported file must play its
- animation when re-opened in the three.ws viewer.
-- **Clip JSON:** download the baked `clip.toJSON()` as a `.json` matching
- `public/animations/clips/*.json`. This is the artifact that Task 4 saves to the account and Task
- 5 plays via `AnimationManager`.
-- Both export buttons must have loading + success + error states.
-
-### 6. Provide a clean handoff API for Task 4/5/6
-Expose (in module state or a small exported object): the current editing document, a
-`bake()` returning the `AnimationClip`, `serializeClip()` returning the clip JSON, and a
-`captureThumbnail()` (reuse the existing PNG capture) so Task 4 can save without re-implementing.
-
-## Definition of done
-- A user can build a multi-keyframe animation (e.g. a 4–6 keyframe walk cycle on a rigged avatar),
- scrub it, and **play it looping** smoothly — verified in the browser, no console errors.
-- Rotations interpolate via slerp (no gimbal popping); easing visibly changes timing.
-- "Export GLB" produces a file that **plays its animation** when loaded in the three.ws viewer
- (verify by loading the exported GLB). "Export JSON" matches the clip JSON schema and
- `AnimationClip.parse()` accepts it.
-- Timeline empty/loading/error states designed; every control has hover/active/focus + ARIA.
-- `npm test` green. Add a small unit/contract test for the bake → `toJSON` → `parse` round-trip if
- the suite has a matching location (e.g. under `tests/`). Run `completionist`; fix all findings.
-- Handoff note: the names of the `bake()`/`serializeClip()`/`captureThumbnail()` accessors Task 4
- will call, and the editing-document shape.
-
-Do not build account saving or monetization here (Tasks 4 and 6).
-Do not push unless the user explicitly approves (then both remotes per CLAUDE.md).
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/animation-studio/02-keyframe-timeline-and-export.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/animation-studio/03-backend-animation-clips-api.md b/prompts/animation-studio/03-backend-animation-clips-api.md
deleted file mode 100644
index e08859efb..000000000
--- a/prompts/animation-studio/03-backend-animation-clips-api.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# Task 3 — Backend: animation_clips table + /api/animations CRUD
-
-> Read `prompts/animation-studio/00-README.md` first (backend patterns, DB/auth/migration
-> conventions, the `mocap_clips` precedent). Follow `CLAUDE.md`. No mocks, real DB, wire 100%.
->
-> This task is **independent of the frontend** and can run in parallel with Tasks 1–2. Tasks 4, 5,
-> and 6 depend on it.
-
-You are adding the persistence layer for user-created animations: a table and a REST API to
-create, list, read, update, and delete animation clips owned by a user, with public/private
-visibility and fields ready for monetization (Task 6).
-
-**Mirror the existing `mocap_clips` implementation closely** — it already solves auth, ownership,
-slugs, visibility, soft-delete, and large-payload storage. Read it before writing:
-- [api/mocap/clips.js](../../api/mocap/clips.js) (GET list + POST create)
-- [api/mocap/[id].js](../../api/mocap/[id].js) (GET / PATCH / DELETE)
-- [api/_lib/migrations/2026-05-24-mocap-clips.sql](../../api/_lib/migrations/2026-05-24-mocap-clips.sql)
-- [api/_lib/db.js](../../api/_lib/db.js), [api/_lib/auth.js](../../api/_lib/auth.js),
- [api/_lib/schema.sql](../../api/_lib/schema.sql)
-
-## What to build
-
-### 1. Migration: `animation_clips`
-Create `api/_lib/migrations/<today's date>-animation-clips.sql` (use the real current date,
-`YYYY-MM-DD`). Mirror `mocap_clips` columns and indexes:
-
-- `id uuid pk default gen_random_uuid()`
-- `owner_id uuid not null references users(id) on delete cascade`
-- `avatar_id uuid references avatars(id) on delete set null` (the rig the animation targets)
-- `slug text not null`, `name text not null`, `description text`
-- `kind text not null default 'animation' check (kind in ('animation','loop','sequence'))`
-- `format text not null default 'three.ws.animation.v1'`
-- `duration_ms int not null default 0`, `frame_count int not null default 0`
-- `fps int`, `loop boolean not null default true`
-- `clip jsonb` — the baked `AnimationClip.toJSON()` (see README clip format). For large clips,
- support `storage_key text` (R2) exactly like `mocap_clips.frames`/`storage_key` does.
-- `thumbnail_key text`
-- `tags text[] not null default '{}'`
-- `visibility text not null default 'private' check (visibility in ('private','unlisted','public'))`
-- `price_amount numeric(30,9)`, `price_currency text` (populated by Task 6; nullable here)
-- `play_count bigint not null default 0`
-- `created_at`, `updated_at`, `deleted_at timestamptz`
-- `unique (owner_id, slug)`
-- Indexes mirroring mocap: owner+created_at (where not deleted), visibility+created_at (where
- public, not deleted), kind+created_at, and a GIN index on `tags`.
-- `updated_at` trigger using the shared `set_updated_at()` function (guard with the
- `EXCEPTION WHEN duplicate_object` block like other migrations).
-
-Also add the table definition to [api/_lib/schema.sql](../../api/_lib/schema.sql) after
-`mocap_clips`, so fresh deploys get it. Apply locally with `npm run db:migrate` and confirm via
-`npm run db:status` (do **not** edit the file after it's applied — roll forward).
-
-### 2. API: `api/animations/clips.js` (GET list, POST create)
-- Use a `resolveAuth(req, scope)` helper identical in spirit to mocap's (`getSessionUser` →
- `authenticateBearer`). Use the avatars scopes already in use (`'avatars:read'` / `'avatars:write'`)
- unless a more specific scope already exists.
-- **POST create:** validate with `zod` (mirror mocap's `createSchema`). Accept
- `{ name, slug?, description?, avatar_id?, tags?, visibility?, fps?, loop?, clip: { name, duration,
- tracks[] } }`. Validate the clip JSON shape (tracks have `name`, `times`, `values`, `type`).
- Enforce reasonable size limits; if the inline JSON exceeds the inline cap (mirror mocap's
- threshold), store to R2 and set `storage_key` instead of `clip`. Auto-generate a unique slug if
- absent. If `avatar_id` is provided, verify the avatar is owned by the caller (mirror mocap's
- ownership check). Insert with `sql`...`` tagged template; return the created row.
-- **GET list:** mirror mocap's dynamic-WHERE logic — unauthenticated → only `visibility='public'`;
- authenticated → own clips, plus public when `include_public=true`. Support `limit`, `cursor`
- (created_at DESC), `visibility`, and a `tag` filter. Never return soft-deleted rows.
-
-### 3. API: `api/animations/[id].js` (GET, PATCH, DELETE)
-- **GET:** return a single clip by id. Private clips → 404 for non-owners; public/unlisted →
- visible. Optionally increment `play_count` on a query flag (mirror any mocap behavior). Resolve
- `clip` from R2 when `storage_key` is set (presigned or inlined per mocap's read path).
-- **PATCH:** owner-only; update `name`, `description`, `tags`, `visibility`, `avatar_id` (re-check
- ownership), `loop`. Do not allow changing `owner_id`.
-- **DELETE:** owner-only **soft delete** (`deleted_at = now()`), mirroring mocap.
-
-### 4. Errors, validation, security
-- Handle all error boundaries: unauthenticated (401), not-owner/not-found (404), validation (400),
- oversized payload (413/400). Use the same error helper/shape the mocap endpoints use.
-- No SQL injection (tagged templates only). No leaking other users' private clips. Rate/size limits
- consistent with mocap.
-
-## Definition of done
-- `npm run db:migrate` applies cleanly; `npm run db:status` shows it applied; schema.sql updated.
-- POST creates a clip (verify with a real authenticated request — e.g. via the dev server and a
- signed-in session, or a documented `curl` using a session cookie/API key). GET lists own +
- public correctly; private clips are invisible to others. PATCH and soft-DELETE work and respect
- ownership. Verify each with real requests and paste the responses in your summary.
-- Avatar-ownership check rejects linking an avatar the caller doesn't own.
-- Add contract tests mirroring any existing API test pattern under `tests/` if present.
-- `npm test` green. Run `completionist` on changed files; fix all findings.
-- Handoff note: the exact request/response shapes for create + list + get, so Task 4 (save UI),
- Task 5 (playback), and Task 6 (monetization) can integrate without guessing.
-
-Do not build UI here. Do not wire payments here (Task 6 adds pricing on top of these rows).
-Do not push unless the user explicitly approves (then both remotes per CLAUDE.md).
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/animation-studio/03-backend-animation-clips-api.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/animation-studio/04-save-and-library.md b/prompts/animation-studio/04-save-and-library.md
deleted file mode 100644
index 94d07b5bb..000000000
--- a/prompts/animation-studio/04-save-and-library.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# Task 4 — Save animations to account + "My animations" library in the editor
-
-> Read `prompts/animation-studio/00-README.md` first. Follow `CLAUDE.md`. No mocks, real APIs,
-> wire 100%, design every state, verify in a real browser.
->
-> **Depends on Task 2** (timeline + `bake()`/`serializeClip()`/`captureThumbnail()` accessors and
-> the editing-document shape) and **Task 3** (`/api/animations` CRUD + request/response shapes).
-> Read both tasks' handoff notes before starting.
-
-You are connecting the in-browser animation editor to the user's account: save, load, manage, and
-re-edit animations. This is what makes the studio a real tool instead of a one-shot exporter.
-
-## Outcome
-
-On `/pose`, a signed-in user can:
-1. **Save** the current animation to their account (name, description, tags, visibility, linked
- avatar, thumbnail) via `POST /api/animations/clips`.
-2. Open a **"My animations"** library (drawer/modal) listing their saved clips with thumbnails,
- open one back into the editor to continue editing, **update** it (`PATCH`), or **delete** it.
-3. See proper auth handling: a signed-out user who tries to save is prompted to sign in, then
- returns to their work intact.
-
-## What to build
-
-### 1. Save flow
-- A **"Save"** button in the toolbar. On click:
- - If not signed in → show a sign-in prompt. Use the existing auth/session mechanism the rest of
- the app uses (session cookie via `credentials: 'include'`; check how other authed pages detect
- sign-in — search for the session/me endpoint and the `authenticate-wallet` flow). Do **not**
- invent a new auth path. Preserve the in-progress editing document across sign-in (e.g. keep it
- in memory / sessionStorage and restore on return).
- - If signed in → open a **save dialog**: name (required), description, tags, visibility
- (private/unlisted/public), and the linked avatar (default to the currently loaded avatar's id
- when one is loaded; otherwise none/mannequin).
-- On submit: call `serializeClip()` (Task 2) for the `clip` payload, `captureThumbnail()` for the
- thumbnail, and POST to `/api/animations/clips` with the metadata. Upload the thumbnail using the
- same mechanism mocap/avatars use for thumbnails (check `thumbnail_key` handling in
- [api/mocap/clips.js](../../api/mocap/clips.js) / the avatars upload path) — real upload, not a
- placeholder.
-- After save: switch the editor into "editing saved clip" state (store the returned id), so
- subsequent saves **PATCH** the existing clip and offer "Save as copy" to create a new one.
-- Loading + success + error states on the save action (disable button while in flight, real
- spinner, surfaced API errors).
-
-### 2. "My animations" library
-- A button opening a drawer/modal that fetches `GET /api/animations/clips` (own clips; offer a
- tab/toggle for public/community clips via `include_public=true`).
-- Render each clip as a card: thumbnail, name, duration, visibility badge, tags, updated date.
- Actions per card: **Open** (loads the clip's keyframes back into the editor — see below),
- **Rename/edit metadata** (PATCH), **Delete** (soft delete with confirm), **Export**, and (stub
- the hook for) **Sell** which Task 6 will fully wire.
-- States: loading (skeletons), empty ("You haven't saved any animations yet — create one and press
- Save" with a clear CTA), error (retry).
-
-### 3. Re-open a saved clip into the editor
-- Opening a saved clip must reconstruct the **editing document** (keyframes/duration/fps/loop), not
- just play a baked clip. Two paths — pick the one consistent with how Task 2 stored things:
- - If Task 2 persists the keyframe document (preferred), save that alongside the baked `clip` (add
- it to the create payload as part of `clip` metadata or a sibling field) so it can be restored
- losslessly for editing.
- - Otherwise, reconstruct an editable keyframe document from the baked clip's tracks (sample each
- track at its keyframe times back into per-bone pose snapshots).
- Coordinate with Task 2's document shape; if you need to extend the saved payload to make
- re-editing lossless, do it and update Task 3's create handler/validation accordingly (keep it
- backward compatible).
-- After opening, the correct avatar/mannequin should be loaded (use the clip's `avatar_id`); if the
- avatar can't be loaded (deleted/not owned), fall back to the mannequin with a clear notice.
-
-### 4. UX + accessibility
-- Match existing design tokens. Hover/active/focus states + ARIA on every control. Keyboard:
- `Ctrl/Cmd+S` to save. Confirm-before-delete. Toasts/inline status for save/update/delete results.
-- Optimistic UI is fine but must reconcile with the server response; never show a fake success.
-
-## Definition of done
-- A signed-in user saves an animation; it appears in "My animations" with a real thumbnail; the row
- exists in `animation_clips` (verify via the API/DB). Re-saving PATCHes; "Save as copy" creates a
- new clip.
-- Opening a saved clip restores an **editable** animation (keyframes intact) on the right rig, then
- plays correctly.
-- Signed-out save prompts sign-in and restores the in-progress work afterward.
-- Rename/edit-metadata and delete work and respect ownership (verify a second account can't see
- private clips).
-- All states designed; no console errors; network tab shows real `/api/animations` calls.
-- `npm test` green. Run `completionist`; fix all findings.
-- Handoff note: confirm the saved payload shape (esp. how the editable keyframe document is stored)
- for Task 5 (playback) and Task 6 (selling).
-
-Do not implement payments/pricing here — leave the "Sell" affordance as a clearly-labeled hook for
-Task 6. Do not push unless the user explicitly approves (then both remotes per CLAUDE.md).
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/animation-studio/04-save-and-library.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/animation-studio/06-monetization.md b/prompts/animation-studio/06-monetization.md
deleted file mode 100644
index b585f4758..000000000
--- a/prompts/animation-studio/06-monetization.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# Task 6 — Monetize animations: sell for USDC via x402, list in marketplace + bazaar
-
-> Read `prompts/animation-studio/00-README.md` first (x402 patterns, `paid_assets` +
-> `asset-download.js`, payout overrides, bazaar schema). Follow `CLAUDE.md`. No mocks, real
-> payments rails, wire 100%, design every state, verify in a real browser.
->
-> **Depends on Task 3** (`animation_clips` rows with `price_amount`/`price_currency`) and **Task 4**
-> (clips saved to accounts + the "Sell" hook in the library). Benefits from Task 5 (playback for
-> previews/post-purchase). Read their handoff notes first.
-
-You are letting creators **sell** the animations they make. The platform already sells downloadable
-assets for USDC — **reuse that machinery**, don't build a parallel one.
-
-Read these before writing:
-- [api/x402/asset-download.js](../../api/x402/asset-download.js) — the "pay once → presigned R2
- download" endpoint, with per-creator payout overrides + SIWX re-download. This is your template.
-- [api/_lib/x402-paid-endpoint.js](../../api/_lib/x402-paid-endpoint.js) — `paidEndpoint()` helper.
-- [api/_lib/x402-spec.js](../../api/_lib/x402-spec.js) — `buildBazaarSchema()`, `bazaarExtension()`,
- payment requirement structs (prices are **USDC atomics**, 6 decimals: `1_000_000` = $1.00).
-- [api/x402-skus.js](../../api/x402-skus.js) — hosted checkout SKUs → `/pay/c/<slug>`.
-- The marketplace page + bazaar UI and their data APIs (search `pages/marketplace*.html`,
- `public/bazaar.js`, `api/bazaar/*`).
-- Payout config + per-asset overrides in [api/_lib/env.js](../../api/_lib/env.js)
- (`X402_PAY_TO_*`, `creator_payto_base/solana/bsc`).
-
-## What to build
-
-### 1. Pricing an animation (creator side)
-- In the "My animations" library (Task 4), wire the **"Sell"** affordance into a real flow: set a
- **price** (USDC) and the **payout wallet(s)** (Base / Solana), then publish for sale.
-- Publishing for sale must:
- - Set `price_amount` / `price_currency` on the `animation_clips` row (Task 3 added these), and
- set visibility appropriately (a priced clip should be discoverable — `public`/`unlisted` as the
- UI specifies; gate the actual file behind payment, not behind listing visibility).
- - Make the clip's downloadable artifact available to the paid endpoint. Decide the artifact:
- the **GLB with embedded animation** (preferred for broad compatibility) and/or the clip JSON.
- Store it in R2 the way `paid_assets` stores files, and capture the per-creator payout addresses.
- If reusing the `paid_assets` table is the cleanest fit, create the `paid_assets` row from the
- animation (link it back to the `animation_clips.id`); otherwise add the needed columns to
- `animation_clips` and serve from there. Choose the approach that **minimizes divergence** from
- `asset-download.js` and document it.
-- Let the creator set/rotate price, unpublish, and see basic **earnings/stats** (mirror the stats
- pattern in [api/x402-skus.js](../../api/x402-skus.js) — paid calls, revenue, recent txs).
-
-### 2. Paid download endpoint
-- Add `api/x402/animation-download.js` modeled directly on `asset-download.js`:
- - `GET /api/x402/animation-download?id=<id>` (or `?slug=`). Look up the priced animation; if not
- priced/published, 404.
- - Wrap with `paidEndpoint()`: price from the row's atomics, networks Base + Solana, payout via the
- per-creator override (`buildPayToOverride`-style), bazaar extension via `buildBazaarSchema()`.
- - On payment: presign the R2 artifact (GLB/JSON) and return `{ ok, title, mimeType, sizeBytes,
- downloadUrl, expiresAt }` exactly like `asset-download.js`. Wire **SIWX re-download** so buyers
- re-download without re-paying (reuse the `siwx_payments` flow).
- - Increment a purchase counter / record the checkout call for stats.
-
-### 3. Buyer experience
-- On the public gallery / animation detail (Task 5) and in the marketplace, a priced animation shows
- its price and a **Buy** button that runs the existing x402 payment flow (reuse the drop-in
- payment modal / SKU checkout used elsewhere — search for the existing client payment widget;
- do not hand-roll wallet signing). After payment, the buyer can **download** the GLB/JSON and
- **play** it (link into Task 5's playback / "use on my avatar").
-- Optionally create a hosted SKU (`/pay/c/<slug>`) per the `x402-skus.js` pattern so creators get a
- shareable checkout link. If you add it, wire it fully (creation + the `/pay/c/<slug>` page render).
-- States: price display, buy in-flight, payment success (download + play CTA), payment
- error/cancel (recoverable), already-purchased (SIWX → free re-download).
-
-### 4. Listing in marketplace + bazaar
-- Make priced animations appear in the **marketplace** (whatever data source the marketplace page
- reads — add animations to it with title, price, seller, thumbnail, category "Animation") and
- discoverable in the **bazaar** via the `bazaarExtension()`/`buildBazaarSchema()` declaration on
- the paid endpoint so x402 discovery validation passes.
-- Cross-link: marketplace card → animation detail/preview (Task 5) → Buy. No dead links.
-
-## Definition of done
-- A creator can price + publish an animation; the row carries `price_amount`/`price_currency` and a
- per-creator payout address; the artifact is in R2.
-- `GET /api/x402/animation-download?id=...` returns a real 402 challenge with the correct price and
- payout, and — after a real payment on a test network/wallet — returns a working presigned
- download. SIWX re-download works without re-paying. **Verify the 402 challenge and the post-
- payment response with real requests and paste them.** (If a live settlement can't be performed in
- the environment, demonstrate the 402 envelope + verify path and document exactly what a real
- payment would complete — but do not fake a settlement.)
-- The animation appears in the marketplace and validates in the bazaar discovery schema.
-- Buyer flow works end-to-end in the browser: see price → Buy → pay → download + play. All states
- designed; no console errors.
-- Creator earnings/stats reflect real checkout records.
-- `npm test` green. Run `completionist`; fix all findings.
-- Handoff note: anything Task 7 should cross-link (marketplace entry points, gallery, studio).
-
-Reuse the existing x402 facilitator/settlement rails and payout config — never mock a payment, a
-settlement, or an on-chain tx. Do not push unless the user explicitly approves (then both remotes
-per CLAUDE.md).
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/animation-studio/06-monetization.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/02-avatars.md b/prompts/dashboard-next/02-avatars.md
deleted file mode 100644
index e426faf70..000000000
--- a/prompts/dashboard-next/02-avatars.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# 02 — Avatars page
-
-**Read `prompts/dashboard-next/_shared.md` first.** It contains the project rules, foundation paths, atomic classes, smoke-test recipe, and commit instructions. Then build the slice below.
-
-## Your slice
-
-Build the Avatars page at **`/dashboard-next/avatars`** — a grid of every avatar the signed-in user owns, with live 3D thumbnails and inline management.
-
-## Layout (top to bottom)
-
-1. **Page header row** — `.dn-h1` ("Avatars") + `.dn-h1-sub` ("Your 3D models, animated and ready to embed."). On the right of the row, a `.dn-btn.primary` "+ New avatar" that opens a small popover with three options:
- - "From a selfie" → `/create/selfie`
- - "Upload a GLB" → `/create`
- - "From an existing avatar" → `/marketplace`
-
-2. **Filter bar** — a thin row with:
- - Search input (`.dn-btn`-styled, full-width on the left) — filters client-side by name as the user types
- - Visibility filter chips: All · Public · Unlisted · Private (one chip active, click toggles)
- - Sort dropdown: Newest · Oldest · Name A→Z · Name Z→A
-
-3. **Avatar grid** — `grid-template-columns: repeat(auto-fill, minmax(220px, 1fr))`. Each card:
- - Top: live `<threews-avatar avatar-id="…" hide-chrome bg="transparent">` (load via `<script src="/embed.js">` in the page HTML), 220×280 portrait
- - Below: name (editable inline on click — pencil icon on hover), visibility tag (`.dn-tag.success` for public, `.dn-tag` neutral for unlisted, `.dn-tag.warn` for private), `relTime(updated_at)`
- - Top-right corner of the card: a `⋮` menu button revealing: Rename · Change visibility · Copy embed snippet · Open in viewer (`/app#avatar=<id>`) · Download GLB · Delete (`.dn-btn.danger`, confirm modal required)
-
-4. **Pagination** — cursor-based using `/api/avatars?cursor=…&limit=24`. Render a `.dn-btn.ghost` "Load more" at the bottom while `next_cursor` is non-null. Auto-load the next page when the button enters the viewport (IntersectionObserver). Stop showing the button when `next_cursor === null`.
-
-## Files you create
-
-- `pages/dashboard-next/avatars.html` (use the page boilerplate from `_shared.md`, add `<script src="/embed.js"></script>`)
-- `src/dashboard-next/pages/avatars.js`
-
-Do not modify any other file.
-
-## API endpoints to use
-
-- `GET /api/avatars?limit=24&cursor=…` → `{ avatars: [{ id, name, visibility, updated_at, thumbnail_url?, source_meta? }], next_cursor }`
-- `PATCH /api/avatars/:id` → `{ name?, visibility? }` for inline rename and visibility change
-- `DELETE /api/avatars/:id` → confirm via a custom modal (not `confirm()`), then optimistically remove from the grid and toast on success / undo on failure
-- `GET /api/avatars/:id` → for the embed snippet (returns id you already have, but read the helper in `src/dashboard/dashboard.js` to see what extra metadata the existing avatar page uses)
-
-Read `src/dashboard/dashboard.js` for the existing avatar list/edit/delete patterns before writing — match them.
-
-## Empty / loading / error states
-
-- **First load:** show 8 skeleton cards (`.dn-skeleton` boxes shaped 220×280).
-- **No avatars at all:** `.dn-empty` block:
- > **No avatars yet.** Build your first 3D agent — drop a selfie or upload a GLB.
- > [Create from selfie] [Upload a GLB]
-- **Network failure:** inline error banner above the (empty) grid with a Retry button. Do not blank the page.
-- **Inline action failure** (rename, visibility change, delete): toast with the server error string, never silently fail.
-
-## Visual quality bar
-
-- Card hover: scale 1.015 over 180ms, soft accent glow (`box-shadow: 0 0 0 1px var(--nxt-accent-soft), 0 8px 24px rgba(0,0,0,0.4)`)
-- Visibility chips: pill-shaped, `--nxt-accent-soft` background when active
-- ⋮ menu opens with a 120ms fade + 4px upward translate; closes on outside click and ESC
-- Delete confirm modal uses a `.dn-panel` style with `.dn-btn.danger` for Delete, `.dn-btn.ghost` for Cancel
-
-## Verification
-
-Smoke-test per `_shared.md`:
-```bash
-node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/avatars /tmp/dn-avatars.png
-```
-Open the image. Verify:
-- At least one real 3D avatar is rendered in the grid (if the test user has avatars)
-- No console errors
-- Hover an avatar card in headless mode by appending `await p.hover('.dn-avatar-card:first-child')` before screenshot to capture the hover treatment
-
-Run `npx vite build` and confirm clean.
-
-## Commit message
-
-`dashboard-next: avatars page — live 3D grid + inline manage + cursor pagination`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/02-avatars.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/03-widgets.md b/prompts/dashboard-next/03-widgets.md
deleted file mode 100644
index 86cc35b7a..000000000
--- a/prompts/dashboard-next/03-widgets.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# 03 — Widgets page
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-Build the Widgets page at **`/dashboard-next/widgets`** — a grid of every widget the user has configured, each with a live iframe preview, stats, and quick management actions.
-
-## Layout (top to bottom)
-
-1. **Header row** — `.dn-h1` "Widgets" / `.dn-h1-sub` "Embed your agents anywhere — and see how they're performing." On the right, `.dn-btn.primary` "+ New widget" → `/widget-studio`.
-
-2. **Aggregate stat strip** — four small inline stats (not full cards, more like an inline summary row): Total widgets · Views (7d) · Chat turns (7d) · Avg session (s). Compact, single-line, separated by `·` characters in `--nxt-ink-fade`. Fetch in parallel; each shows `—` until ready. Skip the entire strip if all four return zero.
-
-3. **Widget grid** — `grid-template-columns: repeat(auto-fill, minmax(320px, 1fr))`, gap 14px. Each card is a `.dn-panel` with:
- - **Top half (220px tall):** live `<iframe src="/widget#widget=<id>&kiosk=true" loading="lazy" sandbox="allow-scripts allow-same-origin allow-popups">`. This is the same surface the public embed uses, so we're dogfooding.
- - **Bottom (padding 14px):** widget name (link to `/widget-studio?id=<id>`), tiny status badge (`.dn-tag.success` "Active" if last view < 24h else `.dn-tag` "Idle"), two columns of stats: Views 7d / Turns 7d.
- - **Top-right corner ⋮ menu:** Open studio · Copy embed snippet · Duplicate · Open transcripts · Delete
-
-4. **Empty state** — `.dn-empty` if `/api/widgets` returns no rows:
- > **No widgets yet.** Turn any avatar into an embeddable agent — from a brand widget to a talking guide.
- > [Open widget studio]
-
-## Files you create
-
-- `pages/dashboard-next/widgets.html`
-- `src/dashboard-next/pages/widgets.js`
-
-Do not modify any other file.
-
-## API endpoints
-
-- `GET /api/widgets` → `{ widgets: [...] }` (or array; check `src/dashboard/dashboard.js`)
-- `GET /api/widgets/:id/stats?days=7` → views, turns, avg session
-- `POST /api/widgets/:id/duplicate` → returns new widget id, push it to the front of the grid
-- `DELETE /api/widgets/:id` → confirm modal, optimistic remove
-
-For the aggregate stat strip, sum across the per-widget `/stats` calls rather than inventing a new endpoint. Fire all stats requests in `Promise.allSettled` and use `.value` on fulfilled ones.
-
-## "Copy embed snippet"
-
-Opens a small popover (NOT a full modal) with three tabs:
-
-1. **Script tag** (default, easiest):
- ```html
- <script async src="https://three.ws/embed.js"
- data-widget="WIDGET_ID"
- data-reveal="interaction"
- data-poster="auto"></script>
- ```
-2. **iframe**:
- ```html
- <iframe src="https://three.ws/widget#widget=WIDGET_ID&kiosk=true"
- width="600" height="600" frameborder="0"></iframe>
- ```
-3. **Web component**:
- ```html
- <threews-avatar avatar-id="AVATAR_ID" hide-chrome></threews-avatar>
- ```
-
-Each tab has a "Copy" button (uses `navigator.clipboard.writeText`) and a toast on success.
-
-## Empty / loading / error states
-
-- 6 skeleton cards on first load (220px iframe slot shown as `.dn-skeleton`)
-- Stats failure on a single card: the card still renders, stats slots show `—`
-- Whole list failure: inline error banner with Retry, do not blank the page
-
-## Performance note
-
-Iframes are heavy. Use `loading="lazy"` and `<iframe>` only when the card scrolls into view (IntersectionObserver). Until then, render a poster image at `/api/widgets/<id>/og` (the existing OG-card endpoint — confirms exists in `public/embed.js`) inside the card with a "Click to preview" overlay.
-
-## Verification
-
-Smoke-test:
-```bash
-node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/widgets /tmp/dn-widgets.png
-```
-Verify:
-- Cards render with either iframes or poster images
-- Stats appear or skeleton, never `NaN`
-- No console errors (a `Failed to load resource: /api/widgets/.../og` 404 is acceptable if a widget has no OG; gracefully fall back to a generic placeholder gradient)
-
-`npx vite build` must pass.
-
-## Commit message
-
-`dashboard-next: widgets page — live iframe previews + per-card stats + embed snippet popover`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/03-widgets.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/04-library.md b/prompts/dashboard-next/04-library.md
deleted file mode 100644
index 0f4718b39..000000000
--- a/prompts/dashboard-next/04-library.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# 04 — Library page (animations · memory · strategy · voice)
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-Build the Library page at **`/dashboard-next/library`** — a single page that consolidates the four "creator inputs" today scattered across separate routes: Animations, Memory, Strategy, and Voice. Tabs at the top switch between them. URL hash drives the active tab (`#tab=animations` default).
-
-## Layout
-
-1. **Header row** — `.dn-h1` "Library" / `.dn-h1-sub` "Animations, memories, strategy notes, and voices your agents can draw on."
-
-2. **Tab strip** — four pills under the header, click to switch tabs, ARIA `role="tablist"`:
- - Animations · Memory · Strategy · Voice
- - Sticky to the top of the main scroll area
- - URL hash updates on switch (`history.replaceState` so refresh-able)
- - Active tab uses `.dn-tag.success` styling (accent background)
-
-3. **Active tab content** — render inside a single `<div data-slot="tab-body">`. Each tab is its own render function.
-
-## Per-tab content
-
-### Animations tab
-- Grid of every animation in the user's library (`GET /api/animations`)
-- Each card shows: clip name, duration (rounded to 0.1s), tags, source (uploaded / preset / mocap), and a tiny waveform / preview thumb if available
-- "Upload .glb / .fbx" button at the top of the tab — wires to `/api/animations/presign` flow (read `src/dashboard/dashboard.js` for the existing animation-upload code — copy that pattern exactly)
-- Empty state: `.dn-empty` with copy: "No animations yet. Upload a .glb or pick from our mocap library." with two CTAs: [Upload] [Browse presets → `/walk`]
-
-### Memory tab
-- A list of every persistent memory entry across all the user's agents (`GET /api/agents/me` to list agents, then per-agent `GET /api/agents/:id/memory` — match existing dashboard.js)
-- Each entry: timestamp, agent name (chip), short content preview, source (which conversation it came from). Click to expand the full text inline.
-- "+ Add a note" button at top — opens a small inline editor that POSTs to `/api/agents/:id/memory` (let the user pick which agent the note attaches to via a dropdown)
-- Empty state: "No memories yet. Your agents will save notes here from their conversations — or you can add one yourself."
-
-### Strategy tab
-- A single editable strategy document per agent (current dashboard has `/dashboard/strategy`). Dropdown at top picks agent; below, a `<textarea>` that loads `GET /api/agents/:id/strategy` and saves on blur via `PUT /api/agents/:id/strategy` (debounce 800ms). Auto-save indicator chip ("Saving…" → "Saved · `relTime`")
-- If the user has no agents, show `.dn-empty` "You don't have any agents yet" with CTA to `/dashboard-next/account` or `/create`
-
-### Voice tab
-- Voice picker for each agent: dropdown of available voices (poll `GET /api/voices/list` if it exists, otherwise fall back to whatever `public/dashboard/voice.html` uses)
-- For each agent, show: current voice name, a 12-second sample audio player (`<audio controls>` pointed at `GET /api/voices/sample?voice=<id>`), and a "Test with custom text" input that POSTs to `/api/voices/preview` (text-to-speech preview)
-- "Save" button per agent that PATCHes `/api/agents/:id` with `{ voice: <id> }`
-
-## Files you create
-
-- `pages/dashboard-next/library.html`
-- `src/dashboard-next/pages/library.js`
-- Optional: `src/dashboard-next/pages/library/animations.js`, `memory.js`, `strategy.js`, `voice.js` if you want per-tab split (recommended for readability — keep each under 250 lines)
-
-Do not modify any other file.
-
-## API endpoints
-
-Inspect `src/dashboard/dashboard.js`, `public/dashboard/memory.html`, `public/dashboard/strategy.html`, `public/dashboard/voice.html` for the canonical endpoint paths the existing code uses. **Reuse those paths verbatim** — do not invent new ones.
-
-Likely:
-- `GET /api/animations`, `POST /api/animations/presign`
-- `GET /api/agents`, `GET /api/agents/me`, `GET /api/agents/:id/memory`, `POST /api/agents/:id/memory`
-- `GET /api/agents/:id/strategy`, `PUT /api/agents/:id/strategy`
-- `GET /api/voices/list`, `POST /api/voices/preview`
-
-## Empty / loading / error states
-
-Every tab needs all three. A failed fetch in one tab must not break the others — they each have isolated try/catch blocks.
-
-## Verification
-
-Smoke-test each tab (one screenshot per tab):
-```bash
-for tab in animations memory strategy voice; do
- node scripts/_dn-shot.mjs "http://127.0.0.1:3010/dashboard-next/library#tab=$tab" "/tmp/dn-library-$tab.png"
-done
-```
-Open all four images. Verify:
-- Tab strip highlights the active tab in each shot
-- Real data is present (animations list, memories, etc.) if the test user has any
-- No console errors across any tab
-
-`npx vite build` must pass.
-
-## Commit message
-
-`dashboard-next: library page — animations + memory + strategy + voice tabs`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/04-library.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/05-api-embed.md b/prompts/dashboard-next/05-api-embed.md
deleted file mode 100644
index 51c7daac7..000000000
--- a/prompts/dashboard-next/05-api-embed.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# 05 — API & Embed page
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-Build the API & Embed page at **`/dashboard-next/api`** — the developer / integrator surface. API keys, MCP integration, ready-to-paste embed snippets, embed-policy controls, and webhook config (if any).
-
-## Layout
-
-1. **Header** — `.dn-h1` "API & embed" / `.dn-h1-sub` "Issue keys, configure MCP clients, embed agents anywhere."
-
-2. **Section: API keys** — `.dn-panel`:
- - Table of keys: name · prefix (e.g. `tws_…abc12`) · scopes (chips) · created · last used (`relTime` or "never") · Revoke button
- - "+ New key" button → opens modal: name input, scopes multi-select (pull scopes list from the existing dashboard.js — likely `avatars:read avatars:write agents:read agents:write widgets:read widgets:write`), expiry dropdown (Never · 30d · 90d · 1y)
- - On create, show the full secret ONCE in a copy-to-clipboard modal with a warning "This is the only time you'll see this key. Store it somewhere safe."
- - Revoke is destructive — confirm modal required
-
-3. **Section: MCP setup** — `.dn-panel`:
- - Subtitle: "Point Claude Desktop, Cursor, or any MCP client at your agents."
- - Three tabs: Claude Desktop · Cursor · Generic JSON
- - Each tab shows the exact config block to paste, with the user's actual API key pre-filled (use a placeholder `tws_yourkeyhere` and an inline "Pick which key" dropdown that swaps the displayed secret)
- - Copy button per snippet
- - "Test connection" button that calls a real endpoint (likely `/api/mcp/health` — check existing dashboard.js for the actual MCP test endpoint) and shows pass/fail inline
-
-4. **Section: Embed snippets** — `.dn-panel`:
- - Dropdown: pick one of the user's avatars OR widgets
- - Three tabs: Script tag · iframe · Web component (`<threews-avatar>`)
- - Live preview pane next to the snippets (320×320 iframe) so the user sees what they're about to paste
- - Each snippet has knobs that update both the code and the preview:
- - Width · Height · Background (transparent / dark / light) · Reveal mode (auto / interaction) · Hide chrome (checkbox)
- - Copy button per snippet
-
-5. **Section: Embed policy** — `.dn-panel`:
- - Origin allowlist per avatar — table of avatar → allowed origins (one per line), saved via PATCH to `/api/embed-policy/:avatarId` (read `api/_lib/embed-policy.js` for shape — `api/_mcp/embed-policy.js` exists). Default is `*` (anywhere). User can lock down to specific origins.
- - Per-row Save button (debounced auto-save on blur, indicator chip)
- - Help link: "Why does this matter?" → tooltip / inline explainer
-
-## Files you create
-
-- `pages/dashboard-next/api.html`
-- `src/dashboard-next/pages/api.js` (the file, not the directory — `api.js` is fine because it's under `pages/`)
-
-Do not modify any other file.
-
-## API endpoints
-
-Inspect `src/dashboard/dashboard.js`, `public/dashboard/storage.html`, and `public/dashboard/embed-policy.html` for the exact endpoint paths and request/response shapes — match them exactly.
-
-Likely:
-- `GET /api/keys` / `POST /api/keys` / `DELETE /api/keys/:id`
-- `GET /api/embed-policy?avatar_id=…` / `PUT /api/embed-policy/:avatar_id`
-- `GET /api/mcp/config` if it exists, otherwise build the JSON client-side from the user's session
-- `GET /api/avatars` and `GET /api/widgets` for the dropdowns
-
-## Empty / loading / error states
-
-- Keys empty: `.dn-empty` "No keys yet. Issue one to start hitting the API." + [+ New key]
-- MCP test failure: red chip inline next to the button
-- Embed-policy save failure: revert local state, toast with server error
-
-## Visual quality bar
-
-- Code snippets use a `<pre><code>` block with a dark inner background (`#0a0a10`), 1px stroke, monospace, soft accent line on the left
-- Copy buttons sit absolute top-right of the code block, become more visible on hover
-- Tab strips use the same pill style as the Library page
-
-## Verification
-
-```bash
-node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/api /tmp/dn-api.png
-```
-Verify:
-- All four sections visible
-- Real keys list (if test user has any) or empty state
-- Embed snippet preview iframe actually renders
-- No console errors
-
-`npx vite build` passes.
-
-## Commit message
-
-`dashboard-next: api & embed page — keys + MCP setup + live embed snippets + policy`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/05-api-embed.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/06-monetize.md b/prompts/dashboard-next/06-monetize.md
deleted file mode 100644
index b9b56c331..000000000
--- a/prompts/dashboard-next/06-monetize.md
+++ /dev/null
@@ -1,109 +0,0 @@
-# 06 — Monetize page
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-Build the Monetize page at **`/dashboard-next/monetize`** — consolidates Revenue, Payments, Subscriptions, Plan & Usage, Withdrawals, Earnings, and Tokens into one creator-friendly money hub.
-
-## Layout (top to bottom)
-
-1. **Header** — `.dn-h1` "Money" / `.dn-h1-sub` "Where your agents earn — and where it goes."
-
-2. **Hero metric row** — three large stat cards (`.dn-panel`):
- - **Available to withdraw** (`formatUsdc`) — sum of `referral_earnings_total` + agent revenue not yet withdrawn. Below: `.dn-btn.primary` "Withdraw" → opens withdraw modal
- - **30-day revenue** (`formatUsdc`) — `/api/billing/revenue?from=<30d ago>&to=<now>&granularity=day`
- - **Active subscriptions** (count + `formatUsdc`/mo MRR) — `/api/billing/subscriptions` (or whatever the existing path is — check `src/dashboard/dashboard.js`)
-
-3. **Revenue chart** — `.dn-panel`:
- - Title "Revenue · last 30 days" with a small dropdown to switch range (7d / 30d / 90d / 1y)
- - Vanilla `<svg>` bar chart, 240px tall, full width. One bar per day. Hover shows tooltip with day + amount.
- - Granularity adjusts with range: day for ≤90d, week for >90d
- - Source breakdown legend below the chart: how much came from API calls · subscriptions · skill unlocks · tips · token royalties
-
-4. **Recent payments table** — `.dn-panel`:
- - Columns: When (`relTime`) · Source · Amount · Status (`.dn-tag.success` "Settled" / `.dn-tag.warn` "Pending" / `.dn-tag.danger` "Failed") · TX link
- - Source examples: "API call · key tws_abc" · "Subscription · @handle" · "Skill unlock · pump-strategy"
- - Pagination: cursor or "Load more"
- - Filter chips at top: All · Subscriptions · API · Skills · Tips
-
-5. **Withdrawals section** — `.dn-panel`:
- - Pending withdrawals table at top (id · amount · chain · status · est arrival)
- - "Withdraw now" button → opens modal: chain selector (Solana / Base / Polygon / etc, only those with treasury keys configured), destination address (validate format per chain), amount input (clamps to available)
- - Past withdrawals (last 10) collapsed under a "Show past withdrawals" toggle
-
-6. **Plan & usage** — `.dn-panel`:
- - Current plan name + price + renewal date (`relTime`)
- - Usage bars: avatars (X / Y), widgets (X / Y), LLM tokens this period (X / Y), storage GB (X / Y)
- - "Upgrade plan" CTA → `/pricing`
-
-7. **Token earnings** (only if user has launched a token via Pump.fun):
- - Per-token row: ticker · holders · royalties earned · "View token" link
- - Hide section entirely if `/api/tokens?owner=me` is empty
-
-## Files you create
-
-- `pages/dashboard-next/monetize.html`
-- `src/dashboard-next/pages/monetize.js`
-
-Do not modify any other file. This page is dense — consider splitting into per-section helper functions for readability, all in the one `monetize.js` file or under `src/dashboard-next/pages/monetize/` if helpful.
-
-## API endpoints
-
-Read `src/dashboard/dashboard.js` and the existing `public/dashboard/` HTML files (`monetization.html`, `payments.html`, `subscriptions.html`, `billing.html`, `revenue.html`, `withdrawals.html`, `earnings.html`, `tokens.html`) to find the canonical endpoint paths. **Reuse them exactly.**
-
-Likely:
-- `GET /api/billing/revenue` `?from=&to=&granularity=`
-- `GET /api/billing/usage`
-- `GET /api/billing/payments`
-- `GET /api/billing/subscriptions`
-- `GET /api/agent-withdrawals` / `POST /api/agent-withdrawals`
-- `GET /api/tokens?owner=me`
-
-If an endpoint doesn't exist (e.g. unified "available to withdraw"), compute client-side from the data you do have, or surface `—` with a tooltip — don't invent backend.
-
-## Empty / loading / error states
-
-- Skeleton bars on the chart while loading
-- Empty payments: `.dn-empty` "No payments yet. Hook a widget into your site or issue an API key to start earning."
-- Withdrawal modal errors (insufficient balance, bad address): inline error message, keep modal open
-
-## Chart implementation hint
-
-Vanilla SVG. No chart library. Each bar:
-```js
-<rect x="..." y="..." width="..." height="..." fill="var(--nxt-accent)" rx="2"
- data-day="..." data-amount="..." />
-```
-On mouseover, position a `<g>` tooltip absolutely. Keep it under 80 lines.
-
-## Verification
-
-```bash
-node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/monetize /tmp/dn-monetize.png
-```
-Verify:
-- Hero metrics render real values (or `—` with tooltip)
-- Chart bars visible
-- Tables render with real or empty-state content
-- No `NaN`, no `undefined`, no console errors
-
-`npx vite build` passes.
-
-## Commit message
-
-`dashboard-next: monetize page — revenue chart + payments + withdrawals + plan + tokens`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/06-monetize.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/07-account.md b/prompts/dashboard-next/07-account.md
deleted file mode 100644
index e6347ca93..000000000
--- a/prompts/dashboard-next/07-account.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# 07 — Account page
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-Build the Account page at **`/dashboard-next/account`** — consolidates profile, wallets, SNS domains, delegation, action log, and settings.
-
-## Layout
-
-1. **Header** — `.dn-h1` "Account" / `.dn-h1-sub` "Profile, wallets, and the audit trail."
-
-2. **Profile section** — `.dn-panel`:
- - Avatar / initials circle (use `initialsOf(me)`) on the left
- - Display name (editable inline — pencil hover → input → blur saves via `PATCH /api/auth/me`)
- - Handle (`@…`), email (verified chip if `email_verified`)
- - Member since (`relTime(created_at)`) and current plan name (link to `/dashboard-next/monetize`)
- - Sign-out button (`.dn-btn.ghost`) on the right → POST `/api/auth/logout` then redirect to `/`
-
-3. **Wallets section** — `.dn-panel`:
- - Subtitle: "Linked addresses that can claim royalties, pay for subscriptions, or sign as you."
- - Table: chain (chip — `.dn-tag` Solana / Base / Ethereum / Polygon, color-coded) · address (mono, truncated `0x123…abc` with copy-on-click) · linked when (`relTime`) · primary chip (if `is_primary`) · disconnect button
- - "+ Link wallet" → opens chain picker → fires the existing connect flow (read `src/wallet/connect-button.js` and `src/wallet-auth.js` for the sign-in handshake — match it)
- - "Make primary" action on rows that aren't primary
-
-4. **SNS / handle domains** — `.dn-panel`:
- - List the user's SNS (Solana name service) domains owned + which point at this account
- - Each row: domain · status (`.dn-tag.success` "Active" / `.dn-tag.warn` "Pending") · expiry
- - "+ Register a domain" → links to `/vanity-wallet` or the existing SNS flow under `public/dashboard/sns.html` — match that page's behavior
-
-5. **Delegation** — `.dn-panel`:
- - Subtitle: "Let another wallet sign on behalf of one of your agents."
- - Per-agent delegation row: agent name · delegate address · expires · revoke
- - "+ New delegation" → modal with agent dropdown + delegate address + expiry
-
-6. **Action log** — `.dn-panel`:
- - Table of last 50 events: when · category (Auth · Avatar · Widget · Payment · Settings) · description · IP (truncated) · agent string (truncated)
- - "Export full log (CSV)" button → triggers download via `GET /api/audit-log?format=csv` (or the existing path)
- - Pagination: cursor or "Load older"
-
-## Files you create
-
-- `pages/dashboard-next/account.html`
-- `src/dashboard-next/pages/account.js`
-
-Do not modify any other file.
-
-## API endpoints
-
-Read these existing files for the canonical patterns:
-- `public/dashboard/account.html` (profile + sign-out)
-- `public/dashboard/wallets.html` (wallet list/link)
-- `public/dashboard/sns.html` (SNS domains)
-- `public/dashboard/delegation.html` (delegation)
-- `public/dashboard/actions.html` (action log)
-- `src/wallet-auth.js`, `src/wallet/connect-button.js` (wallet linking handshake)
-
-Likely:
-- `GET /api/auth/me`, `PATCH /api/auth/me`, `POST /api/auth/logout`
-- `GET /api/wallets` / `POST /api/wallets` / `DELETE /api/wallets/:id`
-- `GET /api/sns/domains?owner=me`
-- `GET /api/agents/:id/delegations` / `POST /api/agents/:id/delegations` / `DELETE /api/agents/:id/delegations/:delegateId`
-- `GET /api/audit-log?cursor=…&limit=50` / `GET /api/audit-log?format=csv`
-
-## Empty / loading / error states
-
-- No wallets: `.dn-empty` inside the section with "+ Link wallet" CTA
-- No delegations: short prose explainer with CTA
-- Action log empty: `.dn-empty` "Audit log will appear here as you make changes."
-
-## Visual quality bar
-
-- Chain chips color-coded: Solana purple, Base blue, Ethereum gray, Polygon magenta, Optimism red — use semi-transparent accents over the panel background
-- Wallet addresses use `font-family: 'JetBrains Mono', ui-monospace, monospace`, copy-on-click with toast "Copied"
-- "Primary" badge is a small star icon left of the chain chip
-
-## Verification
-
-```bash
-node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/account /tmp/dn-account.png
-```
-Verify:
-- Profile loads with real user data
-- Wallets table renders or empty state
-- Action log shows real events
-- No console errors
-
-`npx vite build` passes.
-
-## Commit message
-
-`dashboard-next: account page — profile + wallets + SNS + delegation + action log`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/07-account.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/08-palette.md b/prompts/dashboard-next/08-palette.md
deleted file mode 100644
index f55455f6b..000000000
--- a/prompts/dashboard-next/08-palette.md
+++ /dev/null
@@ -1,144 +0,0 @@
-# 08 — Command palette (full replace)
-
-**Read `prompts/dashboard-next/_shared.md` first.** Rules, helpers, smoke-test recipe, and commit guidance all live there.
-
-## Your slice
-
-Replace the foundation stub at **`src/dashboard-next/components/palette.js`** with a full-featured command palette. The stub already handles open/close/keyboard and basic filtering — you're upgrading it with fuzzy search, recent history, action handlers beyond navigation, and keyboard accessibility polish.
-
-## Files you own
-
-- `src/dashboard-next/components/palette.js` — **full replace** (the stub comment says "Prompt #8 replaces this")
-
-Do not modify any other file. The shell.js imports this via `mountPaletteBehavior()` — keep that export name.
-
-## What the palette does
-
-### Trigger
-- Keyboard: ⌘K / Ctrl+K (already wired in `topbar.js`)
-- Event: `window.dispatchEvent(new CustomEvent('dn:palette:open'))` (keep this working)
-- Close: Escape, click outside, or selecting an item
-
-### Items (five types)
-
-**1. Navigation** — every route from `nav.js`. Show: icon (from `ICONS`), label, group name right-aligned. Selecting navigates via `location.href`.
-
-**2. Recent pages** — last 6 pages visited, stored in `localStorage` under `dn:recent`. Each visit to a dashboard-next route pushes its `path` + `label` + `timestamp`. Show a "Recent" section above navigation when query is empty. Selecting navigates.
-
-**3. Actions** — hardcoded shortcuts that fire JS, not navigation:
-| Label | Group | Action |
-|---|---|---|
-| "Upload a GLB" | Create | `location.href = '/create'` |
-| "Create from selfie" | Create | `location.href = '/create/selfie'` |
-| "New widget" | Distribute | `location.href = '/widget-studio'` |
-| "Issue API key" | Distribute | fires `window.dispatchEvent(new CustomEvent('dn:action:new-api-key'))` |
-| "Sign out" | Account | `POST /api/auth/logout` then redirect `/` |
-
-**4. Avatar quick-jump** — when the user types more than 2 chars, search their avatars: `GET /api/avatars?q=<query>&limit=5`. Show avatar name + "Open avatar" label. Selecting goes to `/a/<handle>` or `/avatar-page.html?id=<id>`. Show a loading spinner next to the input while the fetch is in flight (debounce 200ms).
-
-**5. Help / docs** — static list of doc links visible when query is empty or matches:
-- "Docs home" → `/docs`
-- "ERC-8004 spec" → `https://eips.ethereum.org/EIPS/eip-8004`
-- "API reference" → `/docs/api`
-
-### Rendering
-
-```
-┌─────────────────────────────────────────────────────────────┐
-│ 🔍 Search or jump to… ⌘K │
-├─────────────────────────────────────────────────────────────┤
-│ RECENT │
-│ 🏠 Overview Create 2m ago │
-│ 💰 Monetize Monetize 18m ago │
-├─────────────────────────────────────────────────────────────┤
-│ NAVIGATION │
-│ 👤 Avatars Create │
-│ 📚 Library Create │
-│ … │
-├─────────────────────────────────────────────────────────────┤
-│ ACTIONS │
-│ ⬆ Upload a GLB Create │
-│ … │
-└─────────────────────────────────────────────────────────────┘
-```
-
-Sections with no matching items are hidden entirely. When query is non-empty, collapse the "Recent" section and merge all matching items (nav + actions + avatar results) into a single flat list sorted by: actions first, then nav, then avatar results.
-
-### Keyboard navigation
-
-- Arrow Up / Down: move the highlight. Wrap around.
-- Enter: activate highlighted item.
-- The highlighted item scrolls into view.
-- Tab: move focus within the input / list (standard browser behavior — don't intercept it).
-
-### Fuzzy matching
-
-Use a simple scorer — no library:
-```js
-function score(query, text) {
- const q = query.toLowerCase();
- const t = text.toLowerCase();
- if (t === q) return 3;
- if (t.startsWith(q)) return 2;
- if (t.includes(q)) return 1;
- // character-walk fuzzy
- let qi = 0;
- for (const c of t) { if (c === q[qi]) qi++; }
- return qi === q.length ? 0.5 : 0;
-}
-```
-Items with `score === 0` are hidden.
-
-### Visual spec
-
-- Overlay: `position:fixed; inset:0; z-index:100; background:rgba(2,3,6,0.6); backdrop-filter:blur(8px)`. Fade in 120ms.
-- Dialog: `width: min(580px, 92vw)`. `background: linear-gradient(180deg, rgba(28,29,39,0.97), rgba(18,19,26,0.97))`. `border: 1px solid var(--nxt-stroke-strong)`. `border-radius: var(--nxt-radius)`. `box-shadow: 0 30px 80px rgba(0,0,0,0.6)`.
-- Input: 16px, `color: var(--nxt-ink)`, no border, transparent bg, `padding: 16px 18px`, border-bottom `1px solid var(--nxt-stroke)`.
-- Section header: `font-size: 10.5px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--nxt-ink-fade); padding: 10px 12px 4px`.
-- Item: `display:flex; align-items:center; gap:12px; padding: 10px 12px; border-radius: 8px; font-size: 13.5px; cursor:pointer`. Highlighted: `background: var(--nxt-accent-soft)`.
-- Icon: 16×16 SVG from `ICONS` dict, or a Unicode glyph fallback. Color `var(--nxt-accent)` when highlighted.
-- Group label right-aligned: `font-size: 11px; color: var(--nxt-ink-fade)`.
-- Recent timestamp right-aligned: `font-size: 11px; color: var(--nxt-ink-fade)`.
-- Loading spinner next to the input: a 12px CSS spinner (`border: 2px solid var(--nxt-stroke); border-top-color: var(--nxt-accent); animation: spin 0.7s linear infinite`) shown only during the avatar fetch.
-
-## Smoke test
-
-Open the page at `http://127.0.0.1:3010/dashboard-next`, press ⌘K (simulate via `p.keyboard.press('Meta+k')`):
-```bash
-cat > scripts/_dn-palette-shot.mjs << 'EOF'
-import { chromium } from 'playwright';
-const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox'] });
-const p = await (await b.newContext({ viewport: { width: 1440, height: 900 } })).newPage();
-const errs = [];
-p.on('pageerror', e => errs.push(e.message.slice(0,200)));
-p.on('console', m => { if (m.type()==='error') errs.push(m.text().slice(0,200)); });
-await p.goto('http://127.0.0.1:3010/dashboard-next', { waitUntil: 'networkidle', timeout: 60000 });
-await p.keyboard.press('Meta+k');
-await p.waitForSelector('#dn-palette[style*="flex"]', { timeout: 5000 });
-await p.screenshot({ path: '/tmp/dn-palette.png' });
-console.log('saved /tmp/dn-palette.png');
-if (errs.length) { errs.forEach(e => console.log('ERR', e)); process.exit(1); }
-await b.close();
-EOF
-node scripts/_dn-palette-shot.mjs
-rm scripts/_dn-palette-shot.mjs
-```
-`Read /tmp/dn-palette.png` — verify the overlay renders, sections visible, no console errors. `npx vite build` passes.
-
-## Commit message
-
-`dashboard-next: command palette — fuzzy search, recent history, action shortcuts, avatar jump`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/08-palette.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/09-activity-drawer.md b/prompts/dashboard-next/09-activity-drawer.md
deleted file mode 100644
index 5738ccfa7..000000000
--- a/prompts/dashboard-next/09-activity-drawer.md
+++ /dev/null
@@ -1,120 +0,0 @@
-# 09 — Activity drawer — live feed
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-Replace the **stub** at [src/dashboard-next/components/drawer.js](src/dashboard-next/components/drawer.js) with a real activity feed: live events streamed from the server (SSE if available, otherwise polling), grouped by day, with filter chips and a relative-time formatter that auto-updates.
-
-## Behaviour spec
-
-- Drawer slot, design, and open/close plumbing already exist. Topbar toggle and ⌘K command (after prompt #08 lands) both fire `dn:drawer:toggled` events.
-- When the drawer is open, fetch and render. When closed, pause the stream (don't fetch in background — wasteful).
-- Persist filter selection in `localStorage` under `dn:drawer:filters`.
-
-## Layout (inside the existing `<aside class="dn-drawer">`)
-
-1. **Header** (already in place — preserve the title + close button structure)
-
-2. **Filter chip row** — under the header, scrollable horizontally if it overflows:
- - All · Widget views · Chat turns · Payments · Avatar edits · Withdrawals · Sign-ins
- - Multi-select (click toggles). Empty selection = All.
-
-3. **Event list** — scrollable, grouped by day:
- ```
- ── Today ─────────────────
- [icon] Widget viewed · wdgt_abc · 2m ago
- [icon] Payment received · $0.50 · 17m ago
- [icon] Chat turn · "What's the weather?" · 28m ago
- ── Yesterday ────────────
- [icon] Avatar updated · Bunny v2 · 1d ago
- ...
- ```
- - Each row shows: icon (per category, color-coded), title, secondary subtitle (when relevant), relative time on the right
- - Click expands the row inline to show full details + a link "Open in viewer" / "Open transcript" / "Open payment" depending on category
- - Use `relTime(iso)` from `api.js`. Re-render `relTime` every 30 seconds for visible rows (use a single `setInterval` while the drawer is open, clear on close)
-
-## Stream / poll strategy
-
-1. **Check for SSE first.** Try opening `new EventSource('/api/events/stream')`. If it connects (one event received within 5s), use that. Subscribe to event types: `widget.view`, `widget.chat_turn`, `payment.received`, `avatar.updated`, `withdrawal.completed`, `auth.signin`.
-
-2. **Fallback to polling.** If SSE not available (404 / connection error), poll `GET /api/events?since=<lastEventTs>&limit=20` every 8 seconds. Use `If-None-Match`-style cursor: pass the latest event id you've seen.
-
-3. **Backoff on error.** If polling fails 3 times in a row, double the interval up to 60s. Surface a tiny "Reconnecting…" chip at the top of the drawer (replace with checkmark when next request succeeds).
-
-4. **Optimistic insertion.** New events get inserted at the top with a 200ms slide-down + brief accent highlight (animate `background` from `--nxt-accent-soft` to transparent).
-
-## Files you create / replace
-
-- **Replace** `src/dashboard-next/components/drawer.js`
-- Optionally add `src/dashboard-next/components/drawer-stream.js` for the SSE/poll logic if it gets large
-
-Do not modify any other file.
-
-## Event icons (inline SVG, ~16px)
-
-| Category | Icon |
-|---|---|
-| `widget.view` | eye |
-| `widget.chat_turn` | speech bubble |
-| `payment.received` | dollar sign |
-| `avatar.updated` | edit pencil |
-| `withdrawal.completed` | arrow-down-circle |
-| `auth.signin` | shield-check |
-| (unknown) | dot |
-
-Use `--nxt-accent` for payments and withdrawals, `--nxt-success` for sign-ins, neutral `--nxt-ink-dim` for the rest.
-
-## Empty / loading / error states
-
-- First load: skeleton rows (4 of them) inside the list
-- No events ever: `.dn-empty` "No activity yet. Embed a widget or issue an API key — events will land here as they happen."
-- Stream / poll failure: tiny "Reconnecting…" chip at the top of the drawer, never a full error blanking the panel
-
-## Endpoints
-
-Inspect `src/dashboard/dashboard.js` and `public/dashboard/actions.html` for the existing event endpoint shape. If the endpoint is named differently (e.g. `/api/audit-log` or `/api/activity`), use that — the API endpoint and event shape are whatever the existing code uses. **Do not invent a new endpoint.** If no event endpoint exists, render only the empty state with a one-line "Live activity is coming soon — wire it up at /api/events when ready."
-
-## Visual quality bar
-
-- Day separators: 11px uppercase `--nxt-ink-fade`, with a 1px stroke line on either side
-- Event rows: 12px vertical padding, hover background `rgba(255,255,255,0.03)`, click to expand
-- Expanded detail block: monospace font for ids, soft accent background card
-
-## Verification
-
-```bash
-node scripts/_dn-shot.mjs "http://127.0.0.1:3010/dashboard-next?drawer=open" /tmp/dn-drawer.png
-```
-The drawer is closed by default — in the screenshot script, before taking the shot, open it:
-```js
-await p.evaluate(() => {
- localStorage.setItem('dn:drawer:open', '1');
-});
-await p.reload({ waitUntil: 'networkidle' });
-await p.waitForSelector('.dn-drawer[aria-label="Activity"]', { state: 'visible' });
-```
-Verify:
-- Drawer renders with filter chips + event rows OR empty state
-- No console errors
-- A `Failed to load: /api/events/stream` 404 is acceptable IF the page then successfully starts polling
-
-`npx vite build` passes.
-
-## Commit message
-
-`dashboard-next: drawer — live activity stream (SSE+poll) with filters and day grouping`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/09-activity-drawer.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/10-polish-pass.md b/prompts/dashboard-next/10-polish-pass.md
deleted file mode 100644
index 376ee3bfd..000000000
--- a/prompts/dashboard-next/10-polish-pass.md
+++ /dev/null
@@ -1,141 +0,0 @@
-# 10 — Polish pass (motion, focus, mobile, perf, a11y)
-
-**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
-
-## Your slice
-
-A cross-cutting polish pass over `/dashboard-next`. This prompt **assumes the other slices have landed**, so you'll be touching shell CSS, JS, and reviewing the existing pages. If a page doesn't exist yet because its prompt hasn't run, skip checks against it — just leave any CSS rules that would apply to it in place (they'll activate when the page lands).
-
-This is the "make it feel premium" pass.
-
-## Scope
-
-### 1. Motion + micro-interactions
-
-Add subtle, performant motion in `public/dashboard-next/shell.css`:
-- Page-load fade-in (200ms ease-out) on `.dn-main-inner` (single transform/opacity, no layout shift)
-- Hover lift on `.dn-panel` (translateY(-1px) + soft accent shadow, 160ms)
-- Active-state press on `.dn-btn` (scale(0.98), 100ms)
-- Sidebar collapse / expand: animate the grid-template-columns change (use the `transition` shorthand on `.dn-shell`)
-- Drawer open / close: 220ms ease-out slide-in from the right
-- Subtle accent pulse on the topbar drawer toggle when the drawer receives a new event (listen for `dn:drawer:new-event` window event — if prompt #9 dispatched it; otherwise add a comment that it'll wire up later)
-
-All motion should respect `prefers-reduced-motion: reduce` — wrap each `@keyframes` / transition rule in a media query that flips it off.
-
-### 2. Focus rings + keyboard nav
-
-- Every interactive element gets a visible focus ring (`outline: 2px solid var(--nxt-accent); outline-offset: 2px;`)
-- Sidebar items are keyboard-navigable in DOM order (no `tabindex="-1"` traps)
-- `Tab` from the input inside the palette doesn't escape the overlay (focus trap — capture and cycle within the palette)
-- `Esc` closes the palette and any open popover / modal
-- Skip-link at the top of the shell: `<a href="#dn-main" class="dn-skip">Skip to content</a>`, hidden until focused, then jumps to the main content slot
-
-### 3. Mobile / responsive QA
-
-The shell.css already has a `@media (max-width: 880px)` block. Verify and tighten:
-- Sidebar collapses into a bottom tab bar at ≤880px (icons + tiny labels, 4–5 items max — pick the most important from each group: Overview · Avatars · Widgets · Money · Account)
-- Topbar shrinks: hide the breadcrumb, keep search button and user chip
-- Drawer becomes a full-screen sheet at ≤640px (slides up from bottom)
-- All page grids reflow to single column at ≤640px
-- Tap targets ≥44px tall
-
-Test at 375px (iPhone SE), 768px (iPad portrait), 1024px (iPad landscape), 1440px (desktop). Take a screenshot at each breakpoint.
-
-### 4. Performance
-
-- `<threews-avatar>` and iframe widgets MUST be lazy-loaded (IntersectionObserver, root margin 200px). If a prompt-2 or prompt-3 page didn't do this, fix it.
-- Verify all images use `loading="lazy"` and `decoding="async"`
-- No blocking webfonts: ensure `font-display: swap` in `public/fonts/fonts.css` (only edit if it's missing — leave existing rules untouched otherwise)
-- Lighthouse-equivalent: open `/dashboard-next` in headless Chrome, capture performance metrics via CDP — log FCP and LCP. Document the numbers in the commit message.
-
-### 5. Accessibility audit
-
-- Every interactive element has an accessible name (`aria-label` or visible text)
-- Color contrast ≥4.5:1 for text (the palette already passes; verify by spot-checking the cards)
-- Screen reader smoke: open `/dashboard-next` and check that the sidebar is announced as a `<nav aria-label="Dashboard sections">`, the main area as `<main>`, the drawer as `<aside aria-label="Activity">` (foundation already does this — verify)
-
-### 6. Empty-state quality pass
-
-Walk through every page and verify the empty state matches the bar:
-- A short title (max 5 words)
-- A one-sentence explainer
-- A single primary CTA
-- Optional secondary CTA only when there's genuinely a second path
-
-## Files you may create / modify
-
-- **Modify** `public/dashboard-next/shell.css` (additions only — don't remove existing rules)
-- **Modify** `src/dashboard-next/shell.js` (add skip-link if missing, focus trap for any modal helpers)
-- **Modify** `src/dashboard-next/components/palette.js` (focus trap — only if prompt #8 didn't already add it)
-- **Modify** individual page files **only** to fix obvious bugs you encounter (e.g. missing `loading="lazy"`); document each modification in the commit body. Do NOT redesign pages.
-
-Do not modify `nav.js`, `api.js`, `tokens.css`.
-
-## Verification
-
-Take screenshots at four widths:
-```bash
-cat > scripts/_dn-shot-mobile.mjs <<'EOF'
-import { chromium } from 'playwright';
-const url = process.argv[2]; const out = process.argv[3]; const w = Number(process.argv[4]);
-const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox'] });
-const p = await (await b.newContext({ viewport: { width: w, height: 900 } })).newPage();
-const errs = [];
-p.on('pageerror', e => errs.push('PAGEERROR ' + e.message.slice(0,200)));
-p.on('console', m => { if (m.type() === 'error') errs.push('[err] ' + m.text().slice(0,200)); });
-await p.goto(url, { waitUntil: 'networkidle', timeout: 60000 });
-await p.waitForSelector('.dn-shell', { timeout: 20000 });
-await p.screenshot({ path: out, fullPage: true });
-console.log('saved', out);
-if (errs.length) { console.log('errors:'); for (const e of errs) console.log(' ' + e); process.exit(1); }
-await b.close();
-EOF
-
-for w in 375 768 1024 1440; do
- node scripts/_dn-shot-mobile.mjs http://127.0.0.1:3010/dashboard-next /tmp/dn-polish-$w.png $w
-done
-rm scripts/_dn-shot-mobile.mjs
-```
-Open all four. Verify:
-- 375px: bottom tab bar, single-column content, all tap targets reachable
-- 768px: bottom tab bar still, content uses available width
-- 1024px: sidebar visible, content in 2-column grid where appropriate
-- 1440px: full three-column shell (if drawer is open) — drawer can be opened in the script via `localStorage.setItem('dn:drawer:open', '1')` before navigation
-
-Lighthouse-equivalent perf:
-```js
-// in headless playwright, after page load:
-const metrics = await p.evaluate(() => JSON.stringify(performance.getEntriesByType('navigation')));
-console.log('nav:', metrics);
-const lcp = await p.evaluate(() => new Promise(r => new PerformanceObserver(l => r(l.getEntries().pop()?.startTime ?? null)).observe({ type: 'largest-contentful-paint', buffered: true })));
-console.log('lcp:', lcp);
-```
-Document FCP / LCP in the commit body.
-
-`npx vite build` and `npx vitest run` must both pass.
-
-## Commit message
-
-```
-dashboard-next: polish pass — motion, focus rings, mobile QA, perf, a11y
-
-- Motion: page-load fade-in, panel hover lift, button press, drawer slide
-- Focus: visible rings, skip-link, palette focus trap
-- Mobile: bottom-tab nav ≤880px, full-sheet drawer ≤640px
-- Perf: lazy 3D + iframes (LCP <Xms / FCP <Yms on /dashboard-next)
-- A11y: aria labels, contrast pass
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/10-polish-pass.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/dashboard-next/11-mobile-nav.md b/prompts/dashboard-next/11-mobile-nav.md
deleted file mode 100644
index 85df999d6..000000000
--- a/prompts/dashboard-next/11-mobile-nav.md
+++ /dev/null
@@ -1,310 +0,0 @@
-# 09 — Mobile bottom navigation
-
-**Read `prompts/dashboard-next/_shared.md` first.** Rules, helpers, smoke-test recipe, and commit guidance all live there.
-
-## Your slice
-
-The shell CSS already converts the sidebar to a bottom nav bar at ≤880px (the rail becomes `position:fixed; bottom:0; height:64px; flex-direction:row`). But it spills all 7 nav items into a horizontal scroll which is cramped. This prompt upgrades the mobile nav to show exactly **5 items max** in the bar with a "More" item that opens a bottom sheet for the rest.
-
-## Files you own
-
-- `public/dashboard-next/shell.css` — add/replace only the `@media (max-width: 880px)` block (lines ~413–455). Do not change anything above it.
-- `src/dashboard-next/components/sidebar.js` — add mobile-specific rendering logic (a `renderMobileNav()` helper and a `mountMobileNavBehavior(shellEl)` function). Do not change `renderSidebar` or `mountSidebarBehavior`.
-- `src/dashboard-next/shell.js` — call `renderMobileNav()` and `mountMobileNavBehavior()` on the shell element, conditional on viewport width. Do this **after** the existing `mountSidebarBehavior` call.
-
-Do not modify any other file. In particular: do not change `tokens.css`, `nav.js`, `api.js`, or any page JS file.
-
-## Behaviour
-
-### Bottom bar (≤880px)
-
-Show the **first 4 nav items** from `NAV` plus a "More" item as the 5th slot:
-
-| Slot | Item |
-|---|---|
-| 1 | Overview (home icon) |
-| 2 | Avatars (avatar icon) |
-| 3 | Widgets (widget icon) |
-| 4 | Monetize (coin icon) |
-| 5 | "More" (three-dots icon, see SVG below) |
-
-Each tab: icon 22×22, label 10.5px below. Active tab: `background: var(--nxt-accent-soft)`, icon and label in `var(--nxt-accent)`. Tap area min 56px wide.
-
-"More" icon SVG:
-```html
-<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><circle cx="4" cy="10" r="1.2" fill="currentColor" stroke="none"/><circle cx="10" cy="10" r="1.2" fill="currentColor" stroke="none"/><circle cx="16" cy="10" r="1.2" fill="currentColor" stroke="none"/></svg>
-```
-
-### "More" bottom sheet
-
-Tapping "More" slides up a bottom sheet (a `<div>` that translates from `translateY(100%)` to `translateY(0)` over 240ms `cubic-bezier(0.2,0.8,0.2,1)`), overlaying a semi-transparent backdrop.
-
-The sheet contains:
-- A drag handle bar (32×4px pill, centered, `background: var(--nxt-stroke-strong)`)
-- Remaining nav items: Library, API & Embed, Account — same row format as the sidebar items (icon + label)
-- A divider
-- "Collapse sidebar" is hidden on mobile; replace with "Settings" → `/settings`
-- "⌘K Command palette" button → fires `window.dispatchEvent(new CustomEvent('dn:palette:open'))`
-
-Close the sheet on: backdrop click, swipe-down drag ≥60px, Escape key.
-
-### Swipe-to-close
-
-Track `touchstart` / `touchmove` / `touchend` on the sheet. If the user drags down by ≥60px before lifting, animate the sheet back down and remove it.
-
-### No horizontal scroll
-
-The existing mobile CSS uses `overflow-x: auto` on `.dn-rail-scroll`. Replace this so the bar never scrolls — it always shows exactly 5 fixed-width slots.
-
-## CSS changes (inside `@media (max-width: 880px)`)
-
-Replace the existing block with:
-
-```css
-@media (max-width: 880px) {
- .dn-shell,
- .dn-shell[data-rail-collapsed='true'] {
- grid-template-columns: 1fr;
- grid-template-rows: var(--dn-topbar-h) 1fr 64px;
- grid-template-areas: 'topbar' 'main' 'rail';
- }
- .dn-rail {
- flex-direction: row;
- position: fixed;
- bottom: 0; left: 0; right: 0;
- height: 64px;
- border-right: none;
- border-top: 1px solid var(--nxt-stroke);
- background: var(--nxt-glass-strong);
- backdrop-filter: blur(16px);
- -webkit-backdrop-filter: blur(16px);
- z-index: 20;
- }
- .dn-rail-head, .dn-rail-foot, .dn-rail-group-label { display: none; }
- .dn-rail-scroll {
- display: grid;
- grid-template-columns: repeat(5, 1fr);
- padding: 0;
- gap: 0;
- overflow: hidden;
- }
- /* hide all nav items except the 5 mobile slots injected by JS */
- .dn-rail-group { display: none; }
- .dn-rail-mobile-slot {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 3px;
- font-size: 10.5px;
- color: var(--nxt-ink-dim);
- padding: 6px 4px;
- cursor: pointer;
- border: none;
- background: transparent;
- font-family: inherit;
- text-decoration: none;
- transition: color 0.12s, background 0.12s;
- min-width: 0;
- }
- .dn-rail-mobile-slot:hover,
- .dn-rail-mobile-slot[aria-current='page'],
- .dn-rail-mobile-slot.active {
- color: var(--nxt-accent);
- background: var(--nxt-accent-soft);
- }
- .dn-rail-mobile-slot svg {
- width: 22px; height: 22px; flex-shrink: 0;
- }
- .dn-rail-mobile-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%; }
- /* bottom sheet */
- .dn-mobile-sheet-backdrop {
- position: fixed; inset: 0; z-index: 40;
- background: rgba(0,0,0,0.5);
- backdrop-filter: blur(4px);
- -webkit-backdrop-filter: blur(4px);
- }
- .dn-mobile-sheet {
- position: fixed; bottom: 64px; left: 0; right: 0; z-index: 41;
- background: var(--nxt-bg-1);
- border-top: 1px solid var(--nxt-stroke-strong);
- border-radius: 18px 18px 0 0;
- padding: 8px 0 env(safe-area-inset-bottom,0) 0;
- transform: translateY(100%);
- transition: transform 240ms cubic-bezier(0.2,0.8,0.2,1);
- touch-action: none;
- }
- .dn-mobile-sheet.open { transform: translateY(0); }
- .dn-mobile-sheet-handle {
- width: 32px; height: 4px;
- background: var(--nxt-stroke-strong);
- border-radius: 99px;
- margin: 6px auto 12px;
- }
- .dn-mobile-sheet-item {
- display: flex; align-items: center; gap: 14px;
- padding: 13px 20px;
- color: var(--nxt-ink-dim);
- font-size: 14.5px;
- cursor: pointer;
- border: none; background: transparent; font-family: inherit;
- text-decoration: none; width: 100%; text-align: left;
- transition: color 0.12s, background 0.12s;
- }
- .dn-mobile-sheet-item:hover,
- .dn-mobile-sheet-item[aria-current='page'] {
- color: var(--nxt-ink); background: rgba(255,255,255,0.04);
- }
- .dn-mobile-sheet-item svg { width: 20px; height: 20px; color: var(--nxt-ink-fade); flex-shrink: 0; }
- .dn-mobile-sheet-divider {
- height: 1px; background: var(--nxt-stroke); margin: 6px 0;
- }
- .dn-main-inner { padding: 18px 16px 80px; } /* extra bottom padding so content isn't under the nav */
-}
-```
-
-## JS changes in `sidebar.js`
-
-Add at the bottom of the file (do not alter existing functions):
-
-```js
-const MOBILE_NAV_ROUTES = ['/dashboard-next', '/dashboard-next/avatars', '/dashboard-next/widgets', '/dashboard-next/monetize'];
-const SHEET_ROUTES = NAV.filter(r => !MOBILE_NAV_ROUTES.includes(r.path));
-
-export function renderMobileNav(pathname) {
- const here = currentRoute(pathname)?.path;
- const slots = MOBILE_NAV_ROUTES.map(path => {
- const r = NAV.find(n => n.path === path);
- if (!r) return '';
- const active = r.path === here ? ' aria-current="page"' : '';
- return `<a href="${esc(r.path)}" class="dn-rail-mobile-slot"${active}>
- <span aria-hidden="true">${ICONS[r.icon] || ''}</span>
- <span class="dn-rail-mobile-label">${esc(r.label)}</span>
- </a>`;
- }).join('');
- const moreActive = SHEET_ROUTES.some(r => r.path === here) ? ' active' : '';
- const moreBtn = `<button type="button" class="dn-rail-mobile-slot${moreActive}" data-action="mobile-more" aria-haspopup="true">
- <span aria-hidden="true"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><circle cx="4" cy="10" r="1.2" fill="currentColor" stroke="none"/><circle cx="10" cy="10" r="1.2" fill="currentColor" stroke="none"/><circle cx="16" cy="10" r="1.2" fill="currentColor" stroke="none"/></svg></span>
- <span class="dn-rail-mobile-label">More</span>
- </button>`;
- return `<div class="dn-rail-scroll" role="tablist" aria-label="Main navigation">${slots}${moreBtn}</div>`;
-}
-
-export function mountMobileNavBehavior(shellEl, pathname) {
- if (window.innerWidth > 880) return;
- // Replace the existing rail scroll with the 5-slot mobile bar
- const rail = shellEl.querySelector('.dn-rail');
- if (!rail) return;
- rail.innerHTML = `
- <div class="dn-rail-head" style="display:none"></div>
- ${renderMobileNav(pathname)}
- <div class="dn-rail-foot" style="display:none"></div>
- `;
- rail.querySelector('[data-action="mobile-more"]')?.addEventListener('click', openSheet);
-}
-
-function openSheet() {
- const here = currentRoute(location.pathname)?.path;
- const backdrop = document.createElement('div');
- backdrop.className = 'dn-mobile-sheet-backdrop';
- const sheet = document.createElement('div');
- sheet.className = 'dn-mobile-sheet';
- sheet.innerHTML = `
- <div class="dn-mobile-sheet-handle" aria-hidden="true"></div>
- ${SHEET_ROUTES.map(r => `<a href="${esc(r.path)}" class="dn-mobile-sheet-item"${r.path===here?' aria-current="page"':''}>
- <span aria-hidden="true">${ICONS[r.icon]||''}</span>
- <span>${esc(r.label)}</span>
- </a>`).join('')}
- <div class="dn-mobile-sheet-divider"></div>
- <a href="/settings" class="dn-mobile-sheet-item">
- <span aria-hidden="true"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="10" cy="10" r="2.5"/><path d="M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4"/></svg></span>
- <span>Settings</span>
- </a>
- <button type="button" class="dn-mobile-sheet-item" onclick="window.dispatchEvent(new CustomEvent('dn:palette:open'))">
- <span aria-hidden="true"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><circle cx="8.5" cy="8.5" r="5"/><path d="M15 15l2.5 2.5"/></svg></span>
- <span>Command palette ⌘K</span>
- </button>
- `;
- document.body.appendChild(backdrop);
- document.body.appendChild(sheet);
- requestAnimationFrame(() => sheet.classList.add('open'));
- const close = () => {
- sheet.classList.remove('open');
- backdrop.style.opacity = '0';
- setTimeout(() => { sheet.remove(); backdrop.remove(); }, 260);
- };
- backdrop.addEventListener('click', close);
- window.addEventListener('keydown', function onKey(e) { if (e.key === 'Escape') { close(); window.removeEventListener('keydown', onKey); }});
- // Swipe-to-close
- let startY = 0, currentY = 0;
- sheet.addEventListener('touchstart', e => { startY = e.touches[0].clientY; }, { passive: true });
- sheet.addEventListener('touchmove', e => {
- currentY = e.touches[0].clientY;
- const dy = currentY - startY;
- if (dy > 0) sheet.style.transform = `translateY(${dy}px)`;
- }, { passive: true });
- sheet.addEventListener('touchend', () => {
- if (currentY - startY >= 60) { close(); }
- else { sheet.style.transform = ''; }
- startY = 0; currentY = 0;
- });
-}
-```
-
-## JS changes in `shell.js`
-
-After the existing `mountSidebarBehavior(shell)` call, add:
-
-```js
-import { mountMobileNavBehavior } from './components/sidebar.js';
-// …
-mountMobileNavBehavior(shell, location.pathname);
-```
-
-The import already exists at the top of `shell.js` — just add `mountMobileNavBehavior` to the named import list.
-
-## Smoke test
-
-Resize the Playwright viewport to 375×812 (iPhone 14 size) and take a screenshot:
-```bash
-cat > scripts/_dn-mobile-shot.mjs << 'EOF'
-import { chromium } from 'playwright';
-const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox'] });
-const p = await (await b.newContext({ viewport: { width: 375, height: 812 }, isMobile: true })).newPage();
-const errs = [];
-p.on('pageerror', e => errs.push(e.message.slice(0,200)));
-p.on('console', m => { if (m.type()==='error') errs.push(m.text().slice(0,200)); });
-await p.goto('http://127.0.0.1:3010/dashboard-next', { waitUntil: 'networkidle', timeout: 60000 });
-await p.screenshot({ path: '/tmp/dn-mobile.png' });
-await p.click('[data-action="mobile-more"]');
-await p.waitForSelector('.dn-mobile-sheet.open', { timeout: 3000 });
-await p.screenshot({ path: '/tmp/dn-mobile-sheet.png' });
-if (errs.length) { errs.forEach(e => console.log('ERR', e)); process.exit(1); }
-await b.close();
-EOF
-node scripts/_dn-mobile-shot.mjs
-rm scripts/_dn-mobile-shot.mjs
-```
-`Read /tmp/dn-mobile.png` and `/tmp/dn-mobile-sheet.png`. Verify:
-- Bottom bar shows exactly 5 slots, no horizontal scroll
-- Sheet slides up when "More" is tapped
-- No console errors
-`npx vite build` passes.
-
-## Commit message
-
-`dashboard-next: mobile nav — 5-slot bottom bar + slide-up sheet for overflow items`
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/dashboard-next/11-mobile-nav.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-backend-api-set-prices.md b/prompts/monetization/03-backend-api-set-prices.md
deleted file mode 100644
index 86d976cc5..000000000
--- a/prompts/monetization/03-backend-api-set-prices.md
+++ /dev/null
@@ -1,62 +0,0 @@
----
-status: not-started
----
-
-# Prompt 3: Backend API to Set Skill Prices
-
-## Objective
-Implement a secure backend API endpoint that allows agent creators to save and update the prices for their skills.
-
-## Explanation
-This API will receive the pricing information from the creator UI and persist it in the database. It's crucial that this endpoint is secure and only allows the agent's owner to modify the prices.
-
-## Instructions
-1. **Create a New API Endpoint:**
- * Create a new API endpoint, for example, `POST /api/agents/:id/skills/prices`.
- * This endpoint should be protected and require authentication. Ensure that the authenticated user is the owner of the agent.
-
-2. **Implement the Logic:**
- * The endpoint will receive a payload containing the skill prices, like ` { "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.
- * Validate the input data to ensure it's in the correct format.
- * In the database, update or insert the new prices in the `agent_skill_prices` table, associating them with the agent and the specific skills.
-
-## Code Example (Backend - Express.js like)
-
-```javascript
-// POST /api/agents/:id/skills/prices
-router.post('/:id/skills/prices', async (req, res) => {
- const { id } = req.params;
- const { prices } = req.body;
- const userId = req.session.userId;
-
- // 1. Authenticate and authorize the user
- const agent = await db.getAgentById(id);
- if (!agent || agent.owner_id !== userId) {
- return res.status(403).json({ error: 'Forbidden' });
- }
-
- // 2. Validate the pricing data
- if (!prices) {
- return res.status(400).json({ error: 'Invalid input' });
- }
-
- // 3. Save the prices to the database
- await db.saveSkillPrices(id, prices);
-
- res.status(200).json({ success: true });
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-backend-api-set-prices.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-backend-api-set-skill-prices.md b/prompts/monetization/03-backend-api-set-skill-prices.md
deleted file mode 100644
index 567fb901e..000000000
--- a/prompts/monetization/03-backend-api-set-skill-prices.md
+++ /dev/null
@@ -1,111 +0,0 @@
----
-status: not-started
----
-
-# Prompt 3: Backend - API to Set/Update Skill Prices
-
-## Objective
-Create a secure backend API endpoint that allows an agent's creator to set or update the price of their skills.
-
-## Explanation
-With the database table in place, we now need a way for creators to manage their skill prices programmatically. This requires an authenticated API endpoint that accepts pricing information and updates the `agent_skill_prices` table. The endpoint must verify that the user making the request is the owner of the agent.
-
-## Instructions
-1. **Create the API Endpoint File:**
- * Create a new file in the API directory, for example, `api/agents/skills.js`. This can be a Vercel serverless function.
- * This endpoint should handle `POST` or `PUT` requests to a path like `/api/agents/[agentId]/skills/prices`.
-
-2. **Implement Authentication and Authorization:**
- * The endpoint must be authenticated. Use your existing authentication middleware (e.g., checking for a valid JWT or session cookie) to get the `user_id` of the requester.
- * Before making any database changes, verify that the `user_id` owns the `agentId` specified in the URL. You'll need to query the `agent_identities` table. If they are not the owner, return a `403 Forbidden` error.
-
-3. **Handle the Request Body:**
- * The request body should contain the skill's name, the price amount (in lamports), and the currency mint address.
- * Example body: `{ "skill_name": "Jupiter Swapper", "amount": 1000000, "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" }`
- * Validate the input. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana public key format.
-
-4. **Implement the Database Logic:**
- * Use an `INSERT ... ON CONFLICT` (UPSERT) statement to either create a new price entry or update an existing one for the given `agent_id` and `skill_name`.
- * The `ON CONFLICT (agent_id, skill_name) DO UPDATE` clause makes the logic simple and atomic.
-
-5. **Return a Response:**
- * If successful, return a `200 OK` or `201 Created` status with the newly created/updated pricing information.
- * Return appropriate error codes for bad input (`400`), unauthorized access (`403`), or server errors (`500`).
-
-## Code Example (Vercel Serverless Function - `api/agents/skills.js`)
-
-```javascript
-import { cors, json, method, wrap } from '../_lib/http.js';
-import { getAuth } from '../_lib/auth.js';
-import { sql } from '../_lib/db.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res)) return;
- if (!method(req, res, ['POST'])) return;
-
- // 1. Authentication
- const auth = await getAuth(req);
- if (!auth.userId) {
- return json(res, 401, { error: 'Authentication required' });
- }
-
- // 2. Extract agentId and validation
- const { agentId } = req.query;
- if (!agentId) {
- return json(res, 400, { error: 'Agent ID is required' });
- }
-
- const [agent] = await sql`
- SELECT user_id FROM agent_identities WHERE id = ${agentId}
- `;
-
- if (!agent) {
- return json(res, 404, { error: 'Agent not found' });
- }
-
- // 3. Authorization
- if (agent.user_id !== auth.userId) {
- return json(res, 403, { error: 'You do not own this agent' });
- }
-
- // 4. Input validation
- const { skill_name, amount, currency_mint } = req.body;
- if (!skill_name || typeof amount !== 'number' || amount < 0 || !currency_mint) {
- return json(res, 400, { error: 'Invalid input: skill_name, amount, and currency_mint are required.' });
- }
-
- // 5. Database UPSERT
- try {
- const [price] = await sql`
- INSERT INTO agent_skill_prices
- (agent_id, skill_name, amount, currency_mint)
- VALUES
- (${agentId}, ${skill_name}, ${amount}, ${currency_mint})
- ON CONFLICT (agent_id, skill_name)
- DO UPDATE SET
- amount = EXCLUDED.amount,
- currency_mint = EXCLUDED.currency_mint,
- updated_at = NOW()
- RETURNING *
- `;
- return json(res, 200, { price });
- } catch (error) {
- console.error('Failed to set skill price:', error);
- return json(res, 500, { error: 'Internal Server Error' });
- }
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-backend-api-set-skill-prices.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-creator-api-set-skill-price.md b/prompts/monetization/03-creator-api-set-skill-price.md
deleted file mode 100644
index c9d88db88..000000000
--- a/prompts/monetization/03-creator-api-set-skill-price.md
+++ /dev/null
@@ -1,109 +0,0 @@
----
-status: not-started
-completed_at: null
----
-# Prompt 3: Creator API to Set/Update Skill Prices
-
-## Objective
-Create a secure backend API endpoint that allows agent creators to set, update, or remove the price for their agent's skills.
-
-## Explanation
-To enable a creator-driven economy, we need to provide the tools for creators to manage their offerings. This prompt focuses on building the backend endpoint that will power the UI for pricing skills in the Creator Dashboard. The endpoint must be secure, ensuring only the agent's owner can modify prices.
-
-## Instructions
-1. **Define the API Endpoint:**
- * Create a new API route: `POST /api/creator/agents/:agentId/skills/price`.
- * This endpoint will handle creating, updating, and deleting skill prices.
-
-2. **Implement Authentication and Authorization:**
- * The endpoint must be protected. Ensure you have middleware that verifies the user is authenticated (e.g., checks for a valid session cookie or JWT).
- * Implement an authorization check. Before processing the request, verify that the authenticated user is the owner of the `agentId` specified in the URL. If not, return a `403 Forbidden` error.
-
-3. **Handle the Request Body:**
- * The request body should contain:
- * `skill_name`: The name of the skill to price.
- * `amount` (optional): The price in the smallest currency unit. If `null` or `0`, it implies the skill is being made free (price is being removed).
- * `currency_mint` (optional): The SPL token mint address. Required if `amount` is greater than 0.
-
-4. **Implement Database Logic:**
- * **If `amount` is positive:**
- * Use an `UPSERT` (or `INSERT ... ON CONFLICT UPDATE`) operation on the `agent_skill_prices` table.
- * Match on the composite primary key `(agent_id, skill_name)`.
- * If a record exists, `UPDATE` the `amount` and `currency_mint`.
- * If no record exists, `INSERT` a new row.
- * **If `amount` is `null`, `0`, or not provided:**
- * `DELETE` the corresponding row from the `agent_skill_prices` table for that `agent_id` and `skill_name`.
-
-5. **Return a Response:**
- * On success, return a `200 OK` or `204 No Content` response.
- * On validation failure (e.g., missing `currency_mint` for a paid skill), return a `400 Bad Request`.
-
-## Code Example (Backend API Handler)
-
-```javascript
-// Example using Express.js and a hypothetical 'db' client
-
-// Assume 'authMiddleware' and 'agentOwnershipMiddleware' exist and are applied to this route.
-app.post('/api/creator/agents/:agentId/skills/price', async (req, res) => {
- const { agentId } = req.params;
- const { skill_name, amount, currency_mint } = req.body;
-
- // Basic validation
- if (!skill_name) {
- return res.status(400).json({ error: 'skill_name is required.' });
- }
-
- const numericAmount = amount ? BigInt(amount) : 0n;
-
- if (numericAmount > 0n && !currency_mint) {
- return res.status(400).json({ error: 'currency_mint is required for paid skills.' });
- }
-
- try {
- if (numericAmount > 0n) {
- // Upsert logic
- const query = `
- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)
- VALUES ($1, $2, $3, $4)
- ON CONFLICT (agent_id, skill_name)
- DO UPDATE SET amount = $3, currency_mint = $4, updated_at = CURRENT_TIMESTAMP;
- `;
- await db.query(query, [agentId, skill_name, numericAmount, currency_mint]);
- } else {
- // Delete logic (make skill free)
- const query = `
- DELETE FROM agent_skill_prices
- WHERE agent_id = $1 AND skill_name = $2;
- `;
- await db.query(query, [agentId, skill_name]);
- }
-
- res.status(204).send();
-
- } catch (error) {
- console.error('Failed to update skill price:', error);
- res.status(500).json({ error: 'An internal error occurred.' });
- }
-});
-```
-
-## Definition of Done
-- A new `POST` endpoint at `/api/creator/agents/:agentId/skills/price` is created and functional.
-- The endpoint correctly requires authentication.
-- The endpoint correctly verifies that the user owns the agent before making changes.
-- The endpoint can successfully create, update, and delete entries in the `agent_skill_prices` table based on the request body.
-- Appropriate error responses (`400`, `403`, `500`) are returned in failure cases.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-creator-api-set-skill-price.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-implement-solana-wallet-connection.md b/prompts/monetization/03-implement-solana-wallet-connection.md
deleted file mode 100644
index 27de4c0c1..000000000
--- a/prompts/monetization/03-implement-solana-wallet-connection.md
+++ /dev/null
@@ -1,103 +0,0 @@
-# Prompt 3: Implement Solana Wallet Connection
-
-## Status
-- [ ] Not Started
-
-## Objective
-Implement the core logic for connecting to a user's Solana wallet using a standard wallet adapter library like `@solana/wallet-adapter-base` and `@solana/wallet-adapter-wallets`.
-
-## Explanation
-This prompt builds on the previous one by implementing the functionality behind the "Connect Wallet" button. We will use the Solana Wallet Adapter libraries to present the user with a list of installed wallets (e.g., Phantom, Solflare) and manage the connection state.
-
-## Instructions
-1. **Install Dependencies:**
- * Add the necessary Solana wallet adapter libraries to your project's `package.json` and install them.
- * You'll typically need `@solana/web3.js`, `@solana/wallet-adapter-base`, `@solana/wallet-adapter-wallets`, and specific wallet adapters you wish to support.
-
-2. **Update the Wallet Module (`src/wallet.js`):**
- * Import the wallet adapter classes.
- * Instantiate the wallets you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).
- * Implement the `onConnectWallet` function to trigger the wallet adapter's connect flow. This will typically open a modal for the user to select their wallet.
- * Listen for changes in the wallet's connection status and update the UI accordingly using the `updateWalletState` function created previously.
-
-## Code Example (Terminal - Installation)
-```bash
-npm install @solana/web3.js @solana/wallet-adapter-base @solana/wallet-adapter-wallets @solana/wallet-adapter-phantom
-```
-
-## Code Example (src/wallet.js)
-```javascript
-// src/wallet.js
-import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';
-import { Connection, PublicKey } from '@solana/web3.js';
-
-let connectedWalletAddress = null;
-
-// Initialize the wallet adapter
-const wallet = new PhantomWalletAdapter();
-
-// Listen for connection events
-wallet.on('connect', (publicKey) => {
- connectedWalletAddress = publicKey.toBase58();
- console.log(`Wallet connected: ${connectedWalletAddress}`);
- updateWalletState(connectedWalletAddress);
-});
-
-wallet.on('disconnect', () => {
- console.log('Wallet disconnected');
- connectedWalletAddress = null;
- updateWalletState(null);
-});
-
-async function onConnectWallet() {
- if (!wallet.connected) {
- try {
- await wallet.connect();
- } catch (error) {
- console.error('Wallet connection failed:', error);
- }
- }
-}
-
-export function updateWalletState(address) {
- const btn = document.getElementById('connect-wallet-btn');
- if (address) {
- btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;
- } else {
- btn.textContent = 'Connect Wallet';
- }
-}
-
-export function initWalletButton() {
- const btn = document.getElementById('connect-wallet-btn');
- if (btn) {
- btn.addEventListener('click', onConnectWallet);
- }
- // Auto-connect if wallet is already connected
- if (wallet.autoConnect) {
- wallet.autoConnect();
- }
-}
-
-export function getConnectedWallet() {
- return wallet.connected ? wallet : null;
-}
-
-export function getConnectedWalletAddress() {
- return connectedWalletAddress;
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-implement-solana-wallet-connection.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-purchase-flow-ui.md b/prompts/monetization/03-purchase-flow-ui.md
deleted file mode 100644
index 9612be609..000000000
--- a/prompts/monetization/03-purchase-flow-ui.md
+++ /dev/null
@@ -1,77 +0,0 @@
-# Prompt 3: Implement Purchase Flow UI Modal
-
-## Objective
-Create a modal dialog that appears when a user clicks the "Unlock" button for a paid skill, presenting the details of the purchase and asking for confirmation.
-
-## Explanation
-A modal is a standard and effective way to handle a confirmation flow without navigating the user away from the current page. This modal will serve as the main interface for the skill purchase process, containing all necessary information for the user to make a decision.
-
-## Instructions
-1. **Create Modal HTML:**
- * In `marketplace.html`, add the HTML structure for a hidden modal.
- * The modal should include a title, a section to display the skill name and price, a "Confirm Purchase" button, and a "Cancel" button or close icon.
-
-2. **Implement Modal Logic (`src/marketplace.js`):**
- * Create functions to `showModal()` and `hideModal()`.
- * Modify the event listener for the `.purchase-btn` clicks.
- * When a purchase button is clicked, extract the skill name and price from the agent data.
- * Populate the modal with the specific skill's details.
- * Call `showModal()` to display it.
- * Add event listeners to the "Cancel" and "Confirm Purchase" buttons within the modal.
-
-## Code Example (HTML - `marketplace.html`)
-```html
-<!-- Add this inside the <body> tag -->
-<div id="purchase-modal" class="modal-hidden">
- <div class="modal-content">
- <span class="close-button">&times;</span>
- <h2>Unlock Skill</h2>
- <p>You are about to purchase:</p>
- <p><strong>Skill:</strong> <span id="modal-skill-name"></span></p>
- <p><strong>Price:</strong> <span id="modal-skill-price"></span></p>
- <button id="modal-confirm-purchase">Confirm Purchase</button>
- </div>
-</div>
-```
-
-## Code Example (JavaScript - `src/marketplace.js`)
-```javascript
-// Add event listener for purchase buttons (delegated)
-document.addEventListener('click', (e) => {
- if (e.target.matches('.purchase-btn')) {
- const skillName = e.target.dataset.skillName;
- const agent = getCurrentAgentData(); // Assume this function gets the current agent's full data
- const price = agent.skill_prices[skillName];
-
- // Populate and show the modal
- document.getElementById('modal-skill-name').textContent = skillName;
- document.getElementById('modal-skill-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
- document.getElementById('purchase-modal').classList.remove('modal-hidden');
- }
-});
-
-// Logic to hide modal
-document.querySelector('.close-button').addEventListener('click', () => {
- document.getElementById('purchase-modal').classList.add('modal-hidden');
-});
-```
-
-## CSS Example (`/marketplace.css`)
-```css
-.modal-hidden { display: none; }
-/* Add styles for modal backdrop, content, etc. */
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-purchase-flow-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-purchase-modal-ui.md b/prompts/monetization/03-purchase-modal-ui.md
deleted file mode 100644
index 5db669d04..000000000
--- a/prompts/monetization/03-purchase-modal-ui.md
+++ /dev/null
@@ -1,94 +0,0 @@
----
-status: not-started
----
-
-# Prompt 3: Purchase Modal UI
-
-## Objective
-Create a reusable modal component for the skill purchase flow, which will serve as the container for payment steps.
-
-## Explanation
-When a user clicks the "Purchase" button, we shouldn't immediately trigger a wallet transaction. Instead, we should present them with a clear, focused modal window that confirms their intent and guides them through the payment process. This modal will initially show the skill details and price, and will later host the wallet connection and payment confirmation steps.
-
-## Instructions
-- [ ] **Create the Modal HTML Structure:**
- - [ ] Add a generic modal structure to `marketplace.html`. It should be hidden by default (`display: none`).
- - [ ] The modal should have a backdrop, a main content area, a title, a close button, and a section for dynamic content.
-
-- [ ] **Create the Modal CSS:**
- - [ ] In `marketplace.css`, add styles for the modal, backdrop, and content area.
- - [ ] Ensure it's centered, has a reasonable size, and is styled consistently with the rest of the application.
-
-- [ ] **Implement Modal Logic:**
- - [ ] In `src/marketplace.js`, add functions to `showModal(title, content)` and `hideModal()`.
- - [ ] `showModal` should populate the modal's title and content sections and make it visible.
- - [ ] `hideModal` should hide the modal. The close button and backdrop should trigger this function.
- - [ ] Add an event listener to the `d-skills` container that listens for clicks on `.purchase-btn` buttons.
- - [ ] When a purchase button is clicked, get the skill name from the `data-skill-name` attribute, then call `showModal` with the appropriate details to confirm the purchase.
-
-## HTML Example (`marketplace.html`)
-
-```html
-<!-- Add this somewhere in your main container -->
-<div id="purchase-modal" class="modal-backdrop" style="display: none;">
- <div class="modal-content">
- <div class="modal-header">
- <h2 id="modal-title"></h2>
- <button id="modal-close" class="modal-close-btn">&times;</button>
- </div>
- <div id="modal-body"></div>
- </div>
-</div>
-```
-
-## JavaScript Example (`src/marketplace.js`)
-
-```javascript
-// Function to show the modal
-function showModal(title, content) {
- $('modal-title').textContent = title;
- $('modal-body').innerHTML = content;
- $('purchase-modal').style.display = 'flex';
-}
-
-// Function to hide the modal
-function hideModal() {
- $('purchase-modal').style.display = 'none';
-}
-
-// Event listener for closing the modal
-$('modal-close').addEventListener('click', hideModal);
-$('purchase-modal').addEventListener('click', (e) => {
- if (e.target.id === 'purchase-modal') {
- hideModal();
- }
-});
-
-// Event listener for the purchase buttons
-$('d-skills').addEventListener('click', (e) => {
- if (e.target.classList.contains('purchase-btn')) {
- const skillName = e.target.dataset.skillName;
- // Find the agent and skill details to show in the modal
- // For now, a simple confirmation:
- showModal(
- `Purchase Skill: ${skillName}`,
- `<p>You are about to purchase the skill "${skillName}".</p>
- <button id="confirm-purchase-btn">Confirm</button>`
- );
- }
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-purchase-modal-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-save-skill-prices.md b/prompts/monetization/03-save-skill-prices.md
deleted file mode 100644
index 683de2ac7..000000000
--- a/prompts/monetization/03-save-skill-prices.md
+++ /dev/null
@@ -1,120 +0,0 @@
----
-status: not-started
----
-
-# Prompt 3: Save Skill Prices
-
-## Objective
-Implement the backend API and frontend logic to save the skill prices set by a creator in the agent edit page.
-
-## Explanation
-Following the creation of the UI for skill pricing, this step involves creating the necessary API endpoint to receive and store the pricing data in the database. The frontend will be updated to send the data from the form to this endpoint.
-
-## Instructions
-1. **Database Schema:**
- * Ensure you have a table to store prices, e.g., `agent_skill_prices`.
- * It should contain columns like `agent_id`, `skill_name`, `amount` (as an integer or bigint for precision), and `currency_mint`.
-
-2. **Create a Backend API Endpoint:**
- * Create a new endpoint, for example, `POST /api/agents/:id/prices`. This could be in `api/agents/prices.js` or handled within the main agent update logic.
- * This endpoint will receive an agent ID and a payload of skill prices (e.g., `{ "skill_name": { "amount": 1500000, "currency_mint": "..." } }`).
- * The endpoint should be protected, ensuring only the agent's owner can update prices.
- * The backend logic should perform an "upsert" operation: for each skill in the payload, it should `UPDATE` the price if it exists or `INSERT` a new row if it doesn't. Skills not in the payload or with an empty price can be deleted.
-
-3. **Update Frontend JavaScript:**
- * In the script for `agent-edit.html`, add an event listener to the "Save Prices" button.
- * When clicked, the script should gather all the data from the skill price input fields.
- * It should construct a payload object mapping skill names to their price and currency. Remember to convert the human-readable amount (e.g., 1.50 USDC) back to the base unit (e.g., 1,500,000 lamports).
- * Send this payload to the new API endpoint using a `fetch` POST request.
- * Provide user feedback (e.g., a toast notification) on success or failure.
-
-## Code Example (Backend API - Express.js style)
-
-```javascript
-// POST /api/agents/:id/prices
-app.post('/api/agents/:id/prices', async (req, res) => {
- const { id } = req.params;
- const prices = req.body.prices; // Expects an object like { skillName: { amount, currency_mint } }
- const userId = await getUserIdFromRequest(req); // Your auth logic
-
- // 1. Verify user owns the agent
- const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [id]);
- if (!agent || agent.owner_id !== userId) {
- return res.status(403).json({ error: 'Forbidden' });
- }
-
- // 2. Use a transaction to update prices
- const client = await db.getClient();
- try {
- await client.query('BEGIN');
- // First, clear existing prices for this agent
- await client.query('DELETE FROM agent_skill_prices WHERE agent_id = $1', [id]);
- // Then, insert the new ones
- for (const skillName in prices) {
- const { amount, currency_mint } = prices[skillName];
- if (amount > 0) {
- await client.query(
- 'INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint) VALUES ($1, $2, $3, $4)',
- [id, skillName, amount, currency_mint]
- );
- }
- }
- await client.query('COMMIT');
- res.status(200).json({ message: 'Prices updated successfully' });
- } catch (e) {
- await client.query('ROLLBACK');
- res.status(500).json({ error: 'Database error' });
- } finally {
- client.release();
- }
-});
-```
-
-## Code Example (Frontend JavaScript)
-
-```javascript
-document.getElementById('save-prices-btn').addEventListener('click', async () => {
- const prices = {};
- const agentId = /* get agent ID from page */;
-
- document.querySelectorAll('.skill-price-row').forEach(row => {
- const priceInput = row.querySelector('.price-input');
- const currencySelect = row.querySelector('.currency-select');
- const skillName = priceInput.dataset.skill;
- const amountFloat = parseFloat(priceInput.value);
-
- if (skillName && !isNaN(amountFloat) && amountFloat > 0) {
- prices[skillName] = {
- amount: Math.round(amountFloat * 1e6), // Convert to lamports
- currency_mint: currencySelect.value
- };
- }
- });
-
- try {
- const response = await fetch(`/api/agents/${agentId}/prices`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json', /* Auth headers */ },
- body: JSON.stringify({ prices })
- });
- if (!response.ok) throw new Error('Failed to save prices');
- showToast('Prices saved!', 'success');
- } catch (error) {
- showToast(error.message, 'error');
- }
-});
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-save-skill-prices.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-skill-purchase-flow-ui.md b/prompts/monetization/03-skill-purchase-flow-ui.md
deleted file mode 100644
index 325aab5b5..000000000
--- a/prompts/monetization/03-skill-purchase-flow-ui.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# Prompt 3: Skill Purchase Flow UI
-
-## Objective
-Implement the UI flow for purchasing a skill. When a user clicks on a paid skill on the agent detail page, a confirmation modal should appear displaying the skill name, price, and a "Buy Now" button.
-
-## Explanation
-After connecting their wallet, the next step is for users to be able to initiate a purchase. This task focuses on creating the frontend modal that serves as the confirmation step before creating and sending the on-chain transaction. This modal prevents accidental purchases and provides a clear summary of the transaction to the user.
-
-## Instructions
-1. **Create the Purchase Modal HTML:**
- * In `marketplace.html`, add the HTML structure for a modal dialog. It should be hidden by default.
- * The modal should have placeholders for the skill name, price, and action buttons.
-
-2. **Add Event Listeners:**
- * In `src/marketplace.js`, modify the `renderDetail` function. When rendering skills, attach a click event listener to the skill entries.
- * If a clicked skill is paid, the event listener should populate the purchase modal with the skill's data (name, price) and make the modal visible.
-
-3. **Style the Modal:**
- * In `/public/marketplace.css`, add CSS rules to style the modal, its backdrop, and content to match the site's aesthetic.
-
-## HTML Example (`marketplace.html`)
-
-```html
-<!-- Add this somewhere inside the <body> tag -->
-<div id="purchaseModal" class="modal-backdrop" style="display: none;">
- <div class="modal-content">
- <div class="modal-header">
- <h2>Confirm Purchase</h2>
- <button id="closePurchaseModal" class="modal-close-btn">&times;</button>
- </div>
- <div class="modal-body">
- <p>You are about to purchase the skill:</p>
- <h3 id="modalSkillName"></h3>
- <p>Price:</p>
- <h3 id="modalSkillPrice"></h3>
- </div>
- <div class="modal-footer">
- <button id="confirmPurchaseBtn" class="modal-action-btn">Buy Now</button>
- </div>
- </div>
-</div>
-```
-
-## JavaScript Logic (`src/marketplace.js`)
-
-```javascript
-// Inside renderDetail or a suitable scope
-const purchaseModal = document.getElementById('purchaseModal');
-const closePurchaseModalBtn = document.getElementById('closePurchaseModal');
-const confirmPurchaseBtn = document.getElementById('confirmPurchaseBtn');
-const modalSkillName = document.getElementById('modalSkillName');
-const modalSkillPrice = document.getElementById('modalSkillPrice');
-
-function openPurchaseModal(skillName, price) {
- modalSkillName.textContent = skillName;
- modalSkillPrice.textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
- purchaseModal.style.display = 'flex';
- // Store data for the next step
- confirmPurchaseBtn.dataset.skillName = skillName;
-}
-
-function closePurchaseModal() {
- purchaseModal.style.display = 'none';
-}
-
-closePurchaseModalBtn.addEventListener('click', closePurchaseModal);
-window.addEventListener('click', (event) => {
- if (event.target === purchaseModal) {
- closePurchaseModal();
- }
-});
-
-// In your skill rendering loop:
-const skillEl = document.createElement('span');
-skillEl.className = 'skill-entry';
-// ... set content ...
-if (price) {
- skillEl.addEventListener('click', () => openPurchaseModal(name, price));
-}
-```
-
-## CSS Example (`/public/marketplace.css`)
-
-```css
-.modal-backdrop {
- position: fixed;
- inset: 0;
- background-color: rgba(0, 0, 0, 0.7);
- display: flex;
- align-items: center;
- justify-content: center;
- z-index: 1000;
-}
-.modal-content {
- background: var(--panel, #14141c);
- padding: 24px;
- border-radius: 12px;
- border: 1px solid var(--border, #1f1f29);
- width: min(400px, 90vw);
-}
-.modal-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- border-bottom: 1px solid var(--border, #1f1f29);
- padding-bottom: 12px;
- margin-bottom: 12px;
-}
-.modal-header h2 { margin: 0; font-size: 18px; }
-.modal-close-btn { background: none; border: none; color: #eee; font-size: 24px; cursor: pointer; }
-.modal-footer { margin-top: 24px; text-align: right; }
-.modal-action-btn {
- background-color: var(--accent, #6a5cff);
- color: white;
- /* ... other button styles */
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-skill-purchase-flow-ui.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-solana-pay-backend.md b/prompts/monetization/03-solana-pay-backend.md
deleted file mode 100644
index bb8f05cec..000000000
--- a/prompts/monetization/03-solana-pay-backend.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Prompt 3: Solana Pay Integration (Backend)
-
-## Objective
-Create a backend API endpoint that generates a Solana Pay transaction request when a user decides to purchase a skill.
-
-## Explanation
-To securely handle payments, we will use Solana Pay. This standard allows us to create a transaction on the backend and present it to the user's mobile wallet for approval. This prompt focuses on creating the API endpoint that prepares this transaction. The endpoint will receive a skill name, look up its price, and construct a transaction to transfer the correct amount of USDC from the buyer to the seller.
-
-## Instructions
-1. **Create a New API Endpoint:**
- * In the `api/payments/` directory, create a new file named `prepare-skill-purchase.js`.
- * This endpoint should handle `POST` requests and expect a `skillName` and `agentId` in the request body.
-
-2. **Implement the Endpoint Logic:**
- * The endpoint needs to perform several actions:
- * Authenticate the user to identify the buyer.
- * From the `agentId`, look up the agent and its creator.
- * From the creator's profile, retrieve their payout wallet address.
- * From `skillName` and `agentId`, query the `agent_skill_prices` table to get the skill's price (amount and currency). For now, we'll assume USDC.
- * Construct a Solana transaction using the `@solana/web3.js` library to transfer the specified amount of USDC from the buyer to the creator.
- * Return the transaction details in the format required by the Solana Pay spec. This includes the transaction itself (serialized), a message, and a label.
-
-3. **Dependencies:**
- * You will need to add `@solana/pay` and `@solana/spl-token` to your backend dependencies if they are not already present.
-
-## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)
-
-```javascript
-// api/payments/prepare-skill-purchase.js
-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
-import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';
-import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db'; // Placeholder for DB functions
-
-const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d');
-const PLATFORM_WALLET = new PublicKey('YourPlatformWalletAddressHere'); // Your platform's treasury wallet
-
-export default async function handler(req, res) {
- if (req.method !== 'POST') {
- return res.status(405).json({ error: 'Method Not Allowed' });
- }
-
- try {
- // User must be authenticated (logic not shown)
- const buyerPublicKey = new PublicKey(req.user.solana_wallet);
-
- const { agentId, skillName } = req.body;
- if (!agentId || !skillName) {
- return res.status(400).json({ error: 'agentId and skillName are required' });
- }
-
- const priceInfo = await findSkillPrice(agentId, skillName);
- if (!priceInfo) {
- return res.status(404).json({ error: 'Skill or price not found' });
- }
-
- const creatorPayoutWallet = await findCreatorPayoutWallet(agentId);
- if (!creatorPayoutWallet) {
- return res.status(500).json({ error: 'Creator payout wallet not configured' });
- }
-
- const connection = new Connection(process.env.SOLANA_RPC_URL);
- const { blockhash } = await connection.getLatestBlockhash();
-
- const transaction = new Transaction({
- recentBlockhash: blockhash,
- feePayer: buyerPublicKey,
- });
-
- const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);
- const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, new PublicKey(creatorPayoutWallet));
-
- // Assuming a 5% platform fee
- const platformFee = Math.floor(priceInfo.amount * 0.05);
- const creatorAmount = priceInfo.amount - platformFee;
-
- // Transfer to creator
- transaction.add(
- createTransferInstruction(
- buyerUsdcAddress,
- creatorUsdcAddress,
- buyerPublicKey,
- creatorAmount
- )
- );
-
- // Transfer to platform
- const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);
- transaction.add(
- createTransferInstruction(
- buyerUsdcAddress,
- platformUsdcAddress,
- buyerPublicKey,
- platformFee
- )
- );
-
- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });
-
- res.status(200).json({
- transaction: serializedTransaction.toString('base64'),
- message: `Purchase skill "${skillName}" for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`,
- label: 'three.ws Agent Skill',
- });
-
- } catch (error) {
- console.error('Error preparing skill purchase:', error);
- res.status(500).json({ error: 'Internal Server Error' });
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-solana-pay-backend.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/prompts/monetization/03-ui-manage-skill-prices.md b/prompts/monetization/03-ui-manage-skill-prices.md
deleted file mode 100644
index 98b9046ce..000000000
--- a/prompts/monetization/03-ui-manage-skill-prices.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Prompt 3: UI for Skill Price Management
-
-## Objective
-Create a user interface within the agent editing page that allows creators to easily set, update, and remove prices for their skills.
-
-## Explanation
-With the backend API in place, creators need a visual tool to manage their skill pricing. This UI will be added to the `agent-edit.html` page, providing an intuitive way to toggle a skill as "paid" and set its price without needing to interact with the API directly.
-
-## Instructions
-1. **Locate the Correct File:**
- * Open `agent-edit.html`. This page contains the forms for editing an agent's properties.
-
-2. **Add a "Monetization" Section:**
- * Find where skills or agent profile prompts are rendered. This is likely in the "Publish" tab (`id="panel-publish"`).
- * Add a new section for skill pricing. You could list the agent's available skills (fetched from the agent's metadata) and provide pricing controls for each.
-
-3. **Implement UI Controls for Each Skill:**
- * For each skill, display its name.
- * Add a checkbox or toggle switch labeled "Paid Skill".
- * When the "Paid Skill" toggle is enabled, show two input fields:
- * An `input type="number"` for the `amount` (in a user-friendly unit like USDC, not lamports).
- * A (potentially hidden or disabled) field for the `currency_mint`, which could default to USDC for now.
- * When the toggle is disabled, hide the price inputs.
-
-4. **Handle Form Submission:**
- * When the creator saves their changes on the `agent-edit` page, your JavaScript should gather the pricing data for each skill.
- * For each skill that is marked as "paid", make a call to the `POST /api/agents/:id/skills/price` endpoint created in the previous prompt.
- * Remember to convert the user-friendly amount (e.g., 1.5 USDC) back to the base unit (e.g., 1,500,000 lamports for a 6-decimal currency) before sending it to the API.
- * If a skill is marked as free (or was paid and is now free), send a request with `amount: 0` to remove the price.
-
-## Code Example (Frontend - `agent-edit.html` script)
-
-```javascript
-// Inside the script tag of agent-edit.html
-
-// Assume 'agent.skills' is an array of skill names and 'currentPrices' is a map from the API
-function renderSkillPricingUI(skills, currentPrices) {
- const container = document.getElementById('skill-pricing-container'); // You'll need to create this container
- container.innerHTML = '<h3>Skill Pricing</h3>';
-
- skills.forEach(skillName => {
- const price = currentPrices[skillName];
- const isPaid = !!price;
- const amountInUSDC = isPaid ? (price.amount / 1e6).toFixed(2) : '1.00';
-
- const skillRow = document.createElement('div');
- skillRow.className = 'form-group skill-price-row';
- skillRow.innerHTML = `
- <label class="form-label">${escapeHtml(skillName)}</label>
- <div class="skill-price-controls">
- <input type="checkbox" class="paid-toggle" data-skill="${escapeHtml(skillName)}" ${isPaid ? 'checked' : ''}>
- <span class="toggle-label">Paid</span>
- <div class="price-inputs" style="${isPaid ? '' : 'display: none;'}">
- <input type="number" class="price-amount" value="${amountInUSDC}" step="0.01" min="0">
- <span>USDC</span>
- </div>
- </div>
- `;
- container.appendChild(skillRow);
- });
-
- // Add event listeners for toggles
- container.querySelectorAll('.paid-toggle').forEach(toggle => {
- toggle.addEventListener('change', (e) => {
- const inputs = e.target.closest('.skill-price-controls').querySelector('.price-inputs');
- inputs.style.display = e.target.checked ? 'flex' : 'none';
- });
- });
-}
-
-// On save, you would iterate through these controls:
-async function saveSkillPrices(agentId) {
- const rows = document.querySelectorAll('.skill-price-row');
- for (const row of rows) {
- const toggle = row.querySelector('.paid-toggle');
- const skillName = toggle.dataset.skill;
- const amountInput = row.querySelector('.price-amount');
-
- let amountInLamports = 0;
- if (toggle.checked) {
- const amountInUSDC = parseFloat(amountInput.value);
- if (!isNaN(amountInUSDC) && amountInUSDC > 0) {
- amountInLamports = Math.round(amountInUSDC * 1e6); // Convert to lamports
- }
- }
-
- await fetch(`/api/agents/${agentId}/skills/price`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- skill_name: skillName,
- amount: amountInLamports,
- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // Assuming USDC
- })
- });
- }
-}
-```
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "prompts/monetization/03-ui-manage-skill-prices.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/src/irl-net.js b/src/irl-net.js
index 0f0f37cf1..47410ea9c 100644
--- a/src/irl-net.js
+++ b/src/irl-net.js
@@ -1,18 +1,20 @@
// Realtime client for /irl — wraps colyseus.js with a tiny event API so irl.js
-// can subscribe to live pin changes without knowing anything about Colyseus.
-// Mirrors walk-net.js in shape (status model, single-retry reconnect, no storms)
-// so the two transports read the same.
+// can subscribe to live PRESENCE and REACTIONS without knowing anything about
+// Colyseus. Mirrors walk-net.js in shape (status model, single-retry reconnect,
+// no storms) so the two transports read the same.
//
// What it does: joins the irl_world room for the viewer's precision-6 geocell and
-// relays the pin MapSchema as pin:add / pin:update / pin:remove events. A late
-// joiner is handed the room's full current pin set on connect (schema sync), so
-// it never misses pins placed before it arrived. When the viewer physically walks
-// into a new geocell, moveTo() re-joins the new room.
+// relays the live viewer set (presence: count + opt-in ghosts) and ambient
+// reactions. It deliberately does NOT transport pins — placed agents are private
+// by location and are discovered only through the per-viewer proximity poll in
+// irl.js, never broadcast here as a roster (see multiplayer/src/rooms/IrlRoom.js).
+// When the viewer physically walks into a new geocell, moveTo() re-joins the room.
//
// Graceful degradation: if no server is configured for this environment, or the
// socket can't be reached after one retry, it settles into a distinct status
-// (`unavailable` / `failed`) so irl.js drops to the poll fallback and the HUD pill
-// says "Polling" — never a dead "reconnecting…" forever.
+// (`unavailable` / `failed`) so presence is simply hidden — pin discovery is
+// unaffected (it runs on the poll regardless), and the HUD pill hides rather than
+// looping on a dead "reconnecting…" forever.
import { Client, getStateCallbacks } from 'colyseus.js';
import { IrlState } from '../multiplayer/src/irl-schemas.js';
@@ -91,10 +93,7 @@ export class IrlNet {
this.error = null;
this._handlers = {
status: new Set(),
- 'pin:add': new Set(),
- 'pin:update': new Set(),
- 'pin:remove': new Set(),
- presence: new Set(), // D2 — declared now so the event API is stable
+ presence: new Set(), // D2 — live viewer count + opt-in ghosts
reaction: new Set(), // D3 — ambient interaction reactions from the room
};
this._retries = 0;
@@ -135,29 +134,6 @@ export class IrlNet {
try { room.leave(); } catch {}
}
- _pinToObj(pin) {
- return {
- id: pin.id,
- lat: pin.lat,
- lng: pin.lng,
- heading: pin.heading,
- avatarUrl: pin.avatarUrl,
- avatarName: pin.avatarName,
- caption: pin.caption,
- x402Endpoint: pin.x402Endpoint,
- agentId: pin.agentId,
- placedAt: pin.placedAt,
- // Room frame — present (roomId !== '') when the pin belongs to a shared
- // room cluster; the renderer prefers these exact offsets over absolute GPS.
- roomId: pin.roomId,
- relEast: pin.relEast,
- relNorth: pin.relNorth,
- originLat: pin.originLat,
- originLng: pin.originLng,
- originYawDeg: pin.originYawDeg,
- };
- }
-
async connect() {
if (this._destroyed) return;
this._closeRoom();
@@ -197,17 +173,11 @@ export class IrlNet {
this._retries = 0; // a clean connection resets the retry budget
// Colyseus 0.16 moved schema callbacks behind getStateCallbacks(room).
+ // NOTE: the room intentionally syncs NO pins — placed agents are never
+ // broadcast as a roster (see IrlRoom.js); they're discovered only via the
+ // per-viewer proximity poll in irl.js. This client consumes presence +
+ // reactions only.
const $ = getStateCallbacks(this.room);
- const $pins = $(this.room.state)?.pins;
- if ($pins) {
- $pins.onAdd((pin) => {
- this._emit('pin:add', this._pinToObj(pin));
- $(pin).onChange(() => this._emit('pin:update', this._pinToObj(pin)));
- });
- $pins.onRemove((pin, id) => {
- this._emit('pin:remove', { id: pin?.id || id });
- });
- }
// D2 presence — the room's `viewers` MapSchema is the live crowd. Any
// add / remove / per-viewer change re-derives the { count, viewers } the
diff --git a/src/irl.js b/src/irl.js
index f45a711a1..748171805 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -1139,8 +1139,8 @@ function pinHeightM(pin) {
// of trusting its own ~10 m-noisy GPS, so a cluster keeps its room-scale layout
// identical for every viewer — couch-agent and wall-agent stay metres apart on
// the right sides no matter how GPS drifts. The math lives in the pure, unit-
-// tested src/irl/room-anchor.js; here we only read it. normalizeStreamPin and
-// the REST projection both deliver these as snake_case, so this reads one shape.
+// tested src/irl/room-anchor.js; here we only read it. The proximity-poll
+// projection delivers these as snake_case, the one shape this reads.
function pinRoom(pin) {
if (!pin || !pin.room_id) return null;
const oLat = Number(pin.origin_lat), oLng = Number(pin.origin_lng);
@@ -1194,9 +1194,10 @@ function blendOrigin(prev, fix) {
};
}
-let _lastNearbyFetch = 0;
-const NEARBY_RADIUS = 150; // metres
-const NEARBY_INTERVAL = 15000; // ms
+// Tight "stumble upon" gate: an agent only renders once you're within ~40 m of
+// it (matches the server's hard radius cap). You discover one by physically being
+// near it with your camera up — never from a list, map, or neighbourhood feed.
+const NEARBY_RADIUS = 40; // metres
function onGPSPosition(pos) {
const wasReady = gpsState.ready;
@@ -1273,21 +1274,11 @@ function onGPSPosition(pos) {
// orb holds its real-world bearing as the user walks (same treatment as pins).
for (const g of ghostViewers.values()) positionGhostOrb(g);
- // Live transport: re-join the room when we cross into a new geocell, and
- // reconcile the rendered set against the stream as the viewer walks (pins move
- // into / out of the nearby radius). Not streaming and not yet polling → keep the
- // throttled poll so the first fixes still show content before the transport
- // settles; once the poll fallback's own timer owns refreshes, this stays quiet.
- if (irlNet && _streamOnline) {
- irlNet.moveTo(gpsState.lat, gpsState.lng);
- scheduleReconcile();
- } else if (!_pollTimer) {
- const now = Date.now();
- if (now - _lastNearbyFetch > NEARBY_INTERVAL) {
- _lastNearbyFetch = now;
- loadNearbyPins();
- }
- }
+ // Live presence follows the viewer into a new geocell as they walk — a no-op
+ // until they actually cross a ~1.2 km cell boundary (and while the socket is
+ // offline). Pin discovery doesn't ride this tick; it's the proximity poll's own
+ // timer (startPinPolling), scoped to a tight radius around the live position.
+ irlNet?.moveTo(gpsState.lat, gpsState.lng);
}
// Build the GPS world-anchor for the freshly locked own avatar and open the
@@ -1466,7 +1457,6 @@ function commitPin(pinLat, pinLng, headingDeg, caption, source = 'gyro-gps') {
if (result?.ok && gpsPin) {
gpsPin.id = result.id;
_myPinIds.add(result.id);
- dropOwnPinFromStream(result.id); // the server echoes my pin over the stream; never double-spawn it
const dir = compassLabel(headingDeg);
setStatus(result.permanent
? `Pinned facing ${dir} — permanently visible to nearby users`
@@ -1659,7 +1649,6 @@ function persistFloorAnchor(pose) {
}).then(result => {
if (result?.ok && gpsPin) {
gpsPin.id = result.id;
- dropOwnPinFromStream(result.id); // the server echoes my pin over the stream; never double-spawn it
revealMyPinsBtn();
setXrHint(result.permanent
? 'Anchored & saved — permanently visible to nearby users'
@@ -1741,49 +1730,23 @@ function removeNearbyPin(id) {
updateNearbyBadge();
}
-// ── Realtime pin sync (D1) ──────────────────────────────────────────────────
-// Polling told you about a new / moved / removed pin only on the next 15 s cycle.
-// This streams them live: IrlNet joins the irl_world room for the viewer's geocell
-// and relays the shared pin set as pin:add / pin:update / pin:remove, which we
-// reconcile into the SAME nearbyPins the poll feeds — so the rest of the app (LOD,
-// radar, sheet, badge) never knows which transport fed it. The poll stays as a
-// real fallback for when the realtime host is unreachable.
+// ── Realtime presence + reactions (D2/D3) ───────────────────────────────────
+// IrlNet joins the irl_world room for the viewer's geocell — but ONLY for live
+// PRESENCE (who else is viewing nearby) and ambient REACTIONS. The room is NOT a
+// pin transport: a placed agent's coordinates are never broadcast as a roster.
+// Agents are discovered solely through the per-viewer proximity poll below
+// (loadNearbyPins), which the server scopes to a tight radius around our OWN
+// position — so you see another agent only by being physically near it with your
+// camera up, never from a list, map, or neighbourhood feed. The poll runs the
+// whole session once GPS is ready, independent of whether the socket connects.
let irlNet = null;
-let _streamOnline = false; // true only while the WS is live and owns nearbyPins
-let _pollTimer = null; // fallback poll interval handle
-let _reconcileRaf = 0; // coalesces a burst of stream events into one reconcile
-const streamPins = new Map(); // id → normalized snake_case pin (the room's full window)
-const POLL_FALLBACK_MS = 10000; // fallback refresh cadence when the stream is down
-
-// Map the room's camelCase wire pin to the snake_case shape the rest of irl.js
-// already reads (spawnNearbyPin / openPinSheet / radar), so those paths are untouched.
-function normalizeStreamPin(w) {
- return {
- id: w.id,
- lat: Number(w.lat),
- lng: Number(w.lng),
- heading: Number(w.heading) || 0,
- avatar_url: w.avatarUrl || null,
- avatar_name: w.avatarName || null,
- caption: w.caption || null,
- x402_endpoint: w.x402Endpoint || null,
- agent_id: w.agentId || null,
- placed_at: w.placedAt || null,
- // Room frame — '' means a standalone pin, so collapse to null to match the
- // REST projection's null and let pinRoom() treat both shapes identically.
- room_id: w.roomId || null,
- rel_east_m: Number.isFinite(w.relEast) ? w.relEast : null,
- rel_north_m: Number.isFinite(w.relNorth) ? w.relNorth : null,
- origin_lat: Number.isFinite(w.originLat) ? w.originLat : null,
- origin_lng: Number.isFinite(w.originLng) ? w.originLng : null,
- origin_yaw_deg: Number.isFinite(w.originYawDeg) ? w.originYawDeg : null,
- };
-}
+let _streamOnline = false; // true only while the presence/reaction socket is live
+let _pollTimer = null; // proximity poll handle (the sole pin-discovery transport)
+const POLL_INTERVAL_MS = 10000; // proximity refresh cadence
function startPinSync() {
if (!gpsState.ready) return;
if (irlNet) irlNet.destroy();
- streamPins.clear();
irlNet = new IrlNet({
lat: gpsState.lat, lng: gpsState.lng,
deviceToken: _deviceToken, agent: _currentAgentId || '',
@@ -1791,133 +1754,54 @@ function startPinSync() {
// when sharing; the server drops it otherwise.
ghost: getShareGhost(), avatar: resolveAvatarUrl(_currentAvatarId),
});
- irlNet.on('pin:add', (w) => ingestStreamPin('add', w));
- irlNet.on('pin:update', (w) => ingestStreamPin('update', w));
- irlNet.on('pin:remove', (w) => ingestStreamPin('remove', w));
irlNet.on('reaction', (msg) => onReaction(msg)); // D3 ambient interaction reactions
irlNet.on('presence', ({ count, viewers }) => updatePresence(count, viewers)); // D2
irlNet.on('status', ({ status }) => onNetStatus(status));
irlNet.connect();
startHeartbeat();
+ // Pins come from the proximity poll, never the socket — start it now and keep it
+ // running for the whole session regardless of presence connectivity.
+ startPinPolling();
}
function onNetStatus(status) {
_streamOnline = status === 'online';
- if (status === 'online') { stopPollFallback(); setNetPill('live'); scheduleReconcile(); }
- else if (status === 'connecting') { streamPins.clear(); setNetPill('connecting'); }
- else if (status === 'offline') { setNetPill('connecting'); } // mid single-retry — pins persist
- else { startPollFallback(); setNetPill('polling'); } // failed | unavailable | idle
- // D2 presence is live-only: the chip + ghosts are meaningful only while the WS
- // owns the stream. Any non-online status clears them so a stale count or frozen
- // ghost never lingers in poll fallback / while reconnecting; online refreshes
- // from the next presence delta.
+ if (status === 'online') setNetPill('live');
+ else if (status === 'connecting' || status === 'offline') setNetPill('connecting');
+ else setNetPill('idle'); // failed | unavailable | idle — presence off; pins still poll
+ // D2 presence (count chip + ghosts) is live-only: clear it whenever the socket
+ // isn't online so a stale count or frozen ghost never lingers. Pin discovery is
+ // unaffected — it runs on the proximity poll either way.
if (status !== 'online') clearPresence();
}
-function ingestStreamPin(kind, wire) {
- if (!wire || !wire.id) return;
- if (kind === 'remove') streamPins.delete(wire.id);
- else streamPins.set(wire.id, normalizeStreamPin(wire));
- scheduleReconcile();
-}
-
-// Coalesce the burst of onAdd callbacks Colyseus fires on join (and any flurry of
-// deltas) into a single reconcile next frame.
-function scheduleReconcile() {
- if (_reconcileRaf) return;
- _reconcileRaf = requestAnimationFrame(() => { _reconcileRaf = 0; reconcileFromStream(); });
-}
-
-// Reconcile the rendered nearby set against the live stream, filtered to the nearby
-// radius — the room holds a coarse ~3 km geocell window, so the per-viewer 150 m
-// filter lives here. Spawns arrivals, refreshes changed pins, despawns pins that
-// left the radius or were removed. The placer's own live pin is never doubled.
-function reconcileFromStream() {
- if (!_streamOnline || !gpsState.ready) return;
- for (const known of [...nearbyPins]) {
- const src = streamPins.get(known.id);
- const within = src && Number.isFinite(src.lat) &&
- haversineMeters(gpsState.lat, gpsState.lng, src.lat, src.lng) <= NEARBY_RADIUS;
- if (!within) removeNearbyPin(known.id);
- }
- for (const [id, src] of streamPins) {
- if (gpsPin?.id && id === gpsPin.id) continue; // never my own anchored pin
- if (!Number.isFinite(src.lat) || !Number.isFinite(src.lng)) continue;
- const d = haversineMeters(gpsState.lat, gpsState.lng, src.lat, src.lng);
- if (d > NEARBY_RADIUS) continue;
- const known = nearbyPins.find((n) => n.id === id);
- if (known) applyStreamFields(known, src);
- else {
- const entry = { ...src, distance_m: Math.round(d), group: null, labelEl: null, glbLoaded: false };
- nearbyPins.push(entry);
- spawnNearbyPin(entry);
- }
- }
- updateNearbyBadge();
-}
-
-// Update a rendered pin from a stream delta: position / heading / caption / name
-// (which applyPinUpdate skips when there's no avatar version bump — the stream has
-// none), then hand off to applyPinUpdate for the avatar GLB swap (a C6 re-skin),
-// which no-ops when the URL is unchanged.
-function applyStreamFields(known, src) {
- if (Number.isFinite(src.lat)) known.lat = src.lat;
- if (Number.isFinite(src.lng)) known.lng = src.lng;
- if (src.heading != null) known.heading = src.heading;
- if (src.caption !== undefined) known.caption = src.caption;
- if (src.x402_endpoint !== undefined) known.x402_endpoint = src.x402_endpoint;
- // Name lives on the floating label; update it here because applyPinUpdate only
- // reaches its name branch on an avatar change, so a rename-only edit would miss it.
- if (src.avatar_name != null && src.avatar_name !== known.avatar_name) {
- known.avatar_name = src.avatar_name;
- const nameEl = known.labelEl?.querySelector('.irl-agent-label-name');
- if (nameEl) nameEl.textContent = known.avatar_name || 'Agent';
- }
- if (known.group) {
- const wp = gpsToWorld(known.lat, known.lng);
- known.group.position.set(wp.x, pinHeightM(known), wp.z);
- known.group.rotation.y = pinYawRad(known);
- if ('baseYaw' in known) known.baseYaw = known.group.rotation.y;
- }
- applyPinUpdate(known, src);
-}
-
-// When this device places its own pin, the server echoes it back over the stream;
-// drop it so the placer never sees a duplicate of their own anchored agent.
-function dropOwnPinFromStream(id) {
- if (!id) return;
- streamPins.delete(id);
- removeNearbyPin(id);
-}
-
-function startPollFallback() {
+function startPinPolling() {
if (_pollTimer) return;
- loadNearbyPins(); // immediate refresh, don't wait a full cycle
- _pollTimer = setInterval(loadNearbyPins, POLL_FALLBACK_MS);
+ loadNearbyPins(); // immediate first fetch, don't wait a cycle
+ _pollTimer = setInterval(loadNearbyPins, POLL_INTERVAL_MS);
}
-function stopPollFallback() {
+function stopPinPolling() {
if (_pollTimer) { clearInterval(_pollTimer); _pollTimer = null; }
}
-// The realtime status pill in the topbar: live (green), connecting (amber pulse),
-// or polling (the fallback transport is active — still fully functional, tap to retry).
+// The presence/reaction socket status pill in the topbar: live (green — you can
+// see who else is here and their reactions), connecting (amber pulse), or hidden
+// when unavailable. Pin discovery never depends on this; it always runs via the
+// proximity poll.
function setNetPill(state) {
const pill = document.getElementById('irl-net-pill');
if (!pill) return;
- pill.classList.remove('is-live', 'is-connecting', 'is-polling');
+ pill.classList.remove('is-live', 'is-connecting');
if (state === 'live') {
pill.classList.add('is-live'); pill.hidden = false;
- pill.textContent = 'Live'; pill.title = 'Live — nearby agents update in realtime';
+ pill.textContent = 'Live'; pill.title = 'Live — you can see who else is viewing nearby and their reactions in realtime';
} else if (state === 'connecting') {
pill.classList.add('is-connecting'); pill.hidden = false;
- pill.textContent = 'Connecting'; pill.title = 'Connecting to live sync…';
- } else if (state === 'polling') {
- pill.classList.add('is-polling'); pill.hidden = false;
- pill.textContent = 'Polling'; pill.title = 'Live sync unavailable — refreshing nearby agents every 10s. Tap to retry.';
+ pill.textContent = 'Connecting'; pill.title = 'Connecting to live presence…';
} else {
pill.hidden = true;
}
- pill.setAttribute('aria-label', `Realtime status: ${pill.textContent || 'idle'}`);
+ pill.setAttribute('aria-label', `Live presence: ${pill.textContent || 'off'}`);
}
// ── Live viewer presence (D2) ───────────────────────────────────────────────
@@ -2068,11 +1952,40 @@ function updateGhosts(dt) {
}
}
+// Refresh an already-rendered pin from a fresh proximity-poll row: move it if its
+// stored position / heading / room frame changed (an owner calibrate or edit),
+// relabel it on a rename, then let applyPinUpdate swap the GLB on a re-skin
+// (avatar_version bump). Repositioning uses pinWorldPos so room-anchored clusters
+// resolve through their shared origin exactly as on spawn.
+function refreshKnownPin(known, pin) {
+ let moved = false;
+ for (const k of ['lat', 'lng', 'heading', 'room_id', 'rel_east_m', 'rel_north_m',
+ 'origin_lat', 'origin_lng', 'origin_yaw_deg']) {
+ if (pin[k] !== undefined && pin[k] !== known[k]) { known[k] = pin[k]; moved = true; }
+ }
+ if (pin.caption !== undefined) known.caption = pin.caption;
+ if (pin.x402_endpoint !== undefined) known.x402_endpoint = pin.x402_endpoint;
+ // Name lives on the floating label; update it here because applyPinUpdate only
+ // reaches its name branch on an avatar change, so a rename-only edit would miss it.
+ if (pin.avatar_name != null && pin.avatar_name !== known.avatar_name) {
+ known.avatar_name = pin.avatar_name;
+ const nameEl = known.labelEl?.querySelector('.irl-agent-label-name');
+ if (nameEl) nameEl.textContent = known.avatar_name || 'Agent';
+ }
+ if (moved && known.group) {
+ const wp = pinWorldPos(known);
+ known.group.position.set(wp.x, wp.y, wp.z);
+ known.group.rotation.y = pinYawRad(known);
+ if ('baseYaw' in known) known.baseYaw = known.group.rotation.y;
+ }
+ applyPinUpdate(known, pin);
+}
+
async function loadNearbyPins() {
if (!gpsState.ready) return;
- // While the live stream owns the nearby set, the poll is a no-op — it would fight
- // the reconcile. It runs only as the fallback transport (see startPollFallback).
- if (_streamOnline) return;
+ // The proximity poll is the SOLE pin-discovery transport: the server returns only
+ // the agents within a tight radius of our live position (no roster, no map), so
+ // this both finds new arrivals and drops ones we've walked away from.
try {
const r = await fetch(
`/api/irl/pins?lat=${gpsState.lat}&lng=${gpsState.lng}&radius=${NEARBY_RADIUS}`,
@@ -2093,14 +2006,13 @@ async function loadNearbyPins() {
return false;
});
- // Spawn new arrivals; refresh any already-known pin whose owner re-skinned
- // it (C6 remote outfit change). The nearby feed carries avatar_version, so a
- // bumped version on a pin we already render means swap its GLB to the new
- // (versioned, cache-busted) avatar_url — every viewer sees the new look on
- // the next poll, the same diff D1's pin_updated push reuses in realtime.
+ // Spawn new arrivals; refresh any already-known pin. The feed carries the
+ // pin's current position (a calibrate/edit may have moved it), caption, name
+ // and avatar_version, so refreshKnownPin moves/relabels it and swaps the GLB
+ // on a C6 re-skin — the poll is the single propagation path for every change.
for (const pin of incoming) {
const known = nearbyPins.find(n => n.id === pin.id);
- if (known) applyPinUpdate(known, pin);
+ if (known) refreshKnownPin(known, pin);
else {
const entry = { ...pin, group: null, labelEl: null, glbLoaded: false };
nearbyPins.push(entry);
@@ -4450,7 +4362,7 @@ loadMyPins().then(pins => { if (pins.length) revealMyPinsBtn(); }).catch(() => {
document.getElementById('irl-net-pill')?.addEventListener('click', () => irlNet?.retry());
// Tear down the live stream + poll on navigation away so we never leak a socket or
// an interval across an SPA transition / tab close.
-window.addEventListener('pagehide', () => { irlNet?.destroy(); stopPollFallback(); });
+window.addEventListener('pagehide', () => { irlNet?.destroy(); stopPinPolling(); });
// URL ?avatar= wins over the saved session (an explicit link is intentional);
// otherwise fall back to whatever avatar was active last visit.
diff --git a/tasks/wow-sprint/14-holder-dashboard.md b/tasks/wow-sprint/14-holder-dashboard.md
deleted file mode 100644
index 5450ba79b..000000000
--- a/tasks/wow-sprint/14-holder-dashboard.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# Task: $three holder dashboard (real Solana / Helius data)
-
-Give holders a reason to log in: a dashboard that shows their real $three position
-and the protocol's real health — all live, no fake numbers.
-
-## Anchor files & data
-- Token protocol API: `api/three-token/[action].js` — `stats`, `revenue-share` (per-user, authed), `burns`, `activity`.
-- Pump data: `api/pump/balances.js`, `api/pump/helius-stats.js`, `api/pump/dashboard.js`, `api/pump/curve.js`.
-- Wallet/auth: `src/wallet.js`, `src/wallet-auth.js`, `src/account.js`. Helius webhook ingestion at `api/pump/helius-webhook.js`.
-- $THREE mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`.
-- Pages: there's `pages/dashboard/` and `pages/pump-dashboard.html`. Build the holder view into the most appropriate one (read both first; don't fork a third dashboard).
-
-## Build a shared data hook FIRST
-Create one reusable client module (e.g. `src/pump/three-token-data.js`) that fetches + caches $three protocol stats and the connected wallet's position, with subscribe/refresh. Tasks 13/16/17 should reuse it. Single source of truth.
-
-## What to show (each with loading/empty/error states)
-1. **Your position** — connected wallet's $three balance, USD value, % of supply, unrealized PnL if cost basis is derivable; "connect wallet" empty state when not signed in (use `authenticate-wallet` flow).
-2. **Your revenue share** — from `?action=revenue-share` (authed). Show claimable/earned if present.
-3. **Protocol health** — price, market cap, holders, 24h volume, total burned (from `stats` + `burns`).
-4. **Recent activity** — your transactions + protocol activity (`?action=activity`), most recent first, paginated.
-5. **Quick actions** — links to trade ($three), the visualizer, and the token page.
-
-## Constraints
-- Real on-chain / API data only. Never fabricate balances or PnL — if a value isn't derivable, omit it, don't guess.
-- Handle the not-connected and zero-balance cases as designed empty states.
-
-## Definition of done
-- `npm run dev`: connect a wallet → real position + protocol data render; all states designed.
-- Shared data hook created and used. Zero console errors. `npm run build` clean.
-- Run the **completionist** subagent. Report the data sources per widget.
-
-> Build the shared data hook here FIRST if running 13/16/17 in parallel.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/wow-sprint/14-holder-dashboard.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/wow-sprint/16-token-page-upgrade.md b/tasks/wow-sprint/16-token-page-upgrade.md
deleted file mode 100644
index aad261127..000000000
--- a/tasks/wow-sprint/16-token-page-upgrade.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# Task: $three token page upgrade — real bonding curve + live trades
-
-Make the coin page the definitive place to understand $three: real-time price,
-real bonding curve, live trade tape, holders, burns — premium and trustworthy.
-
-## Anchor files & data
-- Pages: `pages/pump-coin-page.html`, `pages/pump-live.html`, `pages/pumpfun-buy.html` (read all; build the canonical coin page — likely `pump-coin-page.html` — and link the others).
-- Data: `api/pump/curve.js` (bonding curve), `api/pump/trades-stream.js` (live tape), `api/pump/helius-stats.js`, `api/pump/dashboard.js`, `api/three-token/[action].js` (`stats`, `burns`, `activity`).
-- Client: `src/pump/bonding-curve-chart.js`, `src/components/bonding-curve.js`, `src/pump/pump-swap-quote.js`, `src/pump/dashboard.js`, `src/components/PriceBadge.js`.
-- $THREE mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Reuse the shared data hook from task 14 if present (`src/pump/three-token-data.js`).
-
-## What to build (every widget with loading/empty/error states)
-1. **Price header** — live price, 24h change, market cap, holders, total burned. Updates in real time.
-2. **Bonding curve chart** — render the REAL curve from `api/pump/curve.js` (reserves/progress to graduation). Show current position on the curve and % to graduation. No mock curve.
-3. **Live trade tape** — stream from `api/pump/trades-stream.js`: time, side, size, price, wallet (truncated). Auto-scrolls, reconnects with backoff, shows connection status.
-4. **Buy/sell entry** — wire to the real swap path (`src/pump/pump-swap-quote.js` / `swap-jupiter.js` / the `trade` skill). Show a real quote before confirm. If wallet not connected, prompt connect.
-5. **Burns + activity** — recent burns and protocol activity feeds.
-
-## Constraints
-- 100% real data and real quotes. No fabricated price history — if historical candles aren't available from an endpoint, build/serve them from real trade data, don't fake them.
-- Handle stream disconnects and failed quotes as designed states.
-
-## Definition of done
-- `npm run dev`: coin page shows live price, real bonding curve, streaming trades, working quote.
-- Reconnect + error states work; responsive; zero console errors. `npm run build` clean.
-- Run the **completionist** subagent. Report data sources per widget and the swap path used.
-
-> Shares token data plumbing with 13/14/17 — let task 14 land the shared hook first.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/wow-sprint/16-token-page-upgrade.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/wow-sprint/17-holder-rewards-surface.md b/tasks/wow-sprint/17-holder-rewards-surface.md
deleted file mode 100644
index eab9552ee..000000000
--- a/tasks/wow-sprint/17-holder-rewards-surface.md
+++ /dev/null
@@ -1,47 +0,0 @@
-# Task: $three holder rewards / revenue-share surface (real on-chain)
-
-Give holders tangible upside they can see and act on: surface the real
-revenue-share / rewards the protocol already tracks, and make claiming (if
-supported) a first-class flow. This directly answers "what do I get for holding?"
-
-## Anchor files & data
-- Revenue share: `api/three-token/[action].js?action=revenue-share` (authenticated, per-user) and `?action=stats` for protocol totals; `?action=burns` for buyback/burn history.
-- Staking primitive if present: `src/solana-stake.js`. Wallet/auth: `src/wallet.js`, `src/wallet-auth.js`, `src/account.js`.
-- Contracts: check `contracts/` for any rewards/distribution program before assuming none exists.
-- $THREE mint: `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`. Reuse `src/pump/three-token-data.js` (task 14) if present.
-
-## First: establish what's real
-Read the revenue-share endpoint and any rewards contract to determine what
-actually exists (accrued share, claimable amount, distribution cadence, burn-as-
-reward). Build the UI around the real mechanism. **Do not invent a rewards model
-that the backend doesn't support** — if claiming isn't on-chain yet, present the
-accrued/earned view and clearly label what's live vs coming, sourced from real data.
-
-## What to build (with loading/empty/error states)
-1. **Your rewards** — connected wallet's accrued/earned revenue share from `revenue-share`. USD value. History if available.
-2. **Protocol distribution** — total distributed, total burned (buyback-and-burn is a real holder benefit), cadence — from `stats` + `burns`.
-3. **Claim flow** — IF an on-chain claim exists: a real, wired claim transaction with confirmation + tx link. If not, a clear accrual view (no fake "claim" button).
-4. **Connect-wallet** empty state when not signed in (`authenticate-wallet`).
-
-## Constraints
-- Real data and real transactions only. No fabricated APRs or projected yields presented as fact.
-- Server-verify any claim eligibility.
-
-## Definition of done
-- `npm run dev`: connected holder sees real accrued revenue share + protocol distribution/burn data; claim flow works if supported, else honest accrual view.
-- All states designed; zero console errors; responsive. `npm run build` clean.
-- Run the **completionist** subagent. Report exactly what's live vs labeled-coming and the data sources.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/wow-sprint/17-holder-rewards-surface.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tasks/wow-sprint/18-marketplace-crosslinking.md b/tasks/wow-sprint/18-marketplace-crosslinking.md
deleted file mode 100644
index bf0ba9299..000000000
--- a/tasks/wow-sprint/18-marketplace-crosslinking.md
+++ /dev/null
@@ -1,39 +0,0 @@
-# Task: Wire the marketplace ↔ agent profiles + add sorting/filtering
-
-CLAUDE.md: "A marketplace that doesn't link to agent profiles is half-built."
-Make the marketplace a connected, navigable system.
-
-## Anchor files
-- Marketplace: `pages/marketplace.html`, `src/marketplace.js`, `src/marketplace-lobby.js`, `src/marketplace-detail.js`. API: `api/marketplace/`, `api/agents/`, `api/agent-3d/`.
-- Agent profiles: `pages/agent-detail.html` / `pages/agent-home.html`, `src/agent-detail.js`, `src/agent-home.js`, `src/agents-directory.js`.
-
-## What to build
-1. **Bidirectional links** — every marketplace card links to the real agent profile/detail; every agent profile links back to its marketplace listing and to related agents (same creator / category). No dead cards.
-2. **Sorting** — sort by recent, popularity/usage, price, name. Real fields from the API; persist the choice in the URL query so it's shareable and survives reload.
-3. **Filtering** — by category/capability/price range, driven by real data. Combine with sort. Reflect active filters in the URL.
-4. **Search** — debounced text search over real listings.
-5. **Cross-pollination** — on an agent profile, surface "more from this creator" and "similar agents" using real data relationships.
-6. **States** — loading skeletons, empty (no results → clear filters / create CTA), error (retry). Reuse design tokens.
-
-## Constraints
-- Real API data only — no sample agent arrays. If the marketplace API lacks a sort/filter field, add it to the endpoint rather than faking client-side on fake data.
-- URL is the source of truth for sort/filter/search (back button works).
-
-## Definition of done
-- `npm run dev` → `/marketplace`: sort + filter + search work on real data, reflected in URL; every card navigates to a real profile; profiles link back + show related agents.
-- All states designed; zero console errors; responsive. `npm run build` clean.
-- Run the **completionist** subagent. Report the new links, sort/filter fields, and any API changes.
-
-<!-- AUTO:self-delete-on-complete -->
-
----
-
-## ✅ On completion — delete this file
-
-This file is a unit of work, not a permanent doc. The moment every item above is **built, wired, verified, and committed** to the "Definition of done" in the repo-root `CLAUDE.md`, remove it in the same change:
-
-```bash
-git rm "tasks/wow-sprint/18-marketplace-crosslinking.md"
-```
-
-Stage the deletion alongside your implementation and include it in the completion commit. This directory is the backlog: a file that still exists is unfinished work; a file that is gone has shipped. Do not delete early, and never leave a completed prompt behind.
diff --git a/tests/api/irl-pins-anchor-pose.test.js b/tests/api/irl-pins-anchor-pose.test.js
index 8e0e9a96b..5de3e1bc5 100644
--- a/tests/api/irl-pins-anchor-pose.test.js
+++ b/tests/api/irl-pins-anchor-pose.test.js
@@ -65,9 +65,6 @@ vi.mock('../../api/_lib/granite-guardian.js', () => ({
decide: vi.fn(),
}));
-// Fire-and-forget realtime publish must never touch the network in a test.
-vi.mock('../../api/_lib/irl-publish.js', () => ({ publishIrlPin: vi.fn(async () => {}) }));
-
const { default: handler } = await import('../../api/irl/pins.js');
const ORIGIN = { lat: 40.7128, lng: -74.006 };
diff --git a/tests/api/irl-pins-bbox-auth.test.js b/tests/api/irl-pins-bbox-auth.test.js
deleted file mode 100644
index baf1c2e17..000000000
--- a/tests/api/irl-pins-bbox-auth.test.js
+++ /dev/null
@@ -1,138 +0,0 @@
-// GET /api/irl/pins — location-scrape guards.
-//
-// Two protections, proven here:
-// 1. The bbox window feed (which returns many pins over a multi-km box) is
-// INTERNAL-ONLY. It hydrates the Colyseus irl_world room server-to-server and
-// must reject any caller that doesn't present the shared multiplayer secret —
-// otherwise it's a one-call bulk download of every placement's exact GPS.
-// 2. The public nearby feed is IP rate-limited, so the precise-coordinate feed
-// can't be systematically gridded into a global location scrape.
-// DB / auth / limiter are mocked so the suite stays offline.
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-const PIN = {
- id: 'pin-1', user_id: 'owner-1', device_token: 'dev-1', agent_id: null,
- lat: 40.7128, lng: -74.006, heading: 0,
- avatar_url: null, avatar_name: 'Aria', caption: 'hi', x402_endpoint: null,
- placed_at: '2026-01-01T00:00:00Z', view_count: 0,
- anchor_height_m: null, anchor_yaw_deg: null, anchor_quat: null,
- gps_accuracy_m: null, altitude_m: null, anchor_source: null, avatar_version: 0,
-};
-
-// Any pin SELECT (nearby or bbox) carries `FROM irl_pins` + `lat BETWEEN`; return
-// one in-range pin for those and [] for everything else (ensureTable DDL).
-const sqlMock = vi.fn((strings) => {
- const q = Array.isArray(strings) ? strings.join(' ') : String(strings);
- if (/FROM\s+irl_pins/i.test(q) && /lat BETWEEN/i.test(q)) return Promise.resolve([PIN]);
- return Promise.resolve([]);
-});
-vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
-
-vi.mock('../../api/_lib/auth.js', () => ({ getSessionUser: vi.fn(async () => null) }));
-
-let publicVerdict = { success: true, reset: Date.now() + 60_000 };
-vi.mock('../../api/_lib/rate-limit.js', () => ({
- limits: { publicIp: vi.fn(async () => publicVerdict) },
- clientIp: () => '127.0.0.1',
-}));
-
-const SECRET = 'test-mp-secret';
-const { default: handler } = await import('../../api/irl/pins.js');
-
-function makeRes() {
- return {
- statusCode: 200,
- _h: {},
- headersSent: false,
- writableEnded: false,
- setHeader(k, v) { this._h[k.toLowerCase()] = v; },
- getHeader(k) { return this._h[k.toLowerCase()]; },
- end(body) { this.writableEnded = true; this._body = body; },
- };
-}
-async function get({ query = {}, headers = {} } = {}) {
- const res = makeRes();
- await handler({ url: '/api/irl/pins', method: 'GET', headers: { host: 'x', ...headers }, query }, res);
- let parsed = null;
- try { parsed = JSON.parse(res._body); } catch {}
- return { res, body: parsed };
-}
-function ranPinSelect() {
- return sqlMock.mock.calls.some(([s]) => {
- const q = Array.isArray(s) ? s.join(' ') : String(s);
- return /FROM\s+irl_pins/i.test(q) && /lat BETWEEN/i.test(q);
- });
-}
-
-beforeEach(() => {
- sqlMock.mockClear();
- publicVerdict = { success: true, reset: Date.now() + 60_000 };
- process.env.MULTIPLAYER_SHARED_SECRET = SECRET;
-});
-
-describe('GET /api/irl/pins?bbox — internal-only', () => {
- it('403s a bbox request with no internal header and never queries pins', async () => {
- const { res } = await get({ query: { bbox: '40.70,-74.02,40.73,-73.99' } });
- expect(res.statusCode).toBe(403);
- expect(ranPinSelect()).toBe(false);
- });
-
- it('403s a bbox request with a wrong internal secret', async () => {
- const { res } = await get({
- query: { bbox: '40.70,-74.02,40.73,-73.99' },
- headers: { 'x-mp-internal': 'not-the-secret' },
- });
- expect(res.statusCode).toBe(403);
- expect(ranPinSelect()).toBe(false);
- });
-
- it('200s with the window pins when the correct secret is presented', async () => {
- const { res, body } = await get({
- query: { bbox: '40.70,-74.02,40.73,-73.99' },
- headers: { 'x-mp-internal': SECRET },
- });
- expect(res.statusCode).toBe(200);
- expect(Array.isArray(body.pins)).toBe(true);
- expect(body.pins[0].id).toBe('pin-1');
- expect(ranPinSelect()).toBe(true);
- });
-
- it('400s a bbox larger than the ~0.2° ceiling even with the secret', async () => {
- const { res, body } = await get({
- query: { bbox: '40.0,-75.0,41.0,-74.0' }, // 1° box
- headers: { 'x-mp-internal': SECRET },
- });
- expect(res.statusCode).toBe(400);
- expect(body.error).toMatch(/too large/);
- expect(ranPinSelect()).toBe(false);
- });
-
- it('does not rate-limit the internal hydration path', async () => {
- const { limits } = await import('../../api/_lib/rate-limit.js');
- limits.publicIp.mockClear();
- await get({ query: { bbox: '40.70,-74.02,40.73,-73.99' }, headers: { 'x-mp-internal': SECRET } });
- expect(limits.publicIp).not.toHaveBeenCalled();
- });
-});
-
-describe('GET /api/irl/pins — public nearby feed is rate-limited', () => {
- it('200s a normal nearby query and consults the public limiter', async () => {
- const { limits } = await import('../../api/_lib/rate-limit.js');
- limits.publicIp.mockClear();
- const { res, body } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '150' } });
- expect(res.statusCode).toBe(200);
- expect(body.pins[0].id).toBe('pin-1');
- // Owner identifiers are never projected into the public feed.
- expect(body.pins[0]).not.toHaveProperty('user_id');
- expect(body.pins[0]).not.toHaveProperty('device_token');
- expect(limits.publicIp).toHaveBeenCalledTimes(1);
- });
-
- it('429s the nearby feed when the public limiter is exhausted, before any DB read', async () => {
- publicVerdict = { success: false, reset: Date.now() + 30_000 };
- const { res } = await get({ query: { lat: '40.7128', lng: '-74.006', radius: '150' } });
- expect(res.statusCode).toBe(429);
- expect(ranPinSelect()).toBe(false);
- });
-});
diff --git a/tests/api/irl-pins-outfit.test.js b/tests/api/irl-pins-outfit.test.js
index ea239ac7e..9f3db884b 100644
--- a/tests/api/irl-pins-outfit.test.js
+++ b/tests/api/irl-pins-outfit.test.js
@@ -9,10 +9,9 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-// Hoisted spies so the vi.mock factories (which hoist above imports) can close
-// over them. bakeSpy stands in for the real GLB bake+upload; emitSpy for the D1
-// fan-out hook.
-const { bakeSpy, emitSpy } = vi.hoisted(() => ({ bakeSpy: vi.fn(), emitSpy: vi.fn() }));
+// Hoisted spy so the vi.mock factory (which hoists above imports) can close over
+// it. bakeSpy stands in for the real GLB bake+upload.
+const { bakeSpy } = vi.hoisted(() => ({ bakeSpy: vi.fn() }));
// Content-addressed SQL mock: ensureTable DDL → []; the WHERE-id SELECT returns
// the current pin (null → not found); the outfit UPDATE echoes the new look with
@@ -62,8 +61,6 @@ vi.mock('../../api/_lib/irl-bake.js', () => ({
)),
}));
-vi.mock('../../api/_lib/irl-realtime.js', () => ({ emitPinUpdated: (...a) => emitSpy(...a) }));
-
const { default: handler } = await import('../../api/irl/pins.js');
const BAKED_URL = 'https://three.ws/cdn/irl/pins/pin-1/abc1234567890def.glb';
@@ -98,7 +95,6 @@ beforeEach(() => {
sqlMock.mockClear();
bakeSpy.mockReset();
bakeSpy.mockResolvedValue({ url: BAKED_URL });
- emitSpy.mockReset();
pinRow = {
id: 'pin-1',
user_id: 'owner-uuid',
@@ -167,9 +163,6 @@ describe('PATCH /api/irl/pins outfit — owner re-skin persists for everyone', (
expect(body.pin.avatar_url).toBe(BAKED_URL);
expect(body.pin.avatar_version).toBe(1);
expect(body.pin.avatar_manifest).toEqual(manifest);
- // Realtime fan-out fired with the persisted row.
- expect(emitSpy).toHaveBeenCalledTimes(1);
- expect(emitSpy.mock.calls[0][0]).toMatchObject({ id: 'pin-1', avatar_url: BAKED_URL, avatar_version: 1 });
});
it('re-bakes from the stored base on a later edit (never stacks on the prior bake)', async () => {
@@ -191,7 +184,6 @@ describe('PATCH /api/irl/pins outfit — owner re-skin persists for everyone', (
expect(bakeSpy).not.toHaveBeenCalled(); // nothing bakeable → skip the bake
expect(body.pin.avatar_url).toBe('/api/avatars/av-1/glb'); // served base again
expect(body.pin.avatar_version).toBe(1); // still a versioned change
- expect(emitSpy).toHaveBeenCalledTimes(1);
});
it('502s and does not persist when the bake throws', async () => {
@@ -200,6 +192,5 @@ describe('PATCH /api/irl/pins outfit — owner re-skin persists for everyone', (
expect(res.statusCode).toBe(502);
expect(body.error).toMatch(/could not bake/i);
expect(ranOutfitUpdate()).toBe(false);
- expect(emitSpy).not.toHaveBeenCalled();
});
});
diff --git a/tests/api/irl-pins-room.test.js b/tests/api/irl-pins-room.test.js
index d9a0897f9..a28cae2c6 100644
--- a/tests/api/irl-pins-room.test.js
+++ b/tests/api/irl-pins-room.test.js
@@ -60,9 +60,12 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
vi.mock('../../api/_lib/granite-guardian.js', () => ({
guardianConfig: () => ({ configured: false }), assess: vi.fn(), decide: vi.fn(),
}));
-vi.mock('../../api/_lib/irl-publish.js', () => ({ publishIrlPin: vi.fn(async () => {}) }));
-const { default: handler } = await import('../../api/irl/pins.js');
+// Import the handler fresh per test (after resetModules) so this file's db.js
+// mock deterministically backs the handler even when another pins.js-importing
+// test ran first in the same worker — otherwise a leaked sibling mock (which
+// doesn't echo the room columns) makes these assertions flake. See beforeEach.
+let handler;
const ORIGIN = { lat: 40.7128, lng: -74.006 };
@@ -96,7 +99,11 @@ const room = (over = {}) => ({
originYawDeg: 0, relEast: 2, relNorth: 1, ...over,
});
-beforeEach(() => { sqlMock.mockClear(); sessionUser = null; nearbyRow = null; });
+beforeEach(async () => {
+ sqlMock.mockClear(); sessionUser = null; nearbyRow = null;
+ vi.resetModules(); // drop any pins.js a prior file cached under its own db.js mock
+ ({ default: handler } = await import('../../api/irl/pins.js'));
+});
describe('POST /api/irl/pins — room frame persistence', () => {
it('stores room id + exact offset + origin when the client places into a room', async () => {
diff --git a/tests/api/irl-report.test.js b/tests/api/irl-report.test.js
index 7ebf6023e..2c12d0e66 100644
--- a/tests/api/irl-report.test.js
+++ b/tests/api/irl-report.test.js
@@ -40,13 +40,6 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: () => '127.0.0.1',
}));
-// D1 realtime fan-out — spied so we can prove a threshold hide pushes a live
-// pin:remove into the pin's geocell room (and that a sub-threshold report does not).
-const publishIrlPin = vi.fn(async () => ({ delivered: false }));
-vi.mock('../../api/_lib/irl-publish.js', () => ({
- publishIrlPin: (...a) => publishIrlPin(...a),
-}));
-
const { default: handler } = await import('../../api/irl/report.js');
function makeRes() {
@@ -69,7 +62,6 @@ async function report(body) {
beforeEach(() => {
sqlMock.mockClear();
- publishIrlPin.mockClear();
pinRow = { id: 'pin-1', user_id: null, device_token: 'owner-dev', hidden_at: null, lat: 40.7128, lng: -74.006 };
distinctReporters = 1;
hideUpdated = true;
@@ -107,29 +99,11 @@ describe('POST /api/irl/report', () => {
expect(body.hidden).toBe(true);
});
- it('emits a D1 pin:remove into the geocell room when the threshold hides a pin', async () => {
- distinctReporters = 3;
- await report({ pinId: 'pin-1', reason: 'harassment', deviceToken: 'dev-Z' });
- expect(publishIrlPin).toHaveBeenCalledTimes(1);
- const [type, geocell, payload] = publishIrlPin.mock.calls[0];
- expect(type).toBe('pin:remove');
- expect(typeof geocell).toBe('string');
- expect(geocell.length).toBeGreaterThan(0);
- expect(payload).toEqual({ id: 'pin-1' });
- });
-
- it('does NOT emit a pin:remove for a sub-threshold report', async () => {
- distinctReporters = 1;
- await report({ pinId: 'pin-1', reason: 'spam', deviceToken: 'dev-X' });
- expect(publishIrlPin).not.toHaveBeenCalled();
- });
-
- it('does NOT re-emit pin:remove when the guarded hide UPDATE flips nothing (race)', async () => {
+ it('reports the pin as not hidden when the guarded hide UPDATE flips nothing (race)', async () => {
distinctReporters = 3;
hideUpdated = false; // a concurrent report already set hidden_at
const { body } = await report({ pinId: 'pin-1', reason: 'scam', deviceToken: 'dev-W' });
expect(body.hidden).toBe(false);
- expect(publishIrlPin).not.toHaveBeenCalled();
});
it('a single reporter cannot hide a pin (one distinct token, threshold not met)', async () => {