Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(thumbnails): record that thumbnailUrl returns null when object storage is unset
nirholas3f5c9748b010
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b543561c8..3ba84cc13 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The $THREE economy dashboard no longer errors out on an odd date range**: Asking the public $THREE economy stats endpoint for a window it could not read (a non-numeric range, or one longer than ten years) returned a server error instead of an answer. It now replies with a clear message for a range it cannot parse, caps an oversized one at ten years of history, and treats a blank range as all-time again. The creator earnings ledger does the same for a bad page cursor. `[fix]`- **The $THREE price quote survives an out-of-range dollar amount, and the payment audit log is admin-only for real**: The public $THREE price endpoint converts a dollar amount into a token amount. Because $THREE trades well under a cent, a dollar figure large enough to overflow what a number can hold turned that conversion into a server error, and every such request also filed a false internal alert. It now answers plainly that the amount is out of range. The token amount it quotes is also computed from the exact price printed beside it, so the two can no longer disagree when the live price refreshes partway through a request. Separately, the settled-payment audit log checked admin wallets with its own copy of the rule, comparing Solana addresses without regard to capitalisation. Solana addresses are case-sensitive, so a lookalike address that differed only in capitalisation would have been accepted; the log now uses the platform-wide admin check, which compares Solana addresses exactly and also recognises an admin who signed in with a linked wallet. `[fix, security]`- **The $THREE rider pass now recognises the wallets that paid for it**: The rider pass is a $THREE gate: you qualify either by holding $THREE or by sending 8,000 of it to the rider vault. Only the first half worked. The check answered purely from what a wallet currently holds, so anyone who bought a pass, and therefore no longer held the tokens they had just sent, was told they had no pass. The payments the vault recorded were written to the database and never read by anything. Both sources are now consulted, and a positive answer from either one stands on its own, so a paid pass still verifies while the chain node is unreachable and a holder pass still verifies during a database outage. A single transaction carrying payments from two different wallets used to fail outright and be retried forever by the payment listener, granting neither wallet a pass; every payer in a batch is now credited. The config the rider client loads at startup answered with a page of empty values when the deployment was not set up, which crashed the client with an unexplained error; it now says plainly that the feature is not configured. Repeating the address in the query string returned a server error and now returns a normal validation message. `[fix]`+- **The agent showcase pages all the way through, and the strategy board ranks the whole marketplace**: Three fixes to public read surfaces. Paging the ERC-8004 agent showcase past the first page could repeat a row forever or quietly skip one, because the cursor rounded the registration timestamp to the millisecond while the index stores microseconds, and an agent whose registry event carried no timestamp at all fell out of every page after the first. Both are fixed, and asking for a fractional number of results now returns a page instead of a server error. The published strategy board's default 'performance' order was ranking only the most recently published slice, so a proven, high-return strategy could sit invisible behind newer unproven ones; it now ranks the whole published pool before trimming to your page. And /sitemap.xml no longer answers a POST or a DELETE with the sitemap. (`/showcase`) `[fix]`- **The agent wallet MCP server now quotes its own address when it asks an agent to pay**: Agents that connect to the wallet server at /api/mcp-agent without a three.ws account can pay per call in USDC instead. The payment request it handed back named the main three.ws MCP server, not itself, so a paying agent signed a payment scoped to an endpoint it had not called and service directories listed the wallet server under the wrong description and tool list. It now describes itself: its own address, its own wallet-and-payments summary, and a directory example that only searches for services rather than spending anything. Separately, the one-sentence agent builder no longer mangles accented names when it suggests a handle: Munz now becomes munz rather than mu-nz. (`/docs/mcp-agent`) `[fix]`- **The creations gallery now counts every creation a creator has made, and pages all the way to the end**: The gallery ranked creators and paged the feed over only the newest 120 creations, however many the feed actually held. A creator's older work was invisible in their profile count, the top-creator board scored people on a fraction of their output, and scrolling the gallery dead-ended early with items still left to show. It now reads the full feed depth it always meant to, and does it in two database round trips instead of two per item, so the deeper read loads faster than the shallow one did. (`/creations`) `[fix, improvement]`- **The KOL, Loom and marketplace MCP servers now tell you why a call failed, and ship runnable examples**: When a market-data provider was rate-limited, these servers passed back only a bare code like provider_unavailable and threw away the sentence explaining it. They now surface the full reason. The KOL portfolio tool used to answer a provider outage with an empty card that read as a quiet wallet with no trades; it now reports the outage as an outage, so nobody sizes up a trader from a blank. The KOL and Loom packages also gained runnable examples that talk to the live public API, and the naming SDK now answers an unregistered .eth name the same way it answers an unclaimed .sol one, with data instead of an exception. `[fix, sdk]`diff --git a/api/showcase.js b/api/showcase.jsindex 4c3b283c3..13df110ce 100644--- a/api/showcase.js+++ b/api/showcase.js@@ -1,8 +1,14 @@// GET /api/showcase — public directory of ERC-8004 agents with 3D avatars.//// Reads from `erc8004_agents_index` (populated by api/cron/erc8004-crawl.js).-// Keyset pagination on (registered_at, chain_id, agent_id) — stable under-// concurrent inserts and backed by the `erc8004_agents_has3d_time` index.+// Keyset pagination on (sort_ts, chain_id, agent_id), stable under concurrent+// inserts and backed by the `erc8004_agents_has3d_time` index. `sort_ts` is+// `registered_at` with NULL folded to -infinity, and the cursor carries it as+// Postgres text: two details that keep the key TOTAL. A NULL registered_at+// (a third of the crawled index) would otherwise make the row-comparison NULL+// and drop that agent from every page after the first, and a cursor rendered+// through a JS Date would truncate the stored microseconds, which repeats or+// skips rows on the boundary depending on the sort direction.import { sql } from './_lib/db.js';import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';@@ -27,7 +33,7 @@ export default wrap(async (req, res) => {const decoded = cursor ? decodeCursor(cursor) : null;if (cursor && !decoded) return error(res, 400, 'validation_error', 'invalid cursor');- const cursorAt = decoded?.registeredAt || null;+ const cursorAt = decoded?.sortTs || null;const cursorChain = decoded?.chainId ?? null;const cursorAgent = decoded?.agentId || null;@@ -36,33 +42,35 @@ export default wrap(async (req, res) => {? await sql`SELECT chain_id, agent_id, owner, registry, agent_uri,name, description, image, glb_url, services, x402_support,- registered_block, registered_tx, registered_at+ registered_block, registered_tx, registered_at,+ COALESCE(registered_at, '-infinity'::timestamptz)::text AS sort_tsFROM erc8004_agents_indexWHERE active = trueAND has_3d = trueAND chain_id = ANY(${chainIds}::int[])AND (${cursorAt}::timestamptz IS NULL- OR (registered_at, chain_id, agent_id) <+ OR (COALESCE(registered_at, '-infinity'::timestamptz), chain_id, agent_id) <(${cursorAt}::timestamptz, ${cursorChain}::int, ${cursorAgent}::text))- ORDER BY registered_at DESC NULLS LAST, chain_id DESC, agent_id DESC+ ORDER BY COALESCE(registered_at, '-infinity'::timestamptz) DESC, chain_id DESC, agent_id DESCLIMIT ${limit + 1}`: await sql`SELECT chain_id, agent_id, owner, registry, agent_uri,name, description, image, glb_url, services, x402_support,- registered_block, registered_tx, registered_at+ registered_block, registered_tx, registered_at,+ COALESCE(registered_at, '-infinity'::timestamptz)::text AS sort_tsFROM erc8004_agents_indexWHERE active = trueAND has_3d = trueAND chain_id = ANY(${chainIds}::int[])AND (${cursorAt}::timestamptz IS NULL- OR (registered_at, chain_id, agent_id) >+ OR (COALESCE(registered_at, '-infinity'::timestamptz), chain_id, agent_id) >(${cursorAt}::timestamptz, ${cursorChain}::int, ${cursorAgent}::text))- ORDER BY registered_at ASC NULLS FIRST, chain_id ASC, agent_id ASC+ ORDER BY COALESCE(registered_at, '-infinity'::timestamptz) ASC, chain_id ASC, agent_id ASCLIMIT ${limit + 1}`;@@ -98,7 +106,9 @@ function parseParams(sp) {return { error: 'sort must be newest | oldest' };}- let limit = Number(sp.get('limit')) || DEFAULT_LIMIT;+ // LIMIT is a bigint to Postgres: floor before it gets there, or a fractional+ // ?limit=1.5 becomes `LIMIT 2.5` and fails the query with 22P02.+ let limit = Math.floor(Number(sp.get('limit')));if (!Number.isFinite(limit) || limit < 1) limit = DEFAULT_LIMIT;if (limit > MAX_LIMIT) limit = MAX_LIMIT;@@ -154,19 +164,20 @@ function shapeAgent(row) {};}+// The cursor carries `sort_ts` verbatim as Postgres rendered it, so it round-trips+// at full microsecond precision and survives a NULL registered_at (`-infinity`).function encodeCursor(row) {- const at = row.registered_at ? new Date(row.registered_at).toISOString() : '';- const payload = `${at}|${row.chain_id}|${row.agent_id}`;+ const payload = `${row.sort_ts}|${row.chain_id}|${row.agent_id}`;return Buffer.from(payload, 'utf8').toString('base64url');}function decodeCursor(cursor) {try {const payload = Buffer.from(cursor, 'base64url').toString('utf8');- const [registeredAt, chainIdStr, agentId] = payload.split('|');+ const [sortTs, chainIdStr, agentId] = payload.split('|');const chainId = Number(chainIdStr);- if (!registeredAt || !Number.isInteger(chainId) || !agentId) return null;- return { registeredAt, chainId, agentId };+ if (!sortTs || !Number.isInteger(chainId) || !agentId) return null;+ return { sortTs, chainId, agentId };} catch {return null;}diff --git a/api/sitemap.js b/api/sitemap.jsindex 935fe455f..ef40f97a2 100644--- a/api/sitemap.js+++ b/api/sitemap.js@@ -11,6 +11,7 @@import { sql } from './_lib/db.js';import { env } from './_lib/env.js';+import { method } from './_lib/http.js';const ORIGIN = env.APP_ORIGIN;@@ -54,6 +55,10 @@ async function newestCreated(table, where = '') {}export default async function handler(req, res) {+ // A crawler surface is GET (and HEAD) only. Without this, a POST or DELETE+ // got the sitemap back with a 200, which is a lie about what the route does.+ if (!method(req, res, ['GET'])) return;+const [agentsTs, avatarsTs, widgetsTs, usersTs, subdomainsTs] = await Promise.all([newestCreated('agent_identities', 'deleted_at is null and is_public = true'),newestTimestamp('avatars', "visibility = 'public' and deleted_at is null"),diff --git a/api/sns-subdomain.js b/api/sns-subdomain.jsindex 18f8d1b87..052362641 100644--- a/api/sns-subdomain.js+++ b/api/sns-subdomain.js@@ -80,7 +80,7 @@ async function handleCheck(req, res) {async function handleMint(req, res, auth) {if (!hasOwnerKey()) {- return error(res, 503, 'config_missing', 'subdomain minting unavailable — platform owner key not configured');+ return error(res, 503, 'config_missing', 'subdomain minting unavailable: the platform owner key is not configured');}const body = await readJson(req).catch(() => ({}));@@ -97,7 +97,7 @@ async function handleMint(req, res, auth) {const agentSol = agent.meta?.solana_address;if (!agentSol) {- return error(res, 412, 'agent_missing_wallet', 'agent has no solana wallet — provision one via POST /api/agents/:id/solana');+ return error(res, 412, 'agent_missing_wallet', 'agent has no solana wallet; provision one via POST /api/agents/:id/solana');}let labelInput = typeof body?.label === 'string' && body.label.trim()diff --git a/api/strategies.js b/api/strategies.jsindex 644a2a287..e7eae22c7 100644--- a/api/strategies.js+++ b/api/strategies.js@@ -36,6 +36,12 @@ async function resolveAuth(req) {const LIST_SORTS = new Set(['recent', 'forks', 'equips', 'performance']);+// "performance" is ranked in JS from real closed positions, so the SQL page has to+// be a candidate POOL rather than the answer: ordering by published_at and taking+// `limit` would hide a proven, high-ROI strategy behind newer unproven ones and+// still call the result a performance ranking. Same pool the leaderboard scans.+const PERFORMANCE_POOL = 200;+// Real live performance for a set of strategies, aggregated from real closed// on-chain positions across every equip of each strategy. Returns a map id→stats.// A strategy with 0 closed positions is "unproven" (proven:false) — never faked.@@ -146,7 +152,7 @@ async function handleList(req, res, auth) {${author ? sql`AND owner_id = ${author}` : sql``}${q ? sql`AND (name ILIKE ${'%' + q + '%'} OR description ILIKE ${'%' + q + '%'})` : sql``}ORDER BY ${sort === 'forks' ? sql`forks_count DESC` : sort === 'equips' ? sql`equips_count DESC` : sql`published_at DESC`}- LIMIT ${limit}+ LIMIT ${sort === 'performance' ? PERFORMANCE_POOL : limit}`;const perf = await performanceByStrategy(rows.map((r) => r.id));const names = await ownerNames([...new Set(rows.map((r) => r.owner_id))]);@@ -154,12 +160,14 @@ async function handleList(req, res, auth) {// "performance" sort ranks proven strategies by ROI, then unproven by recency —// a real, honest order (no synthetic curve can climb it).if (sort === 'performance') {- strategies = strategies.sort((a, b) => {- const ap = a.performance.proven ? 1 : 0, bp = b.performance.proven ? 1 : 0;- if (ap !== bp) return bp - ap;- if (ap && bp) return (b.performance.roi_pct ?? -1e9) - (a.performance.roi_pct ?? -1e9);- return new Date(b.published_at || 0) - new Date(a.published_at || 0);- });+ strategies = strategies+ .sort((a, b) => {+ const ap = a.performance.proven ? 1 : 0, bp = b.performance.proven ? 1 : 0;+ if (ap !== bp) return bp - ap;+ if (ap && bp) return (b.performance.roi_pct ?? -1e9) - (a.performance.roi_pct ?? -1e9);+ return new Date(b.published_at || 0) - new Date(a.published_at || 0);+ })+ .slice(0, limit);}return json(res, 200, { data: { scope, sort, strategies } });}diff --git a/data/changelog.json b/data/changelog.jsonindex 8d9abca91..2c1ec19bf 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-16",+ "title": "The agent showcase pages all the way through, and the strategy board ranks the whole marketplace",+ "summary": "Three fixes to public read surfaces. Paging the ERC-8004 agent showcase past the first page could repeat a row forever or quietly skip one, because the cursor rounded the registration timestamp to the millisecond while the index stores microseconds, and an agent whose registry event carried no timestamp at all fell out of every page after the first. Both are fixed, and asking for a fractional number of results now returns a page instead of a server error. The published strategy board's default 'performance' order was ranking only the most recently published slice, so a proven, high-return strategy could sit invisible behind newer unproven ones; it now ranks the whole published pool before trimming to your page. And /sitemap.xml no longer answers a POST or a DELETE with the sitemap.",+ "tags": [+ "fix"+ ],+ "link": "/showcase"+ },{"date": "2026-08-16","title": "Token sentiment reads real pump.fun commentary again",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex b1c264e55..caba3e5fb 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -3385,15 +3385,17 @@ Public directory of ERC-8004 agents with 3D avatars, for homepage and gallery us**Query parameters**-| Parameter | Type | Description |-| --------- | ------- | ------------------------------------------------------------------ |-| `net` | string | `mainnet`, `testnet`, or `all` (default: `all`) |-| `sort` | string | `newest` or `oldest` |-| `chain` | integer | Filter by chain ID |-| `limit` | integer | Max results (default: 20) |-| `cursor` | string | Keyset pagination cursor (`registered_at,chain_id,agent_id` tuple) |+| Parameter | Type | Description |+| --------- | ------- | --------------------------------------------------------------------------------- |+| `net` | string | `mainnet`, `testnet`, or `all` (default: `mainnet`) |+| `sort` | string | `newest` or `oldest` (default: `newest`) |+| `chain` | integer | Comma-separated chain IDs. Overrides `net`; an unknown ID is a `validation_error`. |+| `limit` | integer | Max results, 1 to 60 (default: 24). A fractional value is floored. |+| `cursor` | string | Keyset cursor from the previous page's `next_cursor`. Opaque, pass it back verbatim. |++**Response:** `{ agents, total, next_cursor }`, each agent shaped as in `/api/explore`. `total` is the count for the current filter, not the page. `next_cursor` is `null` on the last page.-**Response:** Same shape as `/api/explore`. Cursor encodes the full keyset tuple for stable pagination under concurrent inserts.+The cursor encodes the full keyset tuple (registration timestamp, chain ID, agent ID) so pagination stays stable while the crawler inserts. Two properties matter if you are reproducing it: the timestamp is carried at Postgres' own microsecond precision (re-rendering it through a millisecond clock repeats or skips the boundary row), and an agent whose registry event carried no timestamp sorts under `-infinity`, at the end of `newest` and the start of `oldest`, rather than dropping out of the walk. A cursor that does not decode is a `400` `validation_error`, never a silent reset to page one.---@@ -6882,7 +6884,7 @@ Paginated list endpoints use `limit`/`offset` query parameters unless noted otheGET /api/v1/pump/launches?limit=24&offset=24```-`/api/explore` and `/api/showcase` use keyset (cursor-based) pagination for stability: pass the returned `cursor` value as the `cursor` query parameter on the next request. `/api/agent-actions` and `/api/users/me/feed` are cursor-based too (`cursor` / `before` timestamps).+`/api/explore` and `/api/showcase` use keyset (cursor-based) pagination for stability: pass the value the previous page returned (`cursor` on explore, `next_cursor` on showcase) as the `cursor` query parameter on the next request. `/api/agent-actions` and `/api/users/me/feed` are cursor-based too (`cursor` / `before` timestamps).---diff --git a/docs/avatar-thumbnails.md b/docs/avatar-thumbnails.mdindex d7b0a8ce1..a4ce1a0f3 100644--- a/docs/avatar-thumbnails.md+++ b/docs/avatar-thumbnails.md@@ -45,8 +45,17 @@ import { thumbnailUrl } from './_lib/r2.js';thumbnailUrl(null) // → nullthumbnailUrl('https://three.ws/avatars/x_og.png') // → null (legacy, always 404s)thumbnailUrl('thumb/abc.png') // → https://<cdn>/thumb/abc.png+thumbnailUrl('thumb/abc.png') // → null (S3_PUBLIC_DOMAIN unset)```+That last case is why the helper is built on `publicUrlOrNull()` rather than bare+`publicUrl()`: reading `env.S3_PUBLIC_DOMAIN` throws on a deployment without object+storage, and a single un-renderable key must not take down a whole list response.+It did: `/api/pulse` answered `502 pulse_failed` and `/api/search` answered+`503 not_configured` for every caller until both were pointed at the read-path+helper. Upload paths keep calling `publicUrl()`, where the throw is the correct+signal that there is nowhere to put the bytes.+Return `null` and let the surface render its designed placeholder. There were 43bare `publicUrl(<thumbnail key>)` call sites across 32 files — agent cards, themarketplace, explore, user profiles, leaderboards, and the image baked into on-chaindiff --git a/prompts/swarm-100/api-top-14.md b/prompts/swarm-100/api-top-14.mddeleted file mode 100644index 304c7039c..000000000--- a/prompts/swarm-100/api-top-14.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/*.js batch 14 (10 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/showcase.js-- api/sign.js-- api/sitemap.js-- api/skills-manifest.js-- api/sns-subdomain.js-- api/sns.js-- api/solana-rpc.js-- api/status.js-- api/strategies.js-- api/subscriptions.js--For every routed handler:--1. Exercise it with curl against the local server: the success path returns- real data with the correct status; malformed input returns a 4xx JSON- error, never a stack trace or an HTML error page; auth is enforced where- the code intends it; CORS matches neighboring handlers.-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed- responses, no unfinished markers. Errors are handled at the boundary and- internal code trusts itself.-3. Do not spend funds or sign anything on-chain while probing. Payment and- trading handlers get their validation and error paths exercised, never a- live settlement.--For every internal (non-routed) module:--4. Something must import it; if nothing does, delete it as dead code (verify- with a repo-wide grep first).-5. Its main path and one failure path must be covered in tests/; add the- missing test if not.--## Definition of done--- [ ] Every listed file has recorded evidence: a curl transcript for routed- handlers, a passing test or a deletion for internal modules.-- [ ] Zero hard-rule violations remain in these files.-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>- exits 0.--## Never blocked--| Blocker | Resolution (act, do not ask) |-|---|---|-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |-| Playwright browser missing | npx playwright install chromium |-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |--## Close out (required)--1. Verify every Definition of done line with the actual command output in- front of you. Never claim a line you did not verify.-2. Commit with explicit paths and a subject that describes the diff (house- style: type(scope): what changed and why a reader cares).-3. Delete this prompt file in that same commit:-- git rm prompts/swarm-100/api-top-14.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/public/changelog.json b/public/changelog.jsonindex f4c716eab..f6940f742 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T07:55:40.643Z",+ "generated_at": "2026-08-16T07:57:38.445Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -206,6 +206,16 @@"fix"]},+ {+ "date": "2026-08-16",+ "type": "update",+ "title": "The agent showcase pages all the way through, and the strategy board ranks the whole marketplace",+ "summary": "Three fixes to public read surfaces. Paging the ERC-8004 agent showcase past the first page could repeat a row forever or quietly skip one, because the cursor rounded the registration timestamp to the millisecond while the index stores microseconds, and an agent whose registry event carried no timestamp at all fell out of every page after the first. Both are fixed, and asking for a fractional number of results now returns a page instead of a server error. The published strategy board's default 'performance' order was ranking only the most recently published slice, so a proven, high-return strategy could sit invisible behind newer unproven ones; it now ranks the whole published pool before trimming to your page. And /sitemap.xml no longer answers a POST or a DELETE with the sitemap.",+ "link": "/showcase",+ "tags": [+ "fix"+ ]+ },{"date": "2026-08-16","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex a59563b2c..26ae5dec1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -158,6 +158,14 @@<category>fix</category><description>The rider pass is a $THREE gate: you qualify either by holding $THREE or by sending 8,000 of it to the rider vault. Only the first half worked. The check answered purely from what a wallet currently holds, so anyone who bought a pass, and therefore no longer held the tokens they had just sent, was told they had no pass. The payments the vault recorded were written to the database and never read by anything. Both sources are now consulted, and a positive answer from either one stands on its own, so a paid pass still verifies while the chain node is unreachable and a holder pass still verifies during a database outage. A single transaction carrying payments from two different wallets used to fail outright and be retried forever by the payment listener, granting neither wallet a pass; every payer in a batch is now credited. The config the rider client loads at startup answered with a page of empty values when the deployment was not set up, which crashed the client with an unexplained error; it now says plainly that the feature is not configured. Repeating the address in the query string returned a server error and now returns a normal validation message.</description></item>+ <item>+ <title>The agent showcase pages all the way through, and the strategy board ranks the whole marketplace</title>+ <link>https://three.ws/showcase</link>+ <guid isPermaLink="false">2026-08-16:The agent showcase pages all the way through, and the strategy board ranks the whole marketplace</guid>+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Three fixes to public read surfaces. Paging the ERC-8004 agent showcase past the first page could repeat a row forever or quietly skip one, because the cursor rounded the registration timestamp to the millisecond while the index stores microseconds, and an agent whose registry event carried no timestamp at all fell out of every page after the first. Both are fixed, and asking for a fractional number of results now returns a page instead of a server error. The published strategy board's default 'performance' order was ranking only the most recently published slice, so a proven, high-return strategy could sit invisible behind newer unproven ones; it now ranks the whole published pool before trimming to your page. And /sitemap.xml no longer answers a POST or a DELETE with the sitemap.</description>+ </item><item><title>The agent wallet MCP server now quotes its own address when it asks an agent to pay</title><link>https://three.ws/docs/mcp-agent</link>diff --git a/tests/api/showcase-keyset.test.js b/tests/api/showcase-keyset.test.jsnew file mode 100644index 000000000..d74ae0265--- /dev/null+++ b/tests/api/showcase-keyset.test.js@@ -0,0 +1,144 @@+// /api/showcase keyset pagination. The showcase pages the ERC-8004 agent index+// with a cursor, and the cursor is only as good as the sort key it encodes:+//+// - `registered_at` is nullable (a third of the crawled index has no date), so+// a row-comparison against a NULL sort key is NULL, not false, and the row+// falls out of every page after the first. The handler folds NULL to+// -infinity so the key is total.+// - Postgres stores microseconds; a cursor rendered through a JS Date keeps+// only milliseconds. Truncating the boundary repeats a row in ascending+// order (an infinite next-page loop for the client) and skips one in+// descending order. The cursor carries Postgres' own text rendering.+// - LIMIT is a bigint upstream, so a fractional ?limit= has to be floored+// before it becomes `LIMIT 2.5` and fails the query with 22P02.+//+// Network-free: the database and rate limiter are mocked, and what is under test+// is the cursor contract and the shape of the parameters the handler sends.++import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';+import { createServer } from 'node:http';++const DATED = {+ chain_id: 8453,+ agent_id: '46366',+ owner: '0xa17b6b1ae86f029a866b786672b03024ed504f7c',+ registry: '0x8004a169fb4a3325136eb29fa0ceb6d2e539a432',+ agent_uri: 'https://example.test/agent.json',+ name: 'Dated agent',+ description: null,+ image: null,+ glb_url: 'https://models.example.test/a.glb',+ services: [],+ x402_support: false,+ registered_block: '31000000',+ registered_tx: '0xabc',+ registered_at: '2026-05-02T00:11:14.638Z',+ sort_ts: '2026-05-02 00:11:14.638997+00',+};++// The crawler leaves registered_at NULL whenever the registry event carried no+// timestamp. Postgres renders the folded key as '-infinity'.+const UNDATED = {+ ...DATED,+ agent_id: '46333',+ name: 'Undated agent',+ registered_at: null,+ sort_ts: '-infinity',+};++// Every call the handler makes, as [strings, ...values]. The rows query is+// always first, the COUNT second.+const calls = [];+let rowsResult = [DATED, UNDATED];++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (...args) => {+ calls.push(args);+ return calls.length === 1 ? rowsResult : [{ count: rowsResult.length }];+ }),+ isDbUnavailableError: () => false,+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: 0 })) },+ clientIp: () => '127.0.0.1',+}));++let server;+let base;++beforeAll(async () => {+ const { default: handler } = await import('../../api/showcase.js');+ server = createServer((req, res) => handler(req, res));+ await new Promise((r) => server.listen(0, '127.0.0.1', r));+ base = `http://127.0.0.1:${server.address().port}`;+});++afterAll(() => server?.close());++beforeEach(() => {+ calls.length = 0;+ rowsResult = [DATED, UNDATED];+});++/** Values interpolated into the rows query, in order. */+const rowsParams = () => calls[0].slice(1);+const decode = (cursor) => Buffer.from(cursor, 'base64url').toString('utf8');++describe('/api/showcase keyset cursor', () => {+ it('carries the full microsecond sort key, not a millisecond JS Date', async () => {+ const r = await fetch(`${base}/api/showcase?limit=1`);+ expect(r.status).toBe(200);+ const body = await r.json();++ // Two rows came back for limit=1, so there is a next page.+ expect(body.agents).toHaveLength(1);+ expect(decode(body.next_cursor)).toBe('2026-05-02 00:11:14.638997+00|8453|46366');+ });++ it('pages past an agent with no registered_at instead of stranding it', async () => {+ rowsResult = [UNDATED, { ...UNDATED, agent_id: '46300' }];+ const r = await fetch(`${base}/api/showcase?sort=oldest&limit=1`);+ const body = await r.json();++ // The old encoder produced an empty timestamp here, which decoded to null+ // and answered the next page with a 400.+ expect(decode(body.next_cursor)).toBe('-infinity|8453|46333');++ calls.length = 0;+ const back = await fetch(`${base}/api/showcase?sort=oldest&limit=1&cursor=${body.next_cursor}`);+ expect(back.status).toBe(200);+ // The '-infinity' boundary reaches the query verbatim, so Postgres compares+ // it against the same folded key the ORDER BY uses.+ expect(rowsParams()).toContain('-infinity');+ });++ it('floors a fractional limit so LIMIT stays an integer', async () => {+ const r = await fetch(`${base}/api/showcase?limit=1.5`);+ expect(r.status).toBe(200);++ const limitParam = rowsParams().at(-1);+ expect(Number.isInteger(limitParam)).toBe(true);+ expect(limitParam).toBe(2); // floor(1.5) + 1 fetch-ahead row+ });++ it('falls back to the default limit for a limit that is not a number', async () => {+ await fetch(`${base}/api/showcase?limit=abc`);+ expect(rowsParams().at(-1)).toBe(25); // DEFAULT_LIMIT + 1+ });++ it('rejects a cursor that is not a decodable sort key', async () => {+ const r = await fetch(`${base}/api/showcase?cursor=%25%25%25`);+ expect(r.status).toBe(400);+ expect((await r.json()).error).toBe('validation_error');+ // Validation runs before any query: a bad cursor costs no database work.+ expect(calls).toHaveLength(0);+ });++ it('stops paging when the page is not full', async () => {+ rowsResult = [DATED];+ const body = await (await fetch(`${base}/api/showcase?limit=24`)).json();+ expect(body.next_cursor).toBeNull();+ expect(body.total).toBe(1);+ });+});diff --git a/tests/api/sitemap-index.test.js b/tests/api/sitemap-index.test.jsnew file mode 100644index 000000000..24bee6907--- /dev/null+++ b/tests/api/sitemap-index.test.js@@ -0,0 +1,93 @@+// The sitemap index at /sitemap.xml (api/sitemap.js), the first file Google and+// Bing fetch. It points at the six sub-sitemaps that api/sitemap/[type].js builds.+//+// Two things are pinned here:+//+// - It is a read surface. Before the method guard, a POST or a DELETE to+// /api/sitemap got a 200 and the full index back, which advertises write+// methods the route does not have.+// - Every sub-sitemap entry is emitted unconditionally, even when its lastmod+// probe returns nothing, so a crawler keeps a stable set of files to poll and+// content appearing later needs no deploy to become discoverable. A dead+// database degrades the dates, never the document.+//+// Network-free: the database is mocked.++import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';+import { createServer } from 'node:http';+import { XMLValidator } from 'fast-xml-parser';++const db = vi.hoisted(() => ({ queries: [], ts: '2026-08-01T10:00:00.000Z', fail: false }));++vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));++vi.mock('../../api/_lib/db.js', () => ({+ sql: Object.assign(() => Promise.resolve([]), {+ unsafe: (text) => {+ db.queries.push(text);+ if (db.fail) return Promise.reject(new Error('connection terminated'));+ return Promise.resolve([{ ts: db.ts }]);+ },+ }),+ isDbUnavailableError: () => false,+}));++let server;+let base;++beforeAll(async () => {+ const { default: handler } = await import('../../api/sitemap.js');+ server = createServer((req, res) => handler(req, res));+ await new Promise((r) => server.listen(0, '127.0.0.1', r));+ base = `http://127.0.0.1:${server.address().port}`;+});++afterAll(() => server?.close());++beforeEach(() => {+ db.queries.length = 0;+ db.fail = false;+});++describe('/api/sitemap index', () => {+ it('serves well-formed XML listing every sub-sitemap', async () => {+ const r = await fetch(`${base}/api/sitemap`);+ expect(r.status).toBe(200);+ expect(r.headers.get('content-type')).toContain('application/xml');+ expect(r.headers.get('cache-control')).toContain('s-maxage=600');++ const body = await r.text();+ expect(XMLValidator.validate(body)).toBe(true);+ for (const type of ['core', 'agents', 'avatars', 'widgets', 'profiles', 'news']) {+ expect(body).toContain(`<loc>https://three.ws/sitemap/${type}.xml</loc>`);+ }+ expect(body).toContain('<lastmod>2026-08-01</lastmod>');+ });++ it('refuses a write method instead of answering it with the index', async () => {+ for (const m of ['POST', 'DELETE', 'PUT', 'PATCH']) {+ const r = await fetch(`${base}/api/sitemap`, { method: m });+ expect(r.status, m).toBe(405);+ expect(r.headers.get('allow')).toContain('GET');+ expect((await r.json()).error).toBe('method_not_allowed');+ }+ // A rejected method costs no database work.+ expect(db.queries).toHaveLength(0);+ });++ it('answers a HEAD probe the way it answers GET', async () => {+ const r = await fetch(`${base}/api/sitemap`, { method: 'HEAD' });+ expect(r.status).toBe(200);+ expect(r.headers.get('content-type')).toContain('application/xml');+ });++ it('still emits every entry when the lastmod probes fail', async () => {+ db.fail = true;+ const r = await fetch(`${base}/api/sitemap`);+ expect(r.status).toBe(200);++ const body = await r.text();+ expect(XMLValidator.validate(body)).toBe(true);+ expect(body.match(/<sitemap>/g)).toHaveLength(6);+ });+});diff --git a/tests/api/strategies-performance-rank.test.js b/tests/api/strategies-performance-rank.test.jsnew file mode 100644index 000000000..a1a499bf4--- /dev/null+++ b/tests/api/strategies-performance-rank.test.js@@ -0,0 +1,132 @@+// GET /api/strategies?sort=performance, the published marketplace's default order.+//+// Performance is not a database column: it is aggregated in the handler from real+// closed on-chain positions, so the SQL page cannot also be the answer. Ordering by+// published_at and taking `limit` rows would rank only the newest slice and still+// label it a performance ranking, hiding the best-performing strategy on the+// platform behind whatever was published most recently. The handler scans a wider+// candidate pool, ranks it, and only then trims to `limit`.+//+// Network-free: database, auth and rate limiter are mocked. What is under test is+// the ordering contract and the size of the pool the handler asks Postgres for.++import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';+import { createServer } from 'node:http';++const OWNER = '5f2f1b3c-1d4e-4a2b-8c9d-0e1f2a3b4c5d';++function strategy(id, name, publishedAt) {+ return {+ id,+ name,+ slug: name.toLowerCase(),+ description: null,+ config: {},+ version: 1,+ published: true,+ published_at: publishedAt,+ owner_id: OWNER,+ fork_of: null,+ forked_from: null,+ forks_count: 0,+ equips_count: 0,+ created_at: publishedAt,+ updated_at: publishedAt,+ };+}++// Newest first, which is the order the SQL returns them in.+const NEWEST_UNPROVEN = strategy('11111111-1111-4111-8111-111111111111', 'Newest', '2026-08-15T00:00:00.000Z');+const MID_MODEST = strategy('22222222-2222-4222-8222-222222222222', 'Modest', '2026-06-01T00:00:00.000Z');+const OLDEST_BEST = strategy('33333333-3333-4333-8333-333333333333', 'Best', '2026-01-01T00:00:00.000Z');++// Real closed positions: only the two older strategies have ever traded.+const POSITIONS = [+ {+ strategy_id: MID_MODEST.id,+ closed: 4, open: 0, wins: 3, losses: 1,+ pnl_lamports: '100000000', entry_lamports: '1000000000',+ worst_lamports: '-20000000', last_closed_at: '2026-07-01T00:00:00.000Z',+ },+ {+ strategy_id: OLDEST_BEST.id,+ closed: 9, open: 1, wins: 8, losses: 1,+ pnl_lamports: '5000000000', entry_lamports: '1000000000',+ worst_lamports: '-10000000', last_closed_at: '2026-07-20T00:00:00.000Z',+ },+];++const calls = [];++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (...args) => {+ const text = Array.isArray(args[0]) ? args[0].join('?') : String(args[0]);+ calls.push({ text, values: args.slice(1) });+ if (text.includes('agent_strategy_positions')) return POSITIONS;+ if (text.includes('FROM users')) return [{ id: OWNER, name: 'Audit owner' }];+ if (text.includes('FROM agent_strategies')) return [NEWEST_UNPROVEN, MID_MODEST, OLDEST_BEST];+ return [];+ }),+ isDbUnavailableError: () => false,+}));++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => null),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: () => null,+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: 0 })),+ authedReadIp: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: 0 })),+ authIp: vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: 0 })),+ },+ clientIp: () => '127.0.0.1',+}));++let server;+let base;++beforeAll(async () => {+ const { default: handler } = await import('../../api/strategies.js');+ server = createServer((req, res) => handler(req, res));+ await new Promise((r) => server.listen(0, '127.0.0.1', r));+ base = `http://127.0.0.1:${server.address().port}`;+});++afterAll(() => server?.close());+beforeEach(() => { calls.length = 0; });++/** The value the list query passed as its LIMIT (always the last interpolation). */+const listLimit = () => calls.find((c) => c.text.includes('FROM agent_strategies')).values.at(-1);++describe('/api/strategies?sort=performance', () => {+ it('ranks the whole published pool, not just the newest page', async () => {+ const r = await fetch(`${base}/api/strategies?sort=performance&limit=1`);+ expect(r.status).toBe(200);++ const { data } = await r.json();+ expect(data.sort).toBe('performance');+ expect(data.strategies).toHaveLength(1);+ // 500% ROI beats 10%, and both beat an unproven strategy published yesterday.+ expect(data.strategies[0].name).toBe('Best');+ expect(data.strategies[0].performance).toMatchObject({ proven: true, trades: 9, roi_pct: 500 });+ });++ it('asks Postgres for a candidate pool rather than one page', async () => {+ await fetch(`${base}/api/strategies?sort=performance&limit=1`);+ expect(listLimit()).toBe(200);+ });++ it('leaves a database-ordered sort paging normally', async () => {+ await fetch(`${base}/api/strategies?sort=forks&limit=7`);+ expect(listLimit()).toBe(7);+ });++ it('sorts unproven strategies below proven ones, newest first among them', async () => {+ const { data } = await (await fetch(`${base}/api/strategies?sort=performance&limit=10`)).json();+ expect(data.strategies.map((s) => s.name)).toEqual(['Best', 'Modest', 'Newest']);+ expect(data.strategies[2].performance).toMatchObject({ proven: false, trades: 0 });+ });+});