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(agora): tell a rate-limited Agora reader how long to wait, and cover the act boundary

nirholas88d513b1bba6
diff --git a/api/agora/[action].js b/api/agora/[action].js
index 44eb3d570..5a5be0d6b 100644
--- a/api/agora/[action].js
+++ b/api/agora/[action].js
@@ -27,7 +27,7 @@ import { PublicKey } from '@solana/web3.js';
import { getAgent, getTaskLifecycleSummary, deriveTaskPda } from '@tetsuo-ai/sdk';
import { createHash } from 'node:crypto';
-import { cors, json, method, error, wrap, serverError } from '../_lib/http.js';
+import { cors, json, method, error, rateLimited, wrap, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { isUuid } from '../_lib/validate.js';
@@ -673,7 +673,11 @@ export default wrap(async (req, res) => {
if (!method(req, res, route.methods)) return;
const rl = await limits.publicIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ // Match the sibling AgenC read model: a 429 here must carry retry-after +
+ // the limiter's own reason, so a poller (the 3D Commons refreshes board and
+ // pulse on a timer) can back off correctly and can tell a genuine quota hit
+ // from a fail-closed limiter outage.
+ if (!rl.success) return rateLimited(res, rl);
try {
return await route.fn(req, res);
diff --git a/prompts/swarm-100/api-agora-01.md b/prompts/swarm-100/api-agora-01.md
deleted file mode 100644
index 2f1ae3098..000000000
--- a/prompts/swarm-100/api-agora-01.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# API audit: api/agora batch 01 (2 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/agora/[action].js
-- api/agora/act.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-agora-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/agora-act-validation.test.js b/tests/agora-act-validation.test.js
new file mode 100644
index 000000000..64ceac901
--- /dev/null
+++ b/tests/agora-act-validation.test.js
@@ -0,0 +1,203 @@
+/**
+ * Agora human actions (api/agora/act.js): the boundary every mutating request
+ * crosses BEFORE any wallet, escrow or chain work happens.
+ *
+ * Two id kinds arrive from the client and both used to be handed straight to a
+ * layer that cannot cope with a malformed one. A citizen id goes to a Postgres
+ * `uuid` column (a non-uuid raises 22P02 and the request 500s) and a task PDA
+ * goes to `new PublicKey()` (a non-base58 string throws, which surfaced as a
+ * 502 for claim and a 500 for complete). A typo is a user mistake, so it must
+ * read as a designed 4xx, and it must be caught before the request registers
+ * the citizen on-chain for work that could never succeed.
+ *
+ * We drive the REAL wrapped handler and mock only the I/O boundary (auth, the
+ * rate limiter, the DB, the citizen/chain helpers and the spend policy) so no
+ * mock ships in app code and the handler's own branching runs unchanged.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const H = vi.hoisted(() => ({
+ citizenRows: [],
+ ensureCalls: 0,
+ registerCalls: 0,
+}));
+
+vi.mock('../api/_lib/zauth.js', () => ({ instrument: () => false, drain: async () => {} }));
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+vi.mock('../api/_lib/db.js', () => {
+ const sql = (strings, ...vals) => {
+ if (!Array.isArray(strings)) return Promise.resolve({ __frag: true });
+ const q = strings.join(' ').toLowerCase();
+ if (q.includes('from users')) {
+ return Promise.resolve([{ id: 'u1', display_name: 'QA', username: 'qa', avatar_url: null }]);
+ }
+ if (q.includes('from agora_citizens')) {
+ // agora_citizens.id is a uuid column, and Postgres does not coerce: a
+ // malformed literal raises 22P02 rather than matching nothing. Emulate
+ // that, or a guard that stopped working would still look green here.
+ if (q.includes('where id =') && !UUID_RE.test(String(vals[0]))) {
+ return Promise.reject(Object.assign(
+ new Error(`invalid input syntax for type uuid: "${vals[0]}"`), { code: '22P02' },
+ ));
+ }
+ return Promise.resolve(H.citizenRows);
+ }
+ return Promise.resolve([]);
+ };
+ return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
+});
+
+vi.mock('../api/_lib/labor-auth.js', () => ({
+ authWrite: async () => ({ userId: 'u1', session: false }),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '1.2.3.4',
+ limits: { mcpAgentPay: async () => ({ success: true, limit: 30, remaining: 29, reset: Date.now() + 1000 }) },
+}));
+
+vi.mock('../api/_lib/token/config.js', () => ({
+ TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',
+ TOKEN_DECIMALS: 6,
+}));
+
+vi.mock('../api/_lib/agora-policy.js', () => ({
+ resolveCluster: () => 'devnet',
+ reservePostSpend: async () => ({ ok: true, reservationId: 'hold-1' }),
+ settlePostSpend: async () => {},
+ releasePostSpend: async () => {},
+}));
+
+vi.mock('../api/_lib/agora-human.js', () => ({
+ PROFESSION_BITS: {
+ fetcher: 0, sculptor: 1, scribe: 2, cartographer: 3,
+ crier: 4, appraiser: 5, verifier: 6, namekeeper: 7,
+ },
+ THREE_ATOMICS_PER_TOKEN: 1000000n,
+ ensureHumanCitizen: async () => {
+ H.ensureCalls += 1;
+ return {
+ citizen: {
+ id: '11111111-1111-4111-8111-111111111111',
+ display_name: 'QA', avatar_url: null, status: 'idle',
+ agenc_cluster: 'devnet', agenc_agent_pda: null, reputation: 0,
+ tasks_posted: 0, tasks_completed: 0, earned_three_atomic: '0',
+ home_x: 0, home_z: 0, pos_x: 0, pos_z: 0, meta: {},
+ },
+ created: false,
+ };
+ },
+ ensureRegistered: async () => {
+ H.registerCalls += 1;
+ throw new Error('ensureRegistered must not run for a malformed request');
+ },
+ ensureDevnetBalance: async () => {},
+ requireFunded: async () => {},
+ projectActivity: async () => {},
+ bumpCitizenStats: async () => {},
+ citizenBalances: async () => ({ sol: 0, three: null, address: null }),
+ professionToCapabilityBits: () => 1n,
+ rewardLabel: () => '0.0010 SOL',
+ proofHashFor: () => 'f'.repeat(64),
+ sendOnchainAttestation: async () => { throw new Error('attestation must not run for a malformed request'); },
+ explorerTx: (sig) => `https://explorer.solana.com/tx/${sig}?cluster=devnet`,
+ recoverTimedOutSignature: async () => null,
+ findCompletionSignature: async () => null,
+}));
+
+import handler from '../api/agora/act.js';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: undefined,
+ ended: false,
+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },
+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },
+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },
+ end(b) { this.body = b; this.ended = true; },
+ get headersSent() { return this.ended; },
+ get writableEnded() { return this.ended; },
+ };
+}
+
+async function act(body) {
+ const req = {
+ method: 'POST',
+ url: '/api/agora/act',
+ headers: { 'content-type': 'application/json' },
+ query: {},
+ body,
+ };
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ H.citizenRows = [];
+ H.ensureCalls = 0;
+ H.registerCalls = 0;
+});
+
+describe('act: citizen ids that are not uuids', () => {
+ it('404s a hire whose citizenId is not a uuid (never a 500 from Postgres 22P02)', async () => {
+ const r = await act({ action: 'hire', title: 'QA hire probe', citizenId: 'not-a-uuid', rewardSol: 0.001 });
+ expect(r.status).toBe(404);
+ expect(r.body.error).toBe('not_found');
+ });
+
+ it('still looks up a well-formed citizenId, so the guard does not over-reject', async () => {
+ H.citizenRows = [];
+ const r = await act({
+ action: 'hire', title: 'QA hire probe',
+ citizenId: '22222222-2222-4222-8222-222222222222', rewardSol: 0.001,
+ });
+ // Reached the DB and found nobody: the same 404, but by lookup, not by shape.
+ expect(r.status).toBe(404);
+ expect(H.ensureCalls).toBe(0);
+ });
+
+ it('404s a vouch whose subjectCitizenId is not a uuid', async () => {
+ const r = await act({ action: 'vouch', subjectCitizenId: 'not-a-uuid' });
+ expect(r.status).toBe(404);
+ expect(r.body.error).toBe('not_found');
+ expect(H.ensureCalls).toBe(0);
+ });
+});
+
+describe('act: task PDAs that are not base58', () => {
+ it('400s a claim with a malformed taskPda before any wallet or chain work', async () => {
+ const r = await act({ action: 'claim', taskPda: 'not-a-pubkey' });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toBe('validation_error');
+ expect(H.ensureCalls).toBe(0);
+ expect(H.registerCalls).toBe(0);
+ });
+
+ it('400s a complete with a malformed taskPda before any wallet or chain work', async () => {
+ const r = await act({ action: 'complete', taskPda: 'not-a-pubkey', deliverable: 'https://three.ws/x.glb' });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toBe('validation_error');
+ expect(H.ensureCalls).toBe(0);
+ expect(H.registerCalls).toBe(0);
+ });
+
+ it('keeps the empty-taskPda message distinct from the malformed one', async () => {
+ const r = await act({ action: 'claim' });
+ expect(r.status).toBe(400);
+ expect(r.body.error_description).toMatch(/required/);
+ });
+});
+
+describe('act: router', () => {
+ it('400s an unknown action', async () => {
+ const r = await act({ action: 'frobnicate' });
+ expect(r.status).toBe(400);
+ expect(r.body.error).toBe('validation_error');
+ });
+});
diff --git a/tests/agora-read-model.test.js b/tests/agora-read-model.test.js
index b22c5b6cf..228892676 100644
--- a/tests/agora-read-model.test.js
+++ b/tests/agora-read-model.test.js
@@ -127,11 +127,15 @@ describe('router', () => {
expect(status).toBe(405);
});
- it('429s when the rate limiter denies', async () => {
+ it('429s when the rate limiter denies, with a retry-after a poller can obey', async () => {
H.rlSuccess = false;
- const { status, body } = await call('pulse');
+ const { status, body, res } = await call('pulse');
expect(status).toBe(429);
expect(body.error).toBe('rate_limited');
+ // The 3D Commons polls board + pulse on a timer, so the 429 has to say how
+ // long to wait rather than leaving the client to guess.
+ expect(Number(res.getHeader('retry-after'))).toBeGreaterThan(0);
+ expect(body.retry_after).toBeGreaterThan(0);
});
});