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.

docs(stage): say that the host's regulars memory counts verified tips only

nirholasa0d767a4ea73
diff --git a/docs/stage.md b/docs/stage.md
index 6c21504d7..73dd181cd 100644
--- a/docs/stage.md
+++ b/docs/stage.md
@@ -54,7 +54,7 @@ The room performs one beat at a time (a tip storm coalesces into a single in-fli
### The host's words
-The words are not canned and not templated. Each beat is sent to [`/api/stage/host`](../api/stage/host.js), which builds a prompt from the agent's own persona, the live show context the room supplies (beat kind, audience size, tip standings, the fresh tip, the queued question), and the stage's returning regulars, then completes it over the platform LLM chain. Regulars are real: the top five tippers across this stage's prior shows, so a returning face gets greeted by name.
+The words are not canned and not templated. Each beat is sent to [`/api/stage/host`](../api/stage/host.js), which builds a prompt from the agent's own persona, the live show context the room supplies (beat kind, audience size, tip standings, the fresh tip, the queued question), and the stage's returning regulars, then completes it over the platform LLM chain. Regulars are real: the top five tippers across this stage's prior shows, so a returning face gets greeted by name. Only verified tips count toward that memory, the same rule the public leaderboard follows, so a name attached to an unproven settlement is never spoken to the room.
The system prompt constrains the host hard, because every line is spoken aloud and shown as a caption: one or two short sentences, in character, no lists, no stage directions, no emoji, and $THREE is the only coin the host ever names. The completion is collapsed to a single clean line with any leaked speaker label stripped.
diff --git a/prompts/swarm-100/api-top-09.md b/prompts/swarm-100/api-top-09.md
deleted file mode 100644
index 17cc19d47..000000000
--- a/prompts/swarm-100/api-top-09.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/*.js batch 09 (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/forge.js
-- api/forged.js
-- api/galaxy.js
-- api/garment-forge.js
-- api/glb.js
-- api/gpt-forge.js
-- api/healthz.js
-- api/home-stats.js
-- api/ibm-mcp.js
-- api/img.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-09.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/api/forged-feed.test.js b/tests/api/forged-feed.test.js
new file mode 100644
index 000000000..7d76767ff
--- /dev/null
+++ b/tests/api/forged-feed.test.js
@@ -0,0 +1,156 @@
+// Tests for /api/forged, the public feed behind the /forged gallery: 3D props
+// the platform's autonomous agents bought with real on-chain USDC via x402.
+//
+// The feed is provenance-carrying (payer wallet, price, settlement signature),
+// so the shaping is the contract: atomic amounts become USDC, a signature
+// becomes an explorer link, a GLB becomes a viewer link, and a row with none of
+// those still renders. Network-free: the database, cache and rate limiter are
+// mocked; what is under test is validation, shaping and the caching contract.
+
+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
+import { createServer } from 'node:http';
+
+const ROWS = [
+ {
+ id: 141,
+ ts: '2026-08-13T05:24:30.894Z',
+ prompt: 'a go-kart with roll bar, 3D prop',
+ category: 'vehicle',
+ tier: 'standard',
+ status: 'done',
+ glb_url: 'https://models.example/forge/go-kart.glb',
+ novelty: '0.09952',
+ cluster_id: 2,
+ tx_sig: 'SigOne',
+ payer: 'X4o2UuVNMxnrgkzVy97kPF5gmS6CLRCVJGB48VastML',
+ amount_atomic: '150000',
+ },
+ // A queued row: no GLB, no settlement yet. Every derived field must be null
+ // rather than a broken link.
+ {
+ id: 142,
+ ts: '2026-08-13T06:00:00.000Z',
+ prompt: 'a sci-fi cargo pod, 3D prop',
+ category: 'container',
+ tier: 'draft',
+ status: 'queued',
+ glb_url: null,
+ novelty: null,
+ cluster_id: null,
+ tx_sig: null,
+ payer: null,
+ amount_atomic: null,
+ },
+];
+
+const STATS = [
+ { total: 2, done: 1, queued: 1, spent_atomic: '150000', latest_ts: '2026-08-13T06:00:00.000Z' },
+];
+const PER_CATEGORY = [{ category: 'vehicle', c: 1 }];
+
+// The handler fires three queries in order (rows, stats, per-category); serve
+// them positionally so each response lands where the handler expects it.
+let queryCount = 0;
+let dbError = null;
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => {
+ if (dbError) throw dbError;
+ queryCount += 1;
+ if (queryCount === 1) return ROWS;
+ if (queryCount === 2) return STATS;
+ return PER_CATEGORY;
+ }),
+ isDbUnavailableError: (err) => err?.code === 'db_down',
+}));
+
+// Cache always misses so every case exercises the real query path, and records
+// what the handler tried to store.
+const cacheWrites = [];
+vi.mock('../../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async () => null),
+ cacheSet: vi.fn(async (key, value, ttl) => {
+ cacheWrites.push({ key, value, ttl });
+ }),
+}));
+
+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/forged.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(() => {
+ queryCount = 0;
+ dbError = null;
+ cacheWrites.length = 0;
+});
+
+describe('/api/forged feed', () => {
+ it('shapes a paid prop into its provenance: USDC price, explorer link, viewer link', async () => {
+ const r = await fetch(`${base}/api/forged?limit=2`);
+ expect(r.status).toBe(200);
+ expect(r.headers.get('cache-control')).toContain('max-age=20');
+
+ const body = await r.json();
+ const [paid, queued] = body.props;
+
+ expect(paid.price_usdc).toBe(0.15);
+ expect(paid.payer_short).toBe('X4o2Uu…stML');
+ expect(paid.explorer_url).toContain('SigOne');
+ expect(paid.viewer_url).toBe(
+ `/app?src=${encodeURIComponent('https://models.example/forge/go-kart.glb')}`,
+ );
+ expect(paid.novelty).toBe(0.09952);
+
+ // A row with no settlement and no model yields nulls, never a dead link.
+ expect(queued.price_usdc).toBeNull();
+ expect(queued.payer_short).toBeNull();
+ expect(queued.explorer_url).toBeNull();
+ expect(queued.viewer_url).toBeNull();
+
+ expect(body.stats).toMatchObject({ total: 2, done: 1, queued: 1, spent_usdc: 0.15 });
+ expect(body.stats.categories).toEqual({ vehicle: 1 });
+ });
+
+ it('caches the shaped payload under a key scoped to every filter', async () => {
+ await fetch(`${base}/api/forged?category=vehicle&status=all&limit=7`);
+ expect(cacheWrites).toHaveLength(1);
+ expect(cacheWrites[0].key).toBe('forged:feed:vehicle:all:7');
+ expect(cacheWrites[0].ttl).toBe(20);
+ });
+
+ it('rejects a category that matches no prop family, naming the real ones', async () => {
+ const r = await fetch(`${base}/api/forged?category=not-a-family`);
+ expect(r.status).toBe(400);
+ const body = await r.json();
+ expect(body.error).toBe('invalid_category');
+ expect(body.error_description).toContain('vehicle');
+ // Validation runs before any query: a bad filter costs no database work.
+ expect(queryCount).toBe(0);
+ });
+
+ it('answers a brief database outage with a retryable 503, not a 500', async () => {
+ dbError = Object.assign(new Error('connection terminated'), { code: 'db_down' });
+ const r = await fetch(`${base}/api/forged`);
+ expect(r.status).toBe(503);
+ expect(r.headers.get('retry-after')).toBe('5');
+ expect((await r.json()).error).toBe('db_unavailable');
+ });
+
+ it('is read-only: anything but GET is 405', async () => {
+ const r = await fetch(`${base}/api/forged`, { method: 'POST' });
+ expect(r.status).toBe(405);
+ });
+});
diff --git a/tests/api/home-stats.test.js b/tests/api/home-stats.test.js
new file mode 100644
index 000000000..ce7ee5f8d
--- /dev/null
+++ b/tests/api/home-stats.test.js
@@ -0,0 +1,89 @@
+// Tests for /api/home-stats, the live "trusted by" numbers on the home page.
+//
+// The contract that matters here is honesty: the strip renders real Neon counts
+// or it renders nothing. A database outage must never degrade into fabricated
+// or zeroed numbers, so the failure path answers { available: false } and the
+// home page hides the strip. Network-free: the database and rate limiter are
+// mocked; what is under test is the payload shape, the caching contract and
+// that failure path.
+
+import { describe, it, expect, vi, beforeAll, afterAll, beforeEach } from 'vitest';
+import { createServer } from 'node:http';
+
+// One count per query, in the order the handler fires them: agents, on-chain
+// agents, widgets, chains, attestations, forge models.
+const COUNTS = [3167, 148470, 613, 18, 3000, 14553];
+
+let queryCount = 0;
+let dbError = null;
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => {
+ if (dbError) throw dbError;
+ const n = COUNTS[queryCount] ?? 0;
+ queryCount += 1;
+ return [{ n }];
+ }),
+}));
+
+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/home-stats.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(() => {
+ queryCount = 0;
+ dbError = null;
+});
+
+describe('/api/home-stats', () => {
+ it('serves every real count the home strip renders, edge-cached', async () => {
+ const r = await fetch(`${base}/api/home-stats`);
+ expect(r.status).toBe(200);
+ expect(r.headers.get('cache-control')).toContain('s-maxage=60');
+ expect(r.headers.get('cache-control')).toContain('stale-while-revalidate=300');
+
+ const body = await r.json();
+ expect(body).toMatchObject({
+ available: true,
+ agents: 3167,
+ onchain_agents: 148470,
+ widgets: 613,
+ chains: 18,
+ attestations: 3000,
+ forge_models: 14553,
+ });
+ // Each metric is its own count, so a dropped or reordered query shows up
+ // as a wrong number rather than silently.
+ expect(queryCount).toBe(6);
+ expect(Number.isNaN(Date.parse(body.updated_at))).toBe(false);
+ });
+
+ it('reports unavailable rather than fabricating numbers when the database is down', async () => {
+ dbError = new Error('connection terminated unexpectedly');
+ const r = await fetch(`${base}/api/home-stats`);
+ // 200 with an explicit flag: the home page hides the strip on this, and a
+ // marketing metric is never worth flapping the page into an error state.
+ expect(r.status).toBe(200);
+ expect(await r.json()).toEqual({ available: false, reason: 'db_unavailable' });
+ // The shortened cache window lets a recovered database show up quickly.
+ expect(r.headers.get('cache-control')).toContain('s-maxage=15');
+ });
+
+ it('is read-only: anything but GET is 405', async () => {
+ const r = await fetch(`${base}/api/home-stats`, { method: 'POST' });
+ expect(r.status).toBe(405);
+ });
+});