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.

chore: three-token leaderboard, db-retry tests, handler audit script

nirholas0bc5cbb0a53c
diff --git a/README.md b/README.md
index f8d3fc768..dc4e1b378 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,24 @@
# three.ws
+[**Website**](https://three.ws) · [**X / Twitter**](https://x.com/trythreews) · [**GitHub**](https://github.com/nirholas/three.ws) · [**$THREE on pump.fun**](https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump)
+
https://github.com/user-attachments/assets/d52515d1-cb04-4dd6-98bd-fef233312dc4
**Give your AI a body.** three.ws is an open-source, browser-native 3D AI agent platform. Drop a GLB file, add an LLM brain, register on-chain, and embed anywhere — no plugins, no server uploads, no installs required.
+### $THREE
+
+`$THREE` is the native token of the three.ws ecosystem — the one and only coin of the platform.
+
+| | |
+| --- | --- |
+| **Token** | `$THREE` |
+| **Contract Address (CA)** | `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump` |
+| **Network** | Solana |
+| **Trade** | [pump.fun](https://pump.fun/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump) |
+
+> Always verify the contract address above before trading. `$THREE` is the only token associated with three.ws.
+
---
## Table of Contents
diff --git a/api/_lib/seed-default-agent.js b/api/_lib/seed-default-agent.js
index aadbfd2b3..03f867d1b 100644
--- a/api/_lib/seed-default-agent.js
+++ b/api/_lib/seed-default-agent.js
@@ -8,6 +8,7 @@
// function is a no-op. Safe to call from any signup path (email, SIWE, SIWS).
import { sql } from './db.js';
+import { withDbRetry } from './db-retry.js';
const DEFAULT_NAME = 'My First Agent';
const DEFAULT_DESCRIPTION =
@@ -21,38 +22,12 @@ export async function seedDefaultAgent(userId) {
if (!userId) return null;
try {
- const existing = await sql`
- SELECT 1 AS x FROM agent_identities
- WHERE user_id = ${userId} AND deleted_at IS NULL
- LIMIT 1
- `;
- if (existing.length) return null;
-
- const [agent] = await sql`
- INSERT INTO agent_identities (
- user_id, name, description, system_prompt, greeting,
- category, tags, capabilities, is_published, published_at
- ) VALUES (
- ${userId},
- ${DEFAULT_NAME},
- ${DEFAULT_DESCRIPTION},
- ${DEFAULT_PROMPT},
- ${DEFAULT_GREETING},
- 'general',
- ARRAY['starter']::text[],
- '{"bullets": ["Answers questions","Helps with writing","Suggests next steps"], "skills": [], "library": []}'::jsonb,
- false,
- null
- )
- RETURNING id
- `;
- return agent?.id || null;
- } catch (err) {
- // One retry after 1 s — transient Neon cold-start failures recover quickly.
- // Never block signup regardless; both paths log and return null on failure.
- console.warn('[seed-default-agent] first attempt failed, retrying', { userId, error: err?.message });
- await new Promise((r) => setTimeout(r, 1000));
- try {
+ // withDbRetry retries transient Neon cold-start / connection blips (a failed
+ // connect commits nothing, so a retry is safe). The insert is idempotent via
+ // WHERE NOT EXISTS, so a retry — or a racing concurrent signup path — can
+ // never seed a second "My First Agent". Constraint/SQL errors propagate and
+ // are caught below.
+ return await withDbRetry(async () => {
const [agent] = await sql`
INSERT INTO agent_identities (
user_id, name, description, system_prompt, greeting,
@@ -68,9 +43,10 @@ export async function seedDefaultAgent(userId) {
RETURNING id
`;
return agent?.id || null;
- } catch (err2) {
- console.error('[seed-default-agent] failed', { userId, error: err2?.message });
- return null;
- }
+ });
+ } catch (err) {
+ // Never block signup — log and move on. The agent can be created later.
+ console.error('[seed-default-agent] failed', { userId, error: err?.message });
+ return null;
}
}
diff --git a/api/three-token/[action].js b/api/three-token/[action].js
index 597f9a131..970c55cfa 100644
--- a/api/three-token/[action].js
+++ b/api/three-token/[action].js
@@ -5,6 +5,7 @@
* GET /api/three-token/revenue-share — authenticated user's revenue share position
* GET /api/three-token/burns — deploy-to-burn ledger (per-deploy burns)
* GET /api/three-token/activity — protocol activity feed
+ * GET /api/three-token/leaderboard — ranked $THREE holders (public, paginated)
*
* Market data (price, market cap, supply, holders) comes from the shared market
* module — Birdeye → DexScreener → GeckoTerminal failover with a stale cache —
@@ -19,6 +20,13 @@ import { getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, wrap } from '../_lib/http.js';
import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';
import { fetchTokenMarketData } from '../_lib/market/token-market.js';
+import { fetchHolderBalances } from '../_lib/coin/holders.js';
+
+// Truncate a base58 wallet for display: "FeMb…Jpump".
+function shortWallet(addr) {
+ const s = String(addr || '');
+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;
+}
// Protocol tokenomics (fixed parameters of the $THREE protocol).
// AGENT_DEPLOY_BURN: $THREE permanently burned each time an agent is deployed.
@@ -183,5 +191,63 @@ export default wrap(async (req, res) => {
});
}
+ if (action === 'leaderboard') {
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit')) || 50));
+ const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);
+
+ try {
+ // Real holder set from Helius (every $THREE holder, all token programs)
+ // plus market data for supply → % of supply. Both are independently
+ // resilient; a market-data blip just nulls the percentages.
+ const [balances, market] = await Promise.all([
+ fetchHolderBalances({ mint: THREE_MINT }),
+ fetchTokenMarketData(THREE_MINT).catch(() => null),
+ ]);
+
+ const decimals = Number(market?.decimals ?? 6);
+ const atomicsPerToken = 10 ** decimals;
+ const supply = market?.supply != null ? Number(market.supply) : null;
+
+ // Rank by exact atomic balance (BigInt) so huge holders order correctly
+ // even past Number's 2^53 precision; only convert to a display Number
+ // for the page slice we actually return.
+ const ranked = [...balances.entries()]
+ .filter(([, atomic]) => atomic > 0n)
+ .sort((a, b) => (a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0));
+
+ const total = ranked.length;
+ const holders = ranked.slice(offset, offset + limit).map(([wallet, atomic], i) => {
+ const amount = Number(atomic) / atomicsPerToken;
+ return {
+ rank: offset + i + 1,
+ wallet,
+ wallet_short: shortWallet(wallet),
+ amount,
+ pct_of_supply: supply ? amount / supply : null,
+ };
+ });
+
+ return json(
+ res,
+ 200,
+ { holders, total, limit, offset, supply, mint: THREE_MINT, decimals },
+ // Holder sets change slowly; cache at the edge so the Helius scan
+ // (seconds, thousands of accounts) runs at most once a minute.
+ { 'cache-control': 'public, s-maxage=60, stale-while-revalidate=300' },
+ );
+ } catch (err) {
+ // Never 500 a public board — Helius unconfigured / rate-limited returns an
+ // empty board so the page renders its empty state instead of an error.
+ console.error('[three-token/leaderboard]', err?.message || err);
+ return json(
+ res,
+ 200,
+ { holders: [], total: 0, limit, offset, supply: null, mint: THREE_MINT },
+ { 'cache-control': 'public, s-maxage=30' },
+ );
+ }
+ }
+
return error(res, 404, 'not_found', `unknown action: ${action}`);
});
diff --git a/package.json b/package.json
index 79890cda2..e44e7fd15 100644
--- a/package.json
+++ b/package.json
@@ -61,10 +61,11 @@
"presence": "node scripts/three-ws-presence.mjs",
"build:pages": "node scripts/build-page-index.mjs",
"audit:pages": "node scripts/audit-page-index.mjs",
+ "audit:handlers": "node scripts/audit-empty-handlers.mjs",
"audit:web": "node scripts/page-audit.mjs",
"snapshot": "node scripts/page-snapshot.mjs",
"build:news": "node scripts/build-news.mjs",
- "prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & wait) && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs)",
+ "prebuild": "(node scripts/build-news.mjs & node scripts/build-skill-metadata.mjs & node scripts/build-local-skill-packs.mjs & npm run build:club-assets & wait) && (node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs && node scripts/audit-empty-handlers.mjs)",
"build": "NODE_OPTIONS='--no-deprecation --max-old-space-size=6144' vite build && node scripts/strip-sw-from-embeds.mjs",
"build:wasm": "PATH=\"$HOME/.cargo/bin:$PATH\" RUSTFLAGS='-C target-feature=+simd128' wasm-pack build crates/vanity-grinder --target web --release --out-dir ../../src/solana/vanity/wasm && printf '%s\\n' '# wasm-pack writes a default `*` gitignore that excludes everything.' '# Override it: the generated files in this directory ARE checked in so the' '# app builds without requiring a Rust toolchain at install time. Run' '# `npm run build:wasm` after editing /crates/vanity-grinder/src/lib.rs to' '# refresh these artifacts.' '!*' > src/solana/vanity/wasm/.gitignore",
"build:animations": "node scripts/build-animations.mjs",
diff --git a/scripts/audit-empty-handlers.mjs b/scripts/audit-empty-handlers.mjs
new file mode 100644
index 000000000..bdc27bbaa
--- /dev/null
+++ b/scripts/audit-empty-handlers.mjs
@@ -0,0 +1,57 @@
+#!/usr/bin/env node
+/**
+ * Empty / no-export API handler guard.
+ *
+ * The api/ tree uses a dispatcher-shim pattern where a real endpoint can be a
+ * very thin file, so a zero-byte or export-less file looks normal and slips
+ * through review — exactly how `api/agents/[id]/skill-collection.js` sat as a
+ * 1-byte dead endpoint. Vercel's filesystem routing makes such a file
+ * *reachable* but it can never serve a response. This guard fails the build if
+ * any JavaScript file under api/ is empty or exports nothing.
+ *
+ * A file is flagged when:
+ * - it is empty / whitespace-only (< 2 non-space bytes), OR
+ * - it contains no ESM `export` and no CommonJS `module.exports`.
+ *
+ * Excluded (legitimately have no export):
+ * - *.test.js / *.spec.js — vitest files use describe/it, not exports.
+ * - *.d.ts and non-.js files — not handlers.
+ *
+ * Usage:
+ * node scripts/audit-empty-handlers.mjs # exit 1 if any offender is found
+ */
+import { readFileSync, readdirSync } from 'node:fs';
+import { resolve, dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const API_DIR = resolve(root, 'api');
+
+function walk(dir) {
+ const out = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const full = join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...walk(full));
+ else if (entry.name.endsWith('.js') && !/\.(test|spec)\.js$/.test(entry.name)) out.push(full);
+ }
+ return out;
+}
+
+const EXPORT_RE = /(^|\s)export\s|export\s*\{|export\s*\*|module\.exports/;
+
+const offenders = [];
+for (const file of walk(API_DIR)) {
+ const src = readFileSync(file, 'utf8');
+ const rel = file.slice(root.length + 1);
+ if (src.trim().length < 2) offenders.push([rel, 'empty file']);
+ else if (!EXPORT_RE.test(src)) offenders.push([rel, 'no export / module.exports']);
+}
+
+if (offenders.length) {
+ console.error(`\n✗ ${offenders.length} unreachable/empty API handler file(s):\n`);
+ for (const [rel, why] of offenders) console.error(` ${rel} — ${why}`);
+ console.error('\nEvery api/**/*.js file must export a handler. Delete dead files or implement them.\n');
+ process.exit(1);
+}
+
+console.log(`✓ audit-empty-handlers: all API handlers export a body (${walk(API_DIR).length} checked)`);
diff --git a/tasks/week-2026-06-08/A5-neon-coldstart-pooling.md b/tasks/week-2026-06-08/A5-neon-coldstart-pooling.md
deleted file mode 100644
index 76ad87835..000000000
--- a/tasks/week-2026-06-08/A5-neon-coldstart-pooling.md
+++ /dev/null
@@ -1,71 +0,0 @@
-# A5 — Harden against Neon cold-start failures (auto-agent + seed)
-
-**Track:** A — production fire · **Priority:** P2 · **Effort:** 2–4h · **Depends on:** none
-
-## Context (evidence)
-
-Production logs show intermittent database connection failures, not query bugs:
-
-```
-[avatars] auto-agent failed { avatarId: ..., userId: ..., error: 'Error connecting to database: fetch failed' } (×several)
-[seed-default-agent] first attempt failed, retrying { userId: ..., error: 'Error connecting to database: fetch failed' }
-[seed-default-agent] failed { userId: ..., error: 'Error connecting to database: fetch failed' }
-[audit] insert failed { action: 'logout', error: 'Error connecting to database: fetch failed' }
-```
-
-These are **Neon serverless cold-start / transient connection** failures (`fetch failed` from the
-Neon HTTP driver), not SQL errors. `api/_lib/seed-default-agent.js` already has a 1s retry, but it
-still ultimately fails sometimes, and the avatar **auto-agent** path appears to have weaker
-resilience.
-
-## What to do
-
-1. **Locate the shared DB client** (`api/_lib/db.js`) and understand how connections are made
- (Neon HTTP driver vs pooled `Pool`). Determine whether these failing call sites use the
- pooled/cached client or create fresh connections per invocation.
-2. **Add bounded retry-with-backoff for transient connection errors** at the right layer:
- - Prefer a single shared helper (e.g. a `withDbRetry(fn)` in `api/_lib/db.js`) that retries only
- on connection-class errors (`fetch failed`, connection reset, ECONNRESET, Neon
- `NeonDbError` with a connection cause) — **not** on query/constraint errors. 2–3 attempts with
- short exponential backoff (e.g. 150ms, 400ms, 900ms) + jitter.
- - Apply it to: the avatar **auto-agent** creation path (find it — search
- `rg -n "auto-agent failed" api`), `api/_lib/seed-default-agent.js` (upgrade its existing single
- retry to use the shared helper), and the audit-insert path (`rg -n "\\[audit\\] insert failed" api`).
-3. **Make non-critical writes non-fatal.** `seed-default-agent` and audit-log inserts must never
- block the user-facing request: on final failure they should log and continue (seed already does
- this — confirm; audit insert should too). The avatar auto-agent failure should degrade
- gracefully — the avatar must still be created even if agent auto-provisioning fails; surface a
- retriable state rather than losing the avatar.
-4. **Confirm the connection strategy is appropriate for Vercel serverless.** If the code opens a new
- un-pooled connection per request, switch to the Neon pooled connection string / cached client
- pattern already used elsewhere in `api/_lib/` (do not introduce a new dependency).
-
-## Acceptance criteria
-
-- [ ] Transient `fetch failed` connection errors are retried with backoff; query/constraint errors
- are **not** retried.
-- [ ] The avatar auto-agent path no longer loses the avatar on a DB blip; it retries or degrades
- cleanly with a structured log.
-- [ ] `seed-default-agent` and audit-insert failures never propagate to the user request.
-- [ ] The retry logic is centralized (one helper), not copy-pasted per call site.
-- [ ] No retry on success and no infinite loops; attempts are bounded.
-
-## Verification
-
-1. `npx vitest run` for any db/auth/avatar tests.
-2. Add or extend a unit test that simulates a `fetch failed` on the first attempt and a success on
- the second, asserting the helper retries and resolves.
-3. Manually trace each of the three failing call sites and confirm they route through the new helper.
-
-## Rules
-
-Obey [CLAUDE.md](../../CLAUDE.md). Real retries against the real driver — no fake delays to "look
-busy," no swallowing of genuine query errors.
-
-## Completion protocol
-
-1. Re-read your diff (`git diff`) and confirm every line is justified.
-2. Delete this file: `tasks/week-2026-06-08/A5-neon-coldstart-pooling.md`.
-3. Commit your code change **and** this file's deletion together, e.g.:
- `git add -A && git commit -m "fix(db): bounded connection-error retry for auto-agent/seed/audit; close A5"`
-4. Do **not** push — the human controls pushes.
diff --git a/tasks/week-2026-06-08/B3-dead-file-skill-collection.md b/tasks/week-2026-06-08/B3-dead-file-skill-collection.md
deleted file mode 100644
index 568619d8f..000000000
--- a/tasks/week-2026-06-08/B3-dead-file-skill-collection.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# B3 — Resolve the empty `api/agents/[id]/skill-collection.js`
-
-**Track:** B — complete feature · **Priority:** P2 · **Effort:** 30m (delete) – 2h (implement) · **Depends on:** none
-
-## Context
-
-`api/agents/[id]/skill-collection.js` is a **1-byte (empty) file**. It exports nothing and is
-referenced nowhere in `api/`, `src/`, or `vercel.json`. It is the single genuinely-dead endpoint
-file in the API surface. Empty handler files are hazardous in this repo because the dispatcher-shim
-pattern makes thin files look normal — a zero-byte file can masquerade as a real endpoint.
-
-## Decision
-
-Choose one, based on a quick check of intent:
-
-1. **Search for any intended consumer / spec.** Grep `src/`, `api/`, `docs/`, `specs/`, `tasks/`
- for `skill-collection`, "skill NFT", "Metaplex", "skill collection" to see if a feature was
- planned (the name suggests a Metaplex on-chain collection of an agent's skills).
-2. **If there is no live consumer and no committed spec → delete the file.** This is the default and
- correct action; do not leave dead scaffolding.
-3. **If there is a clear, committed spec/consumer that this was meant to satisfy → implement it
- fully** (real Metaplex mint / collection read, wired into a reachable route in `vercel.json` and
- a UI entry point), per the no-stubs rule. Only do this if the scope is genuinely small and
- specified; otherwise delete and, if the feature is still wanted, it belongs in its own task —
- note that in your commit message rather than half-building it here.
-
-## Acceptance criteria
-
-- [ ] The empty file no longer exists, **or** it is a complete, reachable, real implementation
- (no stub, no `not_implemented`, wired into a route + UI).
-- [ ] No dangling import/route references remain.
-- [ ] If deleted: a one-line note in the commit message explains it was dead (no consumer/spec).
-
-## Verification
-
-1. `rg -n "skill-collection" .` returns no live code references (only, at most, this resolved state).
-2. `npm run build` (or the relevant lint/knip step) passes with no new unused-file/route warnings.
-
-## Rules
-
-Obey [CLAUDE.md](../../CLAUDE.md): delete aggressively; no stubs; if it exists, it must work and be
-reachable.
-
-## Completion protocol
-
-1. Re-read your diff (`git diff`) and confirm every line is justified.
-2. Delete this file: `tasks/week-2026-06-08/B3-dead-file-skill-collection.md`.
-3. Commit your change **and** this file's deletion together, e.g.:
- `git add -A && git commit -m "chore(api): remove dead empty skill-collection.js endpoint; close B3"`
-4. Do **not** push — the human controls pushes.
diff --git a/tasks/week-2026-06-08/B4-docs-ci-hygiene.md b/tasks/week-2026-06-08/B4-docs-ci-hygiene.md
deleted file mode 100644
index 5196eaadd..000000000
--- a/tasks/week-2026-06-08/B4-docs-ci-hygiene.md
+++ /dev/null
@@ -1,67 +0,0 @@
-# B4 — Docs + CI hygiene: document the texture worker, guard against zero-byte handlers
-
-**Track:** B — complete feature · **Priority:** P2 · **Effort:** 2–3h · **Depends on:** none
-
-## Context
-
-The API/worker audit surfaced two low-risk but real gaps:
-
-1. **`workers/texture/` is fully built** (Dockerfile, cloudbuild.yaml, ~870-LOC `main.py` mesh-
- texturing Cloud Run service) **but is undocumented in `workers/README.md`.** Every other worker
- is listed there. An undocumented-but-deployed service risks being orphaned operationally.
-2. **There is no guard against zero-byte / empty handler files.** The dispatcher-shim pattern makes
- thin files normal, so an empty file (see B3 — `api/agents/[id]/skill-collection.js`) can pass
- unnoticed. A trivial CI/lint check would catch this class permanently.
-
-## What to do
-
-### Part 1 — Document the texture worker
-
-1. Read `workers/README.md` and the existing entries' format (purpose, runtime, build/deploy
- command, any env vars).
-2. Read enough of `workers/texture/` (`main.py`, `Dockerfile`, `cloudbuild.yaml`) to describe it
- accurately: what it does (mesh texturing), its endpoint/contract, how it's built and deployed
- (Cloud Run), and which env/config it needs.
-3. Add a `workers/texture/` entry to `workers/README.md` matching the existing style exactly. Be
- accurate — no aspirational claims; describe what the code actually does.
-
-### Part 2 — CI guard for zero-byte handlers
-
-1. Find where repo checks run — `.github/workflows/` and `package.json` scripts (there are existing
- `audit:*` scripts). Pick the established mechanism; do not invent a parallel one.
-2. Add a check that **fails** if any `api/**/*.js` file is effectively empty (e.g. size < 2 bytes,
- or no `export`). A minimal approach: a small Node script under `scripts/` (e.g.
- `scripts/audit-empty-handlers.mjs`) wired into the existing prebuild/audit step and/or a CI
- workflow. It should print the offending paths and exit non-zero.
-3. Run it once to confirm it would catch the B3 file (if B3 hasn't run yet) and otherwise passes on
- the current tree. Ensure it does **not** false-positive on legitimately-tiny shim files that
- *do* export something — the check is "empty/no export," not "short."
-
-## Acceptance criteria
-
-- [ ] `workers/README.md` has an accurate `workers/texture/` entry in the existing format.
-- [ ] A committed check fails on empty/no-export `api/**/*.js` files and is wired into the repo's
- existing audit/CI flow.
-- [ ] The check passes on the current tree (after B3, or it flags exactly the B3 file if B3 is still
- open — note which in your commit).
-- [ ] No false positives on valid thin dispatcher shims.
-
-## Verification
-
-1. Run the new check locally: `node scripts/audit-empty-handlers.mjs` (or whatever you named it) —
- confirm exit code + output behave as specified.
-2. `npm run prebuild` (or the audit script you hooked into) still succeeds on the clean tree.
-3. Temporarily `touch api/_tmp-empty-test.js`, re-run, confirm it fails, then remove the temp file.
-
-## Rules
-
-Obey [CLAUDE.md](../../CLAUDE.md). Keep the repo root clean — any new script goes in `scripts/`, not
-the root. No scratch files committed.
-
-## Completion protocol
-
-1. Re-read your diff (`git diff`) and confirm every line is justified (and no temp test file remains).
-2. Delete this file: `tasks/week-2026-06-08/B4-docs-ci-hygiene.md`.
-3. Commit your changes **and** this file's deletion together, e.g.:
- `git add -A && git commit -m "chore: document texture worker + CI guard for empty api handlers; close B4"`
-4. Do **not** push — the human controls pushes.
diff --git a/tests/api/three-token-leaderboard.test.js b/tests/api/three-token-leaderboard.test.js
new file mode 100644
index 000000000..c448b7acc
--- /dev/null
+++ b/tests/api/three-token-leaderboard.test.js
@@ -0,0 +1,110 @@
+// Handler tests for GET /api/three-token/leaderboard. Helius holder data and
+// market data are mocked at the module boundary, so these exercise the ranking,
+// pagination, percentage math, and the empty-board degrade — no real RPC.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/coin/holders.js', () => ({ fetchHolderBalances: vi.fn() }));
+vi.mock('../../api/_lib/market/token-market.js', () => ({ fetchTokenMarketData: vi.fn() }));
+vi.mock('../../api/_lib/token/config.js', () => ({
+ TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+}));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+import { fetchHolderBalances } from '../../api/_lib/coin/holders.js';
+import { fetchTokenMarketData } from '../../api/_lib/market/token-market.js';
+import handler from '../../api/three-token/[action].js';
+
+function makeReq({ url, method = 'GET', headers = {} } = {}) {
+ return { url, method, headers };
+}
+function makeRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ _body: null,
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(body) { this._body = body; },
+ };
+}
+const getJson = (res) => JSON.parse(res._body);
+
+// decimals:0 keeps the atomic→display math trivial (amount === atomic units).
+function market({ supply = 1000, decimals = 0 } = {}) {
+ return { supply, decimals, price_usd: 2 };
+}
+
+describe('GET /api/three-token/leaderboard', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('ranks holders descending with rank, short wallet, and % of supply', async () => {
+ fetchHolderBalances.mockResolvedValueOnce(new Map([
+ ['walletA', 300n],
+ ['walletB', 100n],
+ ['walletC', 200n],
+ ]));
+ fetchTokenMarketData.mockResolvedValueOnce(market());
+ const res = makeRes();
+ await handler(makeReq({ url: '/api/three-token/leaderboard' }), res);
+
+ expect(res.statusCode).toBe(200);
+ const body = getJson(res);
+ expect(body.total).toBe(3);
+ expect(body.holders.map((h) => h.wallet)).toEqual(['walletA', 'walletC', 'walletB']);
+ expect(body.holders[0]).toMatchObject({ rank: 1, amount: 300, pct_of_supply: 0.3 });
+ expect(body.holders[2]).toMatchObject({ rank: 3, amount: 100, pct_of_supply: 0.1 });
+ expect(body.holders[0].wallet_short).toBeTruthy();
+ expect(res.getHeader('cache-control')).toMatch(/s-maxage=60/);
+ });
+
+ it('paginates with limit + offset and keeps absolute ranks', async () => {
+ fetchHolderBalances.mockResolvedValueOnce(new Map([
+ ['walletA', 300n],
+ ['walletB', 100n],
+ ['walletC', 200n],
+ ]));
+ fetchTokenMarketData.mockResolvedValueOnce(market());
+ const res = makeRes();
+ await handler(makeReq({ url: '/api/three-token/leaderboard?limit=2&offset=1' }), res);
+
+ const body = getJson(res);
+ expect(body.total).toBe(3);
+ expect(body.holders).toHaveLength(2);
+ expect(body.holders.map((h) => h.rank)).toEqual([2, 3]); // ranks stay absolute
+ expect(body.holders.map((h) => h.wallet)).toEqual(['walletC', 'walletB']);
+ });
+
+ it('excludes zero-balance wallets', async () => {
+ fetchHolderBalances.mockResolvedValueOnce(new Map([
+ ['walletA', 300n],
+ ['walletZero', 0n],
+ ]));
+ fetchTokenMarketData.mockResolvedValueOnce(market());
+ const res = makeRes();
+ await handler(makeReq({ url: '/api/three-token/leaderboard' }), res);
+ const body = getJson(res);
+ expect(body.total).toBe(1);
+ expect(body.holders.map((h) => h.wallet)).toEqual(['walletA']);
+ });
+
+ it('nulls percentages when market supply is unavailable', async () => {
+ fetchHolderBalances.mockResolvedValueOnce(new Map([['walletA', 300n]]));
+ fetchTokenMarketData.mockResolvedValueOnce(null);
+ const res = makeRes();
+ await handler(makeReq({ url: '/api/three-token/leaderboard' }), res);
+ const body = getJson(res);
+ expect(body.holders[0].pct_of_supply).toBeNull();
+ });
+
+ it('degrades to an empty board (200, not 500) when Helius fails', async () => {
+ fetchHolderBalances.mockRejectedValueOnce(new Error('helius unconfigured'));
+ const res = makeRes();
+ await handler(makeReq({ url: '/api/three-token/leaderboard' }), res);
+ expect(res.statusCode).toBe(200);
+ const body = getJson(res);
+ expect(body.holders).toEqual([]);
+ expect(body.total).toBe(0);
+ });
+});
diff --git a/tests/db-retry.test.js b/tests/db-retry.test.js
new file mode 100644
index 000000000..bb7c0bf5d
--- /dev/null
+++ b/tests/db-retry.test.js
@@ -0,0 +1,57 @@
+// Unit tests for the DB connection-retry helper. Pure logic — `withDbRetry`
+// takes a thunk, so no DB or network mocking is needed.
+
+import { describe, it, expect, vi } from 'vitest';
+import { withDbRetry } from '../api/_lib/db-retry.js';
+
+function transientError() {
+ // Shape Neon's HTTP driver produces on a cold-start / network blip.
+ return new Error('NeonDbError: Error connecting to database: fetch failed');
+}
+
+function constraintError() {
+ // A real SQL error carries a Postgres SQLSTATE and a deterministic message.
+ return Object.assign(new Error('duplicate key value violates unique constraint "agent_identities_pkey"'), {
+ code: '23505',
+ });
+}
+
+describe('withDbRetry', () => {
+ it('returns the result without retrying when the operation succeeds', async () => {
+ const run = vi.fn().mockResolvedValue('ok');
+ await expect(withDbRetry(run)).resolves.toBe('ok');
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries a transient connection error and succeeds on the next attempt', async () => {
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(transientError())
+ .mockResolvedValueOnce('recovered');
+ await expect(withDbRetry(run)).resolves.toBe('recovered');
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+
+ it('does NOT retry a SQL/constraint error — it fails fast', async () => {
+ const err = constraintError();
+ const run = vi.fn().mockRejectedValue(err);
+ await expect(withDbRetry(run)).rejects.toBe(err);
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+
+ it('gives up after the attempt cap on a persistent transient failure', async () => {
+ const run = vi.fn().mockRejectedValue(transientError());
+ await expect(withDbRetry(run)).rejects.toThrow(/fetch failed/);
+ expect(run).toHaveBeenCalledTimes(3); // MAX_DB_ATTEMPTS
+ });
+
+ it('unwraps a transient cause carried on sourceError', async () => {
+ // NeonDbError nests the underlying fetch failure on `sourceError`.
+ const wrapped = Object.assign(new Error('query failed'), {
+ sourceError: new Error('fetch failed'),
+ });
+ const run = vi.fn().mockRejectedValueOnce(wrapped).mockResolvedValueOnce('ok');
+ await expect(withDbRetry(run)).resolves.toBe('ok');
+ expect(run).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/workers/README.md b/workers/README.md
index 8036384bd..c72fb90f7 100644
--- a/workers/README.md
+++ b/workers/README.md
@@ -42,6 +42,21 @@ One-click geometric stylization filters — turns any mesh into a stylized varia
### `segment/` (CPU)
Splits a 3D model into meaningful, separable parts with clean boundaries (head/torso/limbs on a character; body/wheels/glass on a vehicle) using pure geometry — trimesh + numpy + scipy, no GPU, no model inference. The engine combines connected-component splitting (physically disjoint shells become parts immediately) with the **minima rule** — region growing that cuts the face-adjacency graph at concave creases, where human perception sees part seams — then merges shards and caps the part count to a meaningful handful. Each part is named by its spatial region, tinted a distinct colour, and emitted as a separate named node in the output GLB so it can be hidden, recoloured, replaced, or exported individually. `POST /segment` (`{ mesh, method?, max_parts?, min_part_faces?, crease_angle?, only_part? }`) -> `202 { task_id }`, `GET /tasks/:id` -> `{ status, result_url?, manifest_url?, parts?, part_count?, source_faces?, method?, error? }` (the parts manifest carries each part's id, name, region, bbox, centroid, face/vertex counts, and colour), `GET /health`; bearer-auth on `/segment` + `/tasks`. Routed via `api/_providers/gcp.js` (`segment` mode, `GCP_SEGMENT_URL`); exposed to the web at `/api/forge-segment` (and the `/segment` Parts Studio viewer) and to agents over MCP as the x402-priced `segment_model`.
+## Text-guided texturing (Cloud Run, GPU L4)
+
+### `texture/`
+Two capabilities on one model server. **Full retexture** (`POST /texture`): takes an untextured or poorly-textured GLB plus a text prompt, renders depth maps from 8 canonical viewpoints (pyrender), generates coherent texture views with SDXL Img2Img + ControlNet-Depth, back-projects them onto the UV map (pytorch3d), blends overlaps by distance-weighted confidence, and bakes a final textured GLB. **Magic-brush region retexture** (`POST /retexture_region`): SDXL inpainting of only a UV-space masked region of an existing atlas, feathering the seam so untouched texels stay bit-identical across repeated passes. API: `POST /texture` (`{ mesh, prompt, negative_prompt?, num_views?, texture_size? }`) and `POST /retexture_region` (`{ mesh, prompt, mask_b64?|mask?, color?, strength?, feather?, seed? }`) -> `202 { task_id }`, `GET /tasks/:id`, `GET /health`; bearer-auth via `API_KEY`. Env: `API_KEY`, `GCS_BUCKET` (required), `SDXL_MODEL`, `CONTROLNET_MODEL`. Routed via `api/_providers/gcp.js` (`retex` / `retex_region` modes, `GCP_TEXTURE_URL`); exposed to the web at `/api/studio/retexture-region`, to agents over MCP as the studio retexture tool, and x402-priced in `api/_lib/pump-pricing.js`.
+
+## Mesh processing (Cloud Run, CPU)
+
+### `remesh/`
+Mesh processing — remesh, simplify, repair, retopologize, and convert 3D files. Wraps trimesh + open3d + QuadriFlow + xatlas, with headless Blender (`bpy`) for FBX export. Handles format conversion (GLB ↔ OBJ ↔ FBX ↔ STL ↔ PLY ↔ USDZ ↔ 3MF); a `convert` of a rigged GLB keeps its bone hierarchy, skin weights, and blendshapes (Blender path — trimesh has no FBX writer). No GPU. `GET /tasks/:id`, `GET /health`; routed via `api/_providers/gcp.js` (`remesh` mode, `GCP_REMESH_URL`).
+
+## Image preprocessing (Cloud Run, CPU)
+
+### `rembg/`
+Background removal — strips backgrounds from images using BRIA RMBG-2.0 (Apache-2.0) with rembg's U2Net as a fast CPU fallback. `POST /remove` (`{ image: data-uri|url, model?: "rmbg2"|"u2net"|"isnet" }`) -> `202 { task_id, status }`, `GET /tasks/:id`, `GET /health`. Routed via `api/_providers/gcp.js` (`rembg` mode, `GCP_REMBG_URL`); used to clean source photos before reconstruction.
+
## Cloudflare Worker
### `pump-fun-mcp/`