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.

fix(reputation): rank the whole trusted-agent pool instead of an arbitrary slice of it

nirholas88c093948dad
diff --git a/api/reputation/leaderboard.js b/api/reputation/leaderboard.js
index 049a28546..c8910d324 100644
--- a/api/reputation/leaderboard.js
+++ b/api/reputation/leaderboard.js
@@ -1,7 +1,7 @@
/**
- * GET /api/reputation/leaderboard?limit=20&network=mainnet
+ * GET /api/reputation/leaderboard?limit=20
*
- * The platform's real leaderboard of TRUSTED agents — ranked by the same
+ * The platform's real leaderboard of TRUSTED agents, ranked by the same
* non-gameable wallet-trust score the badge shows, computed entirely from real
* ledger + chain activity (api/_lib/trust/wallet-reputation.js). Unlike a
* follower count, every rank here is backed by money and time and is fully
@@ -9,11 +9,17 @@
*
* Candidate pool = public agents with ANY real footprint (ledger activity, an
* on-chain identity, or a launched coin) so we never burn cycles scoring empty
- * agents. We score that pool, drop the honest "new" agents (no track record),
- * and return the top `limit` by score. Cached 5 min — trust moves slowly.
+ * agents. Scoring is the expensive part (one reputation read per candidate), so
+ * the pool is capped at POOL and, because the candidate set is already larger
+ * than that cap, ordered by settled tip volume: the strongest candidates are
+ * always scored and the same request always sees the same pool. An unordered
+ * `limit` would hand Postgres an arbitrary slice, so the true #1 could vanish
+ * from the board between two identical requests. We score that pool, drop the
+ * honest "new" agents (no track record), and return the top `limit` by score.
+ * Cached 5 min, because trust moves slowly.
*/
-import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { cors, json, method, wrap, rateLimited, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { thumbnailUrl } from '../_lib/r2.js';
@@ -30,9 +36,22 @@ export default wrap(async (req, res) => {
if (!rl.success) return rateLimited(res, rl);
const p = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
- const limit = Math.min(50, Math.max(1, Number(p.get('limit') || 20)));
+ // A non-numeric limit used to survive as NaN all the way to slice(0, NaN),
+ // which returns nothing: the caller paid for a full scoring pass and got an
+ // empty board indistinguishable from "no trusted agents". Reject it up front,
+ // with the same message the SDK's own client-side guard uses; numeric values
+ // keep the SDK's clamp semantics so a caller never gets an error for asking
+ // for more rows than exist.
+ const rawLimit = (p.get('limit') || '').trim();
+ // Number('') and Number(' ') are both 0, which would silently clamp a blank
+ // parameter to a one-row board; a blank means "unspecified", so it defaults.
+ const asked = rawLimit === '' ? 20 : Number(rawLimit);
+ if (!Number.isFinite(asked)) {
+ return error(res, 400, 'bad_request', 'limit must be a number between 1 and 50');
+ }
+ const limit = Math.min(50, Math.max(1, Math.trunc(asked)));
- const cacheKey = `walletrep:leaderboard:v1:${limit}`;
+ const cacheKey = `walletrep:leaderboard:v2:${limit}`;
const redis = await getRedis();
if (redis) {
try {
@@ -46,13 +65,21 @@ export default wrap(async (req, res) => {
}
}
- // Candidate pool — public agents with a real footprint.
+ // Candidate pool: public agents with a real footprint, strongest first.
+ // A DB failure here is NOT swallowed: an empty board and a broken board look
+ // identical to a client, so the error propagates and wrap() answers 503 with a
+ // ref instead of publishing "nobody on this platform is trusted".
const rows = await sql`
select
i.id, i.name,
i.meta->>'solana_address' as solana_address,
a.thumbnail_key as avatar_thumbnail_key,
- a.visibility as avatar_visibility
+ a.visibility as avatar_visibility,
+ (
+ select coalesce(sum(e.usd), 0)
+ from agent_custody_events e
+ where e.agent_id = i.id and e.event_type = 'tip' and e.status in ('confirmed', 'ok')
+ ) as settled_usd
from agent_identities i
left join avatars a on a.id = i.avatar_id and a.deleted_at is null
where i.deleted_at is null and i.is_public = true
@@ -61,8 +88,9 @@ export default wrap(async (req, res) => {
or i.erc8004_agent_id is not null
or exists (select 1 from pump_agent_mints m where m.agent_id = i.id)
)
+ order by settled_usd desc nulls last, i.id
limit ${POOL}
- `.catch(() => []);
+ `;
const byId = new Map(rows.map((r) => [r.id, r]));
const reps = await scoreAgentsLite([...byId.keys()]);
diff --git a/data/changelog.json b/data/changelog.json
index 23c4dd3ee..680d6927a 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-15",
+ "title": "Scanning a skill purchase QR tells you when your wallet is short",
+ "summary": "Paying for a skill from a phone handed the wallet a transfer even when the wallet held none of the token being asked for, so the buyer signed and watched it fail with whatever cryptic message their wallet chose to print. The checkout now checks the paying wallet first and answers with the exact shortfall, so a wallet that is 0.35 short says so and a wallet that has never held the token says that instead of failing at signing time. The same checkout also stopped pinning the busiest public Solana node ahead of the platform's own faster ones, so building the payment is quicker and survives a throttled node.",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-08-15",
"title": "Portfolio token pages price Base and Arbitrum holdings correctly",
diff --git a/packages/reputation/README.md b/packages/reputation/README.md
index aac303760..f9a646bbe 100644
--- a/packages/reputation/README.md
+++ b/packages/reputation/README.md
@@ -178,7 +178,11 @@ Fetch the platform's live ranking of trusted agents
wallet-trust score the badge shows, computed from real ledger + chain activity.
**Options**: `{ limit?: number, signal?: AbortSignal }`. `limit` is clamped to
-1-50 (default 20).
+1-50 (default 20). A non-numeric `limit` throws `invalid_input` here, and the
+endpoint answers raw-HTTP callers with `400 bad_request` rather than an empty
+board. `scored` reports how many candidates were scored to produce the ranking:
+the pool is capped, ordered by settled ledger volume, so the same request always
+returns the same board.
**Returns**: `{ generatedAt, count, scored, agents }`, where each agent carries
`rank`, `id`, `name`, `avatarThumbnailUrl`, `solanaAddress`, `score`, `tier`,
diff --git a/prompts/swarm-100/api-reputation-01.md b/prompts/swarm-100/api-reputation-01.md
deleted file mode 100644
index b9860950e..000000000
--- a/prompts/swarm-100/api-reputation-01.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# API audit: api/reputation batch 01 (1 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/reputation/leaderboard.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-reputation-01.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/tests/reputation-leaderboard-endpoint.test.js b/tests/reputation-leaderboard-endpoint.test.js
new file mode 100644
index 000000000..68eb7a529
--- /dev/null
+++ b/tests/reputation-leaderboard-endpoint.test.js
@@ -0,0 +1,253 @@
+/**
+ * HTTP-level tests for GET /api/reputation/leaderboard, the public ranking the
+ * trending page and the theater roster both render.
+ *
+ * The scoring math has its own suites (tests/wallet-reputation.test.js and the
+ * pure formula in src/shared/agent-financial-reputation.js); this one covers the
+ * handler around it, and pins the three failures the endpoint shipped with:
+ *
+ * 1. `?limit=abc` parsed to NaN, survived to slice(0, NaN), and answered 200
+ * with an empty board after a full scoring pass. A caller could not tell
+ * that from "no agent on this platform is trusted".
+ * 2. The candidate-pool query swallowed every database error and degraded to
+ * an empty pool, so an outage published an empty leaderboard as truth.
+ * 3. The pool was capped at 90 with no ORDER BY while the real candidate set
+ * is larger, so Postgres handed back an arbitrary slice: the top-scoring
+ * agent could be missing from the board, and two identical requests could
+ * rank differently.
+ *
+ * Only the impure edges are stubbed (database, Redis, CDN URL builder, the
+ * per-agent reputation read, the rate limiter). The handler, its validation, its
+ * cache decisions, and its wire shape are the real module.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+class DbDown extends Error {
+ constructor() {
+ super('connection to server failed');
+ this.name = 'DbDown';
+ }
+}
+
+// Every sql`` call the handler makes, as the raw template strings, so the pool
+// query's contract (ordered, deterministic) is assertable.
+const queries = [];
+let poolRows = [];
+let poolError = null;
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: Object.assign(
+ vi.fn(async (strings) => {
+ queries.push(strings.join(' ? '));
+ if (poolError) throw poolError;
+ return poolRows;
+ }),
+ { transaction: vi.fn() },
+ ),
+ isDbUnavailableError: (err) => err instanceof DbDown,
+ isDbCapacityError: () => false,
+ isStoragePressured: async () => ({ pressured: false, sizeMb: 1, highWaterMb: 470 }),
+}));
+
+vi.mock('../api/_lib/redis.js', () => ({ getRedis: async () => null }));
+vi.mock('../api/_lib/r2.js', () => ({ thumbnailUrl: (key) => `https://cdn.test/${key}` }));
+
+const scoreAgentsLite = vi.fn();
+vi.mock('../api/_lib/trust/wallet-reputation.js', () => ({
+ scoreAgentsLite: (...a) => scoreAgentsLite(...a),
+}));
+
+const publicIp = vi.fn(async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 }));
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: (...a) => publicIp(...a) },
+ clientIp: () => '127.0.0.1',
+}));
+
+const { default: handler } = await import('../api/reputation/leaderboard.js');
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ _body: '',
+ _ended: false,
+ setHeader(k, v) {
+ this._headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._headers[k.toLowerCase()];
+ },
+ end(b) {
+ this._body = b || '';
+ this._ended = true;
+ },
+ get json() {
+ try {
+ return JSON.parse(this._body);
+ } catch {
+ return null;
+ }
+ },
+ };
+}
+
+function mockReq(query = '') {
+ return {
+ method: 'GET',
+ url: '/api/reputation/leaderboard' + (query ? `?${query}` : ''),
+ headers: { host: 'three.ws', origin: 'https://three.ws' },
+ };
+}
+
+const read = async (query = '') => {
+ const res = mockRes();
+ await handler(mockReq(query), res);
+ return res;
+};
+
+// Three real-shaped candidates: a public avatar, a private one (thumbnail must
+// stay hidden), and an agent with no track record (filtered out as "new").
+const ROWS = [
+ {
+ id: 'be3548cd-420b-416d-92dd-a826f417866d',
+ name: 'Harbor #21',
+ solana_address: '4Nex4B1MiquVWMF1FuDPHwBWQZWhQZTirichyBFwtxBV',
+ avatar_thumbnail_key: 'thumb/harbor.png',
+ avatar_visibility: 'public',
+ },
+ {
+ id: '3bd520d8-4c4f-4d4a-b472-3555ce241071',
+ name: 'Meridian #22',
+ solana_address: null,
+ avatar_thumbnail_key: 'thumb/meridian.png',
+ avatar_visibility: 'private',
+ },
+ {
+ id: '9507e401-b4dd-42e6-a1eb-806ee0ac28d4',
+ name: 'Glyph #21',
+ solana_address: '9FkceMhUuLi6VmKfcwsXx5UnAoVjVfj6kzokPaY6uDWo',
+ avatar_thumbnail_key: null,
+ avatar_visibility: 'public',
+ },
+];
+
+const rep = (score, isNew = false) => ({
+ score,
+ tier: 'established',
+ tierLabel: 'Established',
+ accent: '#7dd3fc',
+ isNew,
+ totals: { settled_usd: score, distinct_tippers: 4, holds_three: true },
+});
+
+beforeEach(() => {
+ queries.length = 0;
+ poolRows = ROWS;
+ poolError = null;
+ scoreAgentsLite.mockReset();
+ // Deliberately out of score order, and with the lowest-id agent scoring
+ // highest, so a passing rank assertion can only come from the sort.
+ scoreAgentsLite.mockImplementation(async (ids) =>
+ new Map([
+ [ids[1], rep(31.9)],
+ [ids[0], rep(32.4)],
+ [ids[2], rep(9.1, true)],
+ ]),
+ );
+ publicIp.mockResolvedValue({ success: true, limit: 60, remaining: 59, reset: Date.now() + 60_000 });
+});
+
+describe('GET /api/reputation/leaderboard', () => {
+ it('ranks scored agents by score and returns the auditable wire shape', async () => {
+ const res = await read('limit=5');
+ expect(res.statusCode).toBe(200);
+ const body = res.json;
+ expect(body.count).toBe(2); // the "new" agent is dropped
+ expect(body.scored).toBe(3);
+ expect(body.agents.map((a) => [a.rank, a.name, a.score])).toEqual([
+ [1, 'Harbor #21', 32.4],
+ [2, 'Meridian #22', 31.9],
+ ]);
+ const top = body.agents[0];
+ expect(top.tier).toBe('established');
+ expect(top.tier_label).toBe('Established');
+ expect(top.totals.holds_three).toBe(true);
+ expect(top.agent_url).toBe(`https://three.ws/agent/${ROWS[0].id}`);
+ expect(top.breakdown_url).toBe(`https://three.ws/agent/${ROWS[0].id}/wallet#reputation`);
+ expect(top.avatar_thumbnail_url).toBe('https://cdn.test/thumb/harbor.png');
+ expect(Date.parse(body.generated_at)).not.toBeNaN();
+ expect(res.getHeader('x-cache')).toBe('MISS');
+ });
+
+ it('never leaks a private avatar thumbnail', async () => {
+ const body = (await read('limit=5')).json;
+ expect(body.agents.find((a) => a.name === 'Meridian #22').avatar_thumbnail_url).toBeNull();
+ });
+
+ it('scores a deterministic, footprint-ordered pool rather than an arbitrary slice', async () => {
+ await read('limit=5');
+ const pool = queries.find((q) => q.includes('from agent_identities'));
+ expect(pool).toMatch(/order by\s+settled_usd desc nulls last, i\.id/);
+ // The tie-break on i.id is what makes two identical requests agree.
+ expect(pool.indexOf('order by')).toBeLessThan(pool.lastIndexOf('limit'));
+ });
+
+ it('honours limit, clamping numeric values the way the SDK client does', async () => {
+ expect((await read('limit=1')).json.count).toBe(1);
+ expect((await read('limit=0')).json.count).toBe(1);
+ expect((await read('limit=-5')).json.count).toBe(1);
+ expect((await read('limit=999')).json.count).toBe(2);
+ expect((await read('limit=1.9')).json.count).toBe(1);
+ expect((await read()).json.count).toBe(2);
+ // A blank limit means "unspecified", not zero rows: Number('') is 0.
+ expect((await read('limit=')).json.count).toBe(2);
+ expect((await read('limit=%20')).json.count).toBe(2);
+ });
+
+ it('rejects a non-numeric limit with 400 instead of an empty board', async () => {
+ for (const q of ['limit=abc', 'limit=null', 'limit=1e999', 'limit=12px']) {
+ const res = await read(q);
+ expect(res.statusCode, q).toBe(400);
+ expect(res.json.error, q).toBe('bad_request');
+ expect(res.json.error_description, q).toMatch(/limit must be a number between 1 and 50/);
+ }
+ // And it costs nothing: the request is refused before the scoring pass.
+ expect(scoreAgentsLite).not.toHaveBeenCalled();
+ });
+
+ it('answers 503 when the database is down instead of publishing an empty board', async () => {
+ poolError = new DbDown();
+ const res = await read('limit=5');
+ expect(res.statusCode).toBe(503);
+ expect(res.json.agents).toBeUndefined();
+ expect(res.getHeader('retry-after')).toBe('30');
+ expect(scoreAgentsLite).not.toHaveBeenCalled();
+ });
+
+ it('returns a designed empty board when nobody has a track record yet', async () => {
+ scoreAgentsLite.mockImplementation(async (ids) => new Map(ids.map((id) => [id, rep(4.2, true)])));
+ const res = await read('limit=5');
+ expect(res.statusCode).toBe(200);
+ expect(res.json).toMatchObject({ count: 0, scored: 3, agents: [] });
+ });
+
+ it('refuses non-GET methods and answers the CORS preflight', async () => {
+ const post = mockRes();
+ await handler({ ...mockReq(), method: 'POST' }, post);
+ expect(post.statusCode).toBe(405);
+ expect(post.json.error).toBe('method_not_allowed');
+
+ const preflight = mockRes();
+ await handler({ ...mockReq(), method: 'OPTIONS' }, preflight);
+ expect(preflight.statusCode).toBe(204);
+ expect(preflight.getHeader('access-control-allow-origin')).toBe('*');
+ });
+
+ it('surfaces a rate limit as 429 without touching the database', async () => {
+ publicIp.mockResolvedValue({ success: false, limit: 60, remaining: 0, reset: Date.now() + 30_000 });
+ const res = await read('limit=5');
+ expect(res.statusCode).toBe(429);
+ expect(queries).toHaveLength(0);
+ });
+});